diff --git a/.buildkite/pipelines/performance/daily.yml b/.buildkite/pipelines/performance/daily.yml index 10f137a5c5088..ea7e406ba63d8 100644 --- a/.buildkite/pipelines/performance/daily.yml +++ b/.buildkite/pipelines/performance/daily.yml @@ -20,6 +20,12 @@ steps: depends_on: build key: tests timeout_in_minutes: 60 + retry: + automatic: + - exit_status: '-1' + limit: 3 + - exit_status: '*' + limit: 1 - label: '🚢 Performance Tests dataset extraction for scalability benchmarking' command: .buildkite/scripts/steps/functional/scalability_dataset_extraction.sh diff --git a/.buildkite/scripts/common/util.sh b/.buildkite/scripts/common/util.sh index 1ce05856ec6b7..748babfc0650b 100755 --- a/.buildkite/scripts/common/util.sh +++ b/.buildkite/scripts/common/util.sh @@ -39,6 +39,7 @@ check_for_changed_files() { C_RESET='\033[0m' # Reset color SHOULD_AUTO_COMMIT_CHANGES="${2:-}" + CUSTOM_FIX_MESSAGE="${3:-}" GIT_CHANGES="$(git ls-files --modified -- . ':!:.bazelrc')" if [ "$GIT_CHANGES" ]; then @@ -75,7 +76,11 @@ check_for_changed_files() { else echo -e "\n${RED}ERROR: '$1' caused changes to the following files:${C_RESET}\n" echo -e "$GIT_CHANGES\n" - echo -e "\n${YELLOW}TO FIX: Run '$1' locally, commit the changes and push to your branch${C_RESET}\n" + if [ "$CUSTOM_FIX_MESSAGE" ]; then + echo "$CUSTOM_FIX_MESSAGE" + else + echo -e "\n${YELLOW}TO FIX: Run '$1' locally, commit the changes and push to your branch${C_RESET}\n" + fi exit 1 fi fi diff --git a/.buildkite/scripts/steps/checks.sh b/.buildkite/scripts/steps/checks.sh index 4af63d318c804..0e11ac04eea1d 100755 --- a/.buildkite/scripts/steps/checks.sh +++ b/.buildkite/scripts/steps/checks.sh @@ -8,6 +8,7 @@ export DISABLE_BOOTSTRAP_VALIDATION=false .buildkite/scripts/steps/checks/precommit_hook.sh .buildkite/scripts/steps/checks/ftr_configs.sh .buildkite/scripts/steps/checks/bazel_packages.sh +.buildkite/scripts/steps/checks/event_log.sh .buildkite/scripts/steps/checks/telemetry.sh .buildkite/scripts/steps/checks/ts_projects.sh .buildkite/scripts/steps/checks/jest_configs.sh diff --git a/.buildkite/scripts/steps/checks/event_log.sh b/.buildkite/scripts/steps/checks/event_log.sh new file mode 100755 index 0000000000000..dc9c01902c010 --- /dev/null +++ b/.buildkite/scripts/steps/checks/event_log.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +set -euo pipefail + +source .buildkite/scripts/common/util.sh + +echo --- Check Event Log Schema + +# event log schema is pinned to a specific version of ECS +ECS_STABLE_VERSION=1.8 +git clone --depth 1 -b $ECS_STABLE_VERSION https://github.com/elastic/ecs.git ../ecs + +node x-pack/plugins/event_log/scripts/create_schemas.js + +check_for_changed_files 'node x-pack/plugins/event_log/scripts/create_schemas.js' false 'Follow the directions in x-pack/plugins/event_log/generated/README.md to make schema changes for the event log.' diff --git a/.buildkite/scripts/steps/functional/performance_playwright.sh b/.buildkite/scripts/steps/functional/performance_playwright.sh index 111825b3b03a0..6f0399b2de90d 100644 --- a/.buildkite/scripts/steps/functional/performance_playwright.sh +++ b/.buildkite/scripts/steps/functional/performance_playwright.sh @@ -11,26 +11,9 @@ is_test_execution_step rm -rf "$KIBANA_BUILD_LOCATION" .buildkite/scripts/download_build_artifacts.sh -echo "--- 🦺 Starting Elasticsearch" - -node scripts/es snapshot& -export esPid=$! -trap 'kill ${esPid}' EXIT - -export TEST_ES_URL=http://elastic:changeme@localhost:9200 -export TEST_ES_DISABLE_STARTUP=true - -# Pings the es server every second for up to 2 minutes until it is green -curl \ - --fail \ - --silent \ - --retry 120 \ - --retry-delay 1 \ - --retry-connrefused \ - -XGET "${TEST_ES_URL}/_cluster/health?wait_for_nodes=>=1&wait_for_status=yellow" \ - > /dev/null - -echo "✅ ES is ready and will continue to run in the background" +function is_running { + kill -0 "$1" &>/dev/null +} # unset env vars defined in other parts of CI for automatic APM collection of # Kibana. We manage APM config in our FTR config and performance service, and @@ -46,29 +29,100 @@ unset ELASTIC_APM_SERVER_URL unset ELASTIC_APM_SECRET_TOKEN unset ELASTIC_APM_GLOBAL_LABELS -journeys=("login" "ecommerce_dashboard" "flight_dashboard" "web_logs_dashboard" "promotion_tracking_dashboard" "many_fields_discover" "data_stress_test_lens") +# `kill $esPid` doesn't work, seems that kbn-es doesn't listen to signals correctly, this does work +trap 'killall node -q' EXIT + +export TEST_ES_URL=http://elastic:changeme@localhost:9200 +export TEST_ES_DISABLE_STARTUP=true + +echo "--- determining which journeys to run" + +journeys=$(buildkite-agent meta-data get "failed-journeys" --default '') +if [ "$journeys" != "" ]; then + echo "re-running failed journeys:${journeys}" +else + paths=() + for path in x-pack/performance/journeys/*; do + paths+=("$path") + done + journeys=$(printf "%s\n" "${paths[@]}") + echo "running discovered journeys:${journeys}" +fi + +# track failed journeys here which might get written to metadata +failedJourneys=() + +while read -r journey; do + if [ "$journey" == "" ]; then + continue; + fi + + echo "--- $journey - 🔎 Start es" -for journey in "${journeys[@]}"; do - set +e + node scripts/es snapshot& + export esPid=$! + + # Pings the es server every second for up to 2 minutes until it is green + curl \ + --fail \ + --silent \ + --retry 120 \ + --retry-delay 1 \ + --retry-connrefused \ + -XGET "${TEST_ES_URL}/_cluster/health?wait_for_nodes=>=1&wait_for_status=yellow" \ + > /dev/null + + echo "✅ ES is ready and will run in the background" phases=("WARMUP" "TEST") + status=0 for phase in "${phases[@]}"; do echo "--- $journey - $phase" export TEST_PERFORMANCE_PHASE="$phase" + + set +e node scripts/functional_tests \ - --config "x-pack/performance/journeys/$journey.ts" \ + --config "$journey" \ --kibana-install-dir "$KIBANA_BUILD_LOCATION" \ --debug \ --bail - status=$? + set -e + if [ $status -ne 0 ]; then + failedJourneys+=("$journey") echo "^^^ +++" echo "❌ FTR failed with status code: $status" - exit 1 + break + fi + done + + # remove trap, we're manually shutting down + trap - EXIT; + + echo "--- $journey - 🔎 Shutdown ES" + killall node + echo "waiting for $esPid to exit gracefully"; + + timeout=30 #seconds + dur=0 + while is_running $esPid; do + sleep 1; + ((dur=dur+1)) + if [ $dur -ge $timeout ]; then + echo "es still running after $dur seconds, killing ES and node forcefully"; + killall -SIGKILL java + killall -SIGKILL node + sleep 5; fi done +done <<< "$journeys" + +echo "--- report/record failed journeys" +if [ "${failedJourneys[*]}" != "" ]; then + buildkite-agent meta-data set "failed-journeys" "$(printf "%s\n" "${failedJourneys[@]}")" - set -e -done + echo "failed journeys: ${failedJourneys[*]}" + exit 1 +fi diff --git a/.buildkite/scripts/steps/functional/scalability_dataset_extraction.sh b/.buildkite/scripts/steps/functional/scalability_dataset_extraction.sh index a2b81f538b92b..aff087005ac5c 100755 --- a/.buildkite/scripts/steps/functional/scalability_dataset_extraction.sh +++ b/.buildkite/scripts/steps/functional/scalability_dataset_extraction.sh @@ -46,8 +46,13 @@ cd "${OUTPUT_DIR}/.." gsutil -m cp -r "${BUILD_ID}" "${GCS_BUCKET}" cd - -echo "--- Promoting '${BUILD_ID}' dataset to LATEST" -cd "${OUTPUT_DIR}/.." -echo "${BUILD_ID}" > latest -gsutil cp latest "${GCS_BUCKET}" -cd - +if [ "$BUILDKITE_PIPELINE_SLUG" == "kibana-single-user-performance" ]; then + echo "--- Promoting '${BUILD_ID}' dataset to LATEST" + cd "${OUTPUT_DIR}/.." + echo "${BUILD_ID}" > latest + gsutil cp latest "${GCS_BUCKET}" + cd - +else + echo "--- Skipping promotion of dataset to LATEST" + echo "$BUILDKITE_PIPELINE_SLUG is not 'kibana-single-user-performance', so skipping" +fi diff --git a/.buildkite/scripts/steps/storybooks/build_and_upload.ts b/.buildkite/scripts/steps/storybooks/build_and_upload.ts index 8575ee683d82f..dcceca7848910 100644 --- a/.buildkite/scripts/steps/storybooks/build_and_upload.ts +++ b/.buildkite/scripts/steps/storybooks/build_and_upload.ts @@ -41,6 +41,7 @@ const STORYBOOKS = [ 'presentation', 'security_solution', 'shared_ux', + 'triggers_actions_ui', 'ui_actions_enhanced', 'unified_search', ]; diff --git a/.eslintrc.js b/.eslintrc.js index df107348cfafc..902643dbe5066 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1314,7 +1314,7 @@ module.exports = { { // typescript for front and back end files: [ - 'x-pack/plugins/{alerting,stack_alerts,stack_connectors,actions,task_manager,event_log}/**/*.{ts,tsx}', + 'x-pack/plugins/{alerting,stack_alerts,actions,task_manager,event_log}/**/*.{ts,tsx}', ], rules: { '@typescript-eslint/no-explicit-any': 'error', @@ -1322,7 +1322,7 @@ module.exports = { }, { // typescript only for back end - files: ['x-pack/plugins/triggers_actions_ui/server/**/*.ts'], + files: ['x-pack/plugins/{stack_connectors,triggers_actions_ui}/server/**/*.ts'], rules: { '@typescript-eslint/no-explicit-any': 'error', }, diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 51323cee4a112..0a1fcc60d55b6 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -84,10 +84,12 @@ /x-pack/examples/ui_actions_enhanced_examples/ @elastic/kibana-app-services /x-pack/plugins/embeddable_enhanced/ @elastic/kibana-app-services /x-pack/plugins/runtime_fields @elastic/kibana-app-services -/x-pack/test/search_sessions_integration/ @elastic/kibana-app-services /src/plugins/dashboard/public/application/embeddable/viewport/print_media @elastic/kibana-app-services x-pack/plugins/files @elastic/kibana-app-services x-pack/examples/files_example @elastic/kibana-app-services +/x-pack/test/search_sessions_integration/ @elastic/kibana-app-services +/test/plugin_functional/test_suites/panel_actions @elastic/kibana-app-services +/test/plugin_functional/test_suites/data_plugin @elastic/kibana-app-services ### Observability Plugins @@ -130,6 +132,7 @@ x-pack/examples/files_example @elastic/kibana-app-services /x-pack/test/fleet_api_integration @elastic/fleet /x-pack/test/fleet_cypress @elastic/fleet /x-pack/test/fleet_functional @elastic/fleet +/src/dev/build/tasks/bundle_fleet_packages.ts # APM /x-pack/plugins/apm/ @elastic/apm-ui @@ -329,7 +332,9 @@ x-pack/examples/files_example @elastic/kibana-app-services /x-pack/plugins/event_log/ @elastic/response-ops /x-pack/plugins/task_manager/ @elastic/response-ops /x-pack/plugins/stack_connectors/ @elastic/response-ops +/x-pack/plugins/stack_connectors/public/connector_types/stack/ @elastic/response-ops-execution /x-pack/plugins/stack_connectors/server/connector_types/stack/ @elastic/response-ops-execution +/x-pack/plugins/stack_connectors/public/connector_types/cases/ @elastic/response-ops-cases /x-pack/plugins/stack_connectors/server/connector_types/cases/ @elastic/response-ops-cases /x-pack/test/alerting_api_integration/ @elastic/response-ops /x-pack/test/plugin_api_integration/test_suites/task_manager/ @elastic/response-ops @@ -348,6 +353,7 @@ x-pack/examples/files_example @elastic/kibana-app-services # Enterprise Search /x-pack/plugins/enterprise_search @elastic/enterprise-search-frontend /x-pack/test/functional_enterprise_search/ @elastic/enterprise-search-frontend +/x-pack/plugins/enterprise_search/public/applications/shared/doc_links @elastic/ent-search-docs-team # Management Experience - Deployment Management /src/plugins/dev_tools/ @elastic/platform-deployment-management @@ -737,6 +743,8 @@ packages/core/http/core-http-browser-mocks @elastic/kibana-core packages/core/http/core-http-common @elastic/kibana-core packages/core/http/core-http-context-server-internal @elastic/kibana-core packages/core/http/core-http-context-server-mocks @elastic/kibana-core +packages/core/http/core-http-request-handler-context-server @elastic/kibana-core +packages/core/http/core-http-request-handler-context-server-internal @elastic/kibana-core packages/core/http/core-http-router-server-internal @elastic/kibana-core packages/core/http/core-http-router-server-mocks @elastic/kibana-core packages/core/http/core-http-server @elastic/kibana-core @@ -784,6 +792,7 @@ packages/core/preboot/core-preboot-server-internal @elastic/kibana-core packages/core/preboot/core-preboot-server-mocks @elastic/kibana-core packages/core/rendering/core-rendering-browser-internal @elastic/kibana-core packages/core/rendering/core-rendering-browser-mocks @elastic/kibana-core +packages/core/root/core-root-browser-internal @elastic/kibana-core packages/core/saved-objects/core-saved-objects-api-browser @elastic/kibana-core packages/core/saved-objects/core-saved-objects-api-server @elastic/kibana-core packages/core/saved-objects/core-saved-objects-api-server-internal @elastic/kibana-core @@ -906,6 +915,7 @@ packages/kbn-rule-data-utils @elastic/apm-ui packages/kbn-safer-lodash-set @elastic/kibana-security packages/kbn-securitysolution-autocomplete @elastic/security-solution-platform packages/kbn-securitysolution-es-utils @elastic/security-solution-platform +packages/kbn-securitysolution-exception-list-components @elastic/security-solution-platform packages/kbn-securitysolution-hook-utils @elastic/security-solution-platform packages/kbn-securitysolution-io-ts-alerting-types @elastic/security-solution-platform packages/kbn-securitysolution-io-ts-list-types @elastic/security-solution-platform diff --git a/.i18nrc.json b/.i18nrc.json index 20b2588ca2fab..462daff20de63 100644 --- a/.i18nrc.json +++ b/.i18nrc.json @@ -60,6 +60,7 @@ "kibana-react": "src/plugins/kibana_react", "kibanaOverview": "src/plugins/kibana_overview", "lists": "packages/kbn-securitysolution-list-utils/src", + "exceptionList-components": "packages/kbn-securitysolution-exception-list-components/src", "management": ["src/legacy/core_plugins/management", "src/plugins/management"], "monaco": "packages/kbn-monaco/src", "navigation": "src/plugins/navigation", diff --git a/api_docs/actions.mdx b/api_docs/actions.mdx index 9422af0f654d9..929e069b2bf52 100644 --- a/api_docs/actions.mdx +++ b/api_docs/actions.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/actions title: "actions" image: https://source.unsplash.com/400x175/?github description: API docs for the actions plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'actions'] --- import actionsObj from './actions.devdocs.json'; diff --git a/api_docs/advanced_settings.mdx b/api_docs/advanced_settings.mdx index b3f310db1363a..43856104f3281 100644 --- a/api_docs/advanced_settings.mdx +++ b/api_docs/advanced_settings.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/advancedSettings title: "advancedSettings" image: https://source.unsplash.com/400x175/?github description: API docs for the advancedSettings plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'advancedSettings'] --- import advancedSettingsObj from './advanced_settings.devdocs.json'; diff --git a/api_docs/aiops.mdx b/api_docs/aiops.mdx index dd1f0725156f2..7694fbde6190c 100644 --- a/api_docs/aiops.mdx +++ b/api_docs/aiops.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/aiops title: "aiops" image: https://source.unsplash.com/400x175/?github description: API docs for the aiops plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'aiops'] --- import aiopsObj from './aiops.devdocs.json'; diff --git a/api_docs/alerting.devdocs.json b/api_docs/alerting.devdocs.json index a19bdb320740d..9971fcee0a58a 100644 --- a/api_docs/alerting.devdocs.json +++ b/api_docs/alerting.devdocs.json @@ -2666,8 +2666,6 @@ "Alert", "; scheduleActions: (actionGroup: ActionGroupIds, context?: Context) => ", "Alert", - "; scheduleActionsWithSubGroup: (actionGroup: ActionGroupIds, subgroup: string, context?: Context) => ", - "Alert", "; setContext: (context: Context) => ", "Alert", "; getContext: () => Context; hasContext: () => boolean; }" @@ -2832,7 +2830,11 @@ "section": "def-common.IExecutionErrorsResult", "text": "IExecutionErrorsResult" }, - ">; bulkEdit: ; getGlobalExecutionKpiWithAuth: ({ dateStart, dateEnd, filter, }: ", + "GetGlobalExecutionKPIParams", + ") => Promise<{ success: number; unknown: number; failure: number; activeAlerts: number; newAlerts: number; recoveredAlerts: number; erroredActions: number; triggeredActions: number; }>; getRuleExecutionKPI: ({ id, dateStart, dateEnd, filter }: ", + "GetRuleExecutionKPIParams", + ") => Promise<{ success: number; unknown: number; failure: number; activeAlerts: number; newAlerts: number; recoveredAlerts: number; erroredActions: number; triggeredActions: number; }>; bulkEdit: ; }; observability: { setup: { getScopedAnnotationsClient: (requestContext: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { licensing: Promise<", { "pluginId": "licensing", @@ -5696,13 +5684,7 @@ "label": "context", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { licensing: Promise<", { "pluginId": "licensing", diff --git a/api_docs/apm.mdx b/api_docs/apm.mdx index 0d5e1a8a16013..934ffbbd33801 100644 --- a/api_docs/apm.mdx +++ b/api_docs/apm.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/apm title: "apm" image: https://source.unsplash.com/400x175/?github description: API docs for the apm plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'apm'] --- import apmObj from './apm.devdocs.json'; diff --git a/api_docs/banners.mdx b/api_docs/banners.mdx index 817d1a9d9e349..12a25911e2da1 100644 --- a/api_docs/banners.mdx +++ b/api_docs/banners.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/banners title: "banners" image: https://source.unsplash.com/400x175/?github description: API docs for the banners plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'banners'] --- import bannersObj from './banners.devdocs.json'; diff --git a/api_docs/bfetch.devdocs.json b/api_docs/bfetch.devdocs.json index 74f1cf1aee455..f060159bc0f3a 100644 --- a/api_docs/bfetch.devdocs.json +++ b/api_docs/bfetch.devdocs.json @@ -357,13 +357,7 @@ "(path: string, params: (request: ", "KibanaRequest", ", context: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ") => ", { "pluginId": "bfetch", @@ -375,13 +369,7 @@ ", method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | undefined, pluginRouter?: ", "IRouter", "<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", "> | undefined) => void" ], "path": "src/plugins/bfetch/server/plugin.ts", @@ -414,13 +402,7 @@ "(request: ", "KibanaRequest", ", context: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ") => ", { "pluginId": "bfetch", @@ -461,13 +443,7 @@ "signature": [ "IRouter", "<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", "> | undefined" ], "path": "src/plugins/bfetch/server/plugin.ts", diff --git a/api_docs/bfetch.mdx b/api_docs/bfetch.mdx index b9b63b1d6b44c..c4055d6564051 100644 --- a/api_docs/bfetch.mdx +++ b/api_docs/bfetch.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/bfetch title: "bfetch" image: https://source.unsplash.com/400x175/?github description: API docs for the bfetch plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'bfetch'] --- import bfetchObj from './bfetch.devdocs.json'; diff --git a/api_docs/canvas.mdx b/api_docs/canvas.mdx index a1960b0026238..4ef1b1b03a0ec 100644 --- a/api_docs/canvas.mdx +++ b/api_docs/canvas.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/canvas title: "canvas" image: https://source.unsplash.com/400x175/?github description: API docs for the canvas plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'canvas'] --- import canvasObj from './canvas.devdocs.json'; diff --git a/api_docs/cases.mdx b/api_docs/cases.mdx index 32c090dbfa1a1..6df29978541a0 100644 --- a/api_docs/cases.mdx +++ b/api_docs/cases.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/cases title: "cases" image: https://source.unsplash.com/400x175/?github description: API docs for the cases plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'cases'] --- import casesObj from './cases.devdocs.json'; diff --git a/api_docs/charts.mdx b/api_docs/charts.mdx index 3da28b0bad7fd..718e93231dffe 100644 --- a/api_docs/charts.mdx +++ b/api_docs/charts.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/charts title: "charts" image: https://source.unsplash.com/400x175/?github description: API docs for the charts plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'charts'] --- import chartsObj from './charts.devdocs.json'; diff --git a/api_docs/cloud.mdx b/api_docs/cloud.mdx index bc45db69cc1a6..74692e016ccf0 100644 --- a/api_docs/cloud.mdx +++ b/api_docs/cloud.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/cloud title: "cloud" image: https://source.unsplash.com/400x175/?github description: API docs for the cloud plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'cloud'] --- import cloudObj from './cloud.devdocs.json'; diff --git a/api_docs/cloud_experiments.mdx b/api_docs/cloud_experiments.mdx index 8535c5a7082f3..9b5efb2aa51f4 100644 --- a/api_docs/cloud_experiments.mdx +++ b/api_docs/cloud_experiments.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/cloudExperiments title: "cloudExperiments" image: https://source.unsplash.com/400x175/?github description: API docs for the cloudExperiments plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'cloudExperiments'] --- import cloudExperimentsObj from './cloud_experiments.devdocs.json'; diff --git a/api_docs/cloud_security_posture.mdx b/api_docs/cloud_security_posture.mdx index 94352a497b7cf..1ccfb42f61d02 100644 --- a/api_docs/cloud_security_posture.mdx +++ b/api_docs/cloud_security_posture.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/cloudSecurityPosture title: "cloudSecurityPosture" image: https://source.unsplash.com/400x175/?github description: API docs for the cloudSecurityPosture plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'cloudSecurityPosture'] --- import cloudSecurityPostureObj from './cloud_security_posture.devdocs.json'; diff --git a/api_docs/console.mdx b/api_docs/console.mdx index 11e5a000bc0f7..00e0779286aae 100644 --- a/api_docs/console.mdx +++ b/api_docs/console.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/console title: "console" image: https://source.unsplash.com/400x175/?github description: API docs for the console plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'console'] --- import consoleObj from './console.devdocs.json'; diff --git a/api_docs/controls.mdx b/api_docs/controls.mdx index 1cdddefa3f573..e1427ab3d19f0 100644 --- a/api_docs/controls.mdx +++ b/api_docs/controls.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/controls title: "controls" image: https://source.unsplash.com/400x175/?github description: API docs for the controls plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'controls'] --- import controlsObj from './controls.devdocs.json'; diff --git a/api_docs/core.devdocs.json b/api_docs/core.devdocs.json index 08008a2bfe5c5..67fa46292601f 100644 --- a/api_docs/core.devdocs.json +++ b/api_docs/core.devdocs.json @@ -584,6 +584,10 @@ "plugin": "@kbn/core-analytics-server-internal", "path": "packages/core/analytics/core-analytics-server-internal/src/analytics_service.ts" }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.ts" + }, { "plugin": "@kbn/core-status-server-internal", "path": "packages/core/status/core-status-server-internal/src/status_service.ts" @@ -620,6 +624,30 @@ "plugin": "@kbn/core-analytics-browser-mocks", "path": "packages/core/analytics/core-analytics-browser-mocks/src/analytics_service.mock.ts" }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, { "plugin": "@kbn/core-analytics-browser-mocks", "path": "packages/core/analytics/core-analytics-browser-mocks/src/analytics_service.mock.ts" @@ -10361,7 +10389,7 @@ "\nThe outcome for a successful `resolve` call is one of the following values:\n\n * `'exactMatch'` -- One document exactly matched the given ID.\n * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different\n than the given ID.\n * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the\n `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID." ], "signature": [ - "\"exactMatch\" | \"aliasMatch\" | \"conflict\"" + "\"conflict\" | \"exactMatch\" | \"aliasMatch\"" ], "path": "node_modules/@types/kbn__core-saved-objects-api-browser/index.d.ts", "deprecated": false, @@ -10822,6 +10850,14 @@ "plugin": "visualizations", "path": "src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx" }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts" + }, { "plugin": "infra", "path": "x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx" @@ -11156,11 +11192,15 @@ }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts" }, { "plugin": "dashboard", @@ -11204,43 +11244,35 @@ }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "ml", @@ -11250,6 +11282,14 @@ "plugin": "ml", "path": "x-pack/plugins/ml/common/types/modules.ts" }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts" + }, { "plugin": "@kbn/core-saved-objects-server-internal", "path": "packages/core/saved-objects/core-saved-objects-server-internal/src/routes/legacy_import_export/lib/collect_references_deep.test.ts" @@ -15328,9 +15368,9 @@ "label": "SavedObjectsFindOptions", "description": [], "signature": [ - "{ type: string | string[]; filter?: any; search?: string | undefined; aggs?: Record | undefined; fields?: string[] | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; searchFields?: string[] | undefined; hasReference?: ", + "> | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; searchFields?: string[] | undefined; hasReference?: ", "SavedObjectsFindOptionsReference", " | ", "SavedObjectsFindOptionsReference", @@ -19295,6 +19335,10 @@ "plugin": "@kbn/core-analytics-server-internal", "path": "packages/core/analytics/core-analytics-server-internal/src/analytics_service.ts" }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.ts" + }, { "plugin": "@kbn/core-status-server-internal", "path": "packages/core/status/core-status-server-internal/src/status_service.ts" @@ -19331,6 +19375,30 @@ "plugin": "@kbn/core-analytics-browser-mocks", "path": "packages/core/analytics/core-analytics-browser-mocks/src/analytics_service.mock.ts" }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, + { + "plugin": "@kbn/core-root-browser-internal", + "path": "packages/core/root/core-root-browser-internal/src/core_system.test.ts" + }, { "plugin": "@kbn/core-analytics-browser-mocks", "path": "packages/core/analytics/core-analytics-browser-mocks/src/analytics_service.mock.ts" @@ -21478,13 +21546,7 @@ "signature": [ "HttpServicePreboot", "<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ">" ], "path": "src/core/server/index.ts", @@ -21519,7 +21581,10 @@ "description": [ "\nThe `core` context provided to route handler.\n\nProvides the following clients and services:\n - {@link SavedObjectsClient | savedObjects.client} - Saved Objects client\n which uses the credentials of the incoming request\n - {@link ISavedObjectTypeRegistry | savedObjects.typeRegistry} - Type registry containing\n all the registered types.\n - {@link IScopedClusterClient | elasticsearch.client} - Elasticsearch\n data client which uses the credentials of the incoming request\n - {@link IUiSettingsClient | uiSettings.client} - uiSettings client\n which uses the credentials of the incoming request" ], - "path": "src/core/server/core_route_handler_context.ts", + "signature": [ + "CoreRequestHandlerContext" + ], + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false, "children": [ @@ -21533,7 +21598,7 @@ "signature": [ "SavedObjectsRequestHandlerContext" ], - "path": "src/core/server/core_route_handler_context.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false }, @@ -21547,7 +21612,7 @@ "signature": [ "ElasticsearchRequestHandlerContext" ], - "path": "src/core/server/core_route_handler_context.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false }, @@ -21561,7 +21626,7 @@ "signature": [ "UiSettingsRequestHandlerContext" ], - "path": "src/core/server/core_route_handler_context.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false }, @@ -21575,7 +21640,7 @@ "signature": [ "DeprecationsRequestHandlerContext" ], - "path": "src/core/server/core_route_handler_context.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false } @@ -21746,13 +21811,7 @@ "signature": [ "HttpServiceSetup", "<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", "> & { resources: ", { "pluginId": "core", @@ -25894,21 +25953,9 @@ ], "signature": [ "(route: ", "RouteConfig", ", handler: ", @@ -39364,6 +39411,37 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "core", + "id": "def-server.PrebootCoreRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "PrebootCoreRequestHandlerContext", + "description": [], + "signature": [ + "PrebootCoreRequestHandlerContext" + ], + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "core", + "id": "def-server.PrebootCoreRequestHandlerContext.uiSettings", + "type": "Object", + "tags": [], + "label": "uiSettings", + "description": [], + "signature": [ + "PrebootUiSettingsRequestHandlerContext" + ], + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "core", "id": "def-server.PrebootPlugin", @@ -39467,6 +39545,41 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "core", + "id": "def-server.PrebootRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "PrebootRequestHandlerContext", + "description": [], + "signature": [ + "PrebootRequestHandlerContext", + " extends ", + "RequestHandlerContextBase" + ], + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "core", + "id": "def-server.PrebootRequestHandlerContext.core", + "type": "Object", + "tags": [], + "label": "core", + "description": [], + "signature": [ + "Promise<", + "PrebootCoreRequestHandlerContext", + ">" + ], + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "core", "id": "def-server.RegisterDeprecationsConfig", @@ -39532,17 +39645,11 @@ "\nBase context passed to a route handler, containing the `core` context part.\n" ], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " extends ", "RequestHandlerContextBase" ], - "path": "src/core/server/index.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false, "children": [ @@ -39555,16 +39662,10 @@ "description": [], "signature": [ "Promise<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.CoreRequestHandlerContext", - "text": "CoreRequestHandlerContext" - }, + "CoreRequestHandlerContext", ">" ], - "path": "src/core/server/index.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false } @@ -40431,6 +40532,14 @@ "plugin": "visualizations", "path": "src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx" }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts" + }, { "plugin": "infra", "path": "x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx" @@ -40765,11 +40874,15 @@ }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts" }, { "plugin": "dashboard", @@ -40813,43 +40926,35 @@ }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/common/saved_dashboard_references.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts" }, { "plugin": "ml", @@ -40859,6 +40964,14 @@ "plugin": "ml", "path": "x-pack/plugins/ml/common/types/modules.ts" }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts" + }, + { + "plugin": "dashboard", + "path": "src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts" + }, { "plugin": "@kbn/core-saved-objects-server-internal", "path": "packages/core/saved-objects/core-saved-objects-server-internal/src/routes/legacy_import_export/lib/collect_references_deep.test.ts" @@ -45678,11 +45791,11 @@ }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/migrations_730.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts" }, { "plugin": "dashboard", - "path": "src/plugins/dashboard/server/saved_objects/migrations_730.ts" + "path": "src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts" }, { "plugin": "@kbn/core-saved-objects-migration-server-internal", @@ -46663,7 +46776,7 @@ "\nThe outcome for a successful `resolve` call is one of the following values:\n\n * `'exactMatch'` -- One document exactly matched the given ID.\n * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different\n than the given ID.\n * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the\n `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID." ], "signature": [ - "\"exactMatch\" | \"aliasMatch\" | \"conflict\"" + "\"conflict\" | \"exactMatch\" | \"aliasMatch\"" ], "path": "node_modules/@types/kbn__core-saved-objects-api-server/index.d.ts", "deprecated": false, @@ -50120,16 +50233,10 @@ "\nMixin allowing plugins to define their own request handler contexts.\n" ], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { [Key in keyof T]: T[Key] extends Promise ? T[Key] : Promise; }" ], - "path": "src/core/server/index.ts", + "path": "node_modules/@types/kbn__core-http-request-handler-context-server/index.d.ts", "deprecated": false, "trackAdoption": false, "initialIsOpen": false @@ -53606,9 +53713,9 @@ "label": "SavedObjectsCreatePointInTimeFinderOptions", "description": [], "signature": [ - "{ type: string | string[]; filter?: any; search?: string | undefined; aggs?: Record | undefined; fields?: string[] | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", + "> | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", "SortOrder", " | undefined; searchFields?: string[] | undefined; rootSearchFields?: string[] | undefined; hasReference?: ", "SavedObjectsFindOptionsReference", diff --git a/api_docs/core.mdx b/api_docs/core.mdx index 65cff6e9c9ae0..798c6c53ce345 100644 --- a/api_docs/core.mdx +++ b/api_docs/core.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/core title: "core" image: https://source.unsplash.com/400x175/?github description: API docs for the core plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'core'] --- import coreObj from './core.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) for que | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 2684 | 0 | 35 | 0 | +| 2688 | 0 | 30 | 0 | ## Client diff --git a/api_docs/custom_integrations.devdocs.json b/api_docs/custom_integrations.devdocs.json index 7a339106c7a6d..03090384a0559 100644 --- a/api_docs/custom_integrations.devdocs.json +++ b/api_docs/custom_integrations.devdocs.json @@ -438,7 +438,7 @@ "label": "categories", "description": [], "signature": [ - "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" + "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -488,7 +488,7 @@ "\nA category applicable to an Integration." ], "signature": [ - "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" + "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -728,7 +728,7 @@ "label": "categories", "description": [], "signature": [ - "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" + "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -838,7 +838,7 @@ "label": "id", "description": [], "signature": [ - "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" + "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -860,7 +860,7 @@ "\nThe list of all available categories." ], "signature": [ - "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" + "(\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\")[]" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -877,7 +877,7 @@ "\nA category applicable to an Integration." ], "signature": [ - "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" + "\"custom\" | \"enterprise_search\" | \"sample_data\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"microsoft_365\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\" | \"communications\" | \"file_storage\" | \"language_client\" | \"upload_file\" | \"website_search\" | \"geo\"" ], "path": "src/plugins/custom_integrations/common/index.ts", "deprecated": false, @@ -1097,6 +1097,17 @@ "deprecated": false, "trackAdoption": false }, + { + "parentPluginId": "customIntegrations", + "id": "def-common.INTEGRATION_CATEGORY_DISPLAY.infrastructure", + "type": "string", + "tags": [], + "label": "infrastructure", + "description": [], + "path": "src/plugins/custom_integrations/common/index.ts", + "deprecated": false, + "trackAdoption": false + }, { "parentPluginId": "customIntegrations", "id": "def-common.INTEGRATION_CATEGORY_DISPLAY.kubernetes", diff --git a/api_docs/custom_integrations.mdx b/api_docs/custom_integrations.mdx index b1923914ba36b..77c928f34e584 100644 --- a/api_docs/custom_integrations.mdx +++ b/api_docs/custom_integrations.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/customIntegrations title: "customIntegrations" image: https://source.unsplash.com/400x175/?github description: API docs for the customIntegrations plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'customIntegrations'] --- import customIntegrationsObj from './custom_integrations.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Fleet](https://github.com/orgs/elastic/teams/fleet) for questions regar | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 103 | 0 | 84 | 1 | +| 104 | 0 | 85 | 1 | ## Client diff --git a/api_docs/dashboard.devdocs.json b/api_docs/dashboard.devdocs.json index 447c0d0af07ee..c185507fd9101 100644 --- a/api_docs/dashboard.devdocs.json +++ b/api_docs/dashboard.devdocs.json @@ -1,33 +1,99 @@ { "id": "dashboard", "client": { - "classes": [ + "classes": [], + "functions": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer", - "type": "Class", + "id": "def-public.cleanEmptyKeys", + "type": "Function", "tags": [], - "label": "DashboardContainer", + "label": "cleanEmptyKeys", "description": [], "signature": [ + "(stateObj: Record) => Record" + ], + "path": "src/plugins/dashboard/public/locator.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainer", - "text": "DashboardContainer" - }, - " extends ", + "parentPluginId": "dashboard", + "id": "def-public.cleanEmptyKeys.$1", + "type": "Object", + "tags": [], + "label": "stateObj", + "description": [], + "signature": [ + "Record" + ], + "path": "src/plugins/dashboard/public/locator.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.createDashboardEditUrl", + "type": "Function", + "tags": [], + "label": "createDashboardEditUrl", + "description": [], + "signature": [ + "(id: string | undefined, editMode: boolean | undefined) => string" + ], + "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.Container", - "text": "Container" + "parentPluginId": "dashboard", + "id": "def-public.createDashboardEditUrl.$1", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false }, - "<", - "InheritedChildInput", - ", ", + { + "parentPluginId": "dashboard", + "id": "def-public.createDashboardEditUrl.$2", + "type": "CompoundType", + "tags": [], + "label": "editMode", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + } + ], + "returnComment": [], + "initialIsOpen": false + } + ], + "interfaces": [ + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardContainerInput", + "type": "Interface", + "tags": [], + "label": "DashboardContainerInput", + "description": [], + "signature": [ { "pluginId": "dashboard", "scope": "public", @@ -35,1674 +101,1479 @@ "section": "def-public.DashboardContainerInput", "text": "DashboardContainerInput" }, - ", ", + " extends ", { "pluginId": "embeddable", "scope": "public", "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerOutput", - "text": "ContainerOutput" + "section": "def-public.ContainerInput", + "text": "ContainerInput" }, - ">" + "<{}>" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.type", - "type": "string", - "tags": [], - "label": "type", - "description": [], - "signature": [ - "\"dashboard\"" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.controlGroup", + "id": "def-public.DashboardContainerInput.controlGroupInput", "type": "Object", "tags": [], - "label": "controlGroup", + "label": "controlGroupInput", "description": [], "signature": [ { "pluginId": "controls", - "scope": "public", + "scope": "common", "docId": "kibControlsPluginApi", - "section": "def-public.ControlGroupContainer", - "text": "ControlGroupContainer" + "section": "def-common.PersistableControlGroupInput", + "text": "PersistableControlGroupInput" }, " | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.getAllDataViews", - "type": "Function", + "id": "def-public.DashboardContainerInput.refreshConfig", + "type": "Object", "tags": [], - "label": "getAllDataViews", - "description": [ - "\nGets all the dataviews that are actively being used in the dashboard" - ], + "label": "refreshConfig", + "description": [], "signature": [ - "() => ", { - "pluginId": "dataViews", + "pluginId": "data", "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" + "docId": "kibDataQueryPluginApi", + "section": "def-common.RefreshInterval", + "text": "RefreshInterval" }, - "[]" + " | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [ - "An array of dataviews" - ] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.setAllDataViews", - "type": "Function", + "id": "def-public.DashboardContainerInput.isEmbeddedExternally", + "type": "CompoundType", "tags": [], - "label": "setAllDataViews", - "description": [ - "\nUse this to set the dataviews that are used in the dashboard when they change/update" - ], + "label": "isEmbeddedExternally", + "description": [], "signature": [ - "(newDataViews: ", - { - "pluginId": "dataViews", - "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" - }, - "[]) => void" + "boolean | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.setAllDataViews.$1", - "type": "Array", - "tags": [], - "label": "newDataViews", - "description": [ - "The new array of dataviews that will overwrite the old dataviews array" - ], - "signature": [ - { - "pluginId": "dataViews", - "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" - }, - "[]" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.getPanelCount", - "type": "Function", + "id": "def-public.DashboardContainerInput.isFullScreenMode", + "type": "boolean", "tags": [], - "label": "getPanelCount", + "label": "isFullScreenMode", "description": [], - "signature": [ - "() => number" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.getPanelTitles", - "type": "Function", + "id": "def-public.DashboardContainerInput.expandedPanelId", + "type": "string", "tags": [], - "label": "getPanelTitles", + "label": "expandedPanelId", "description": [], "signature": [ - "() => Promise" + "string | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.Unnamed", - "type": "Function", + "id": "def-public.DashboardContainerInput.timeRange", + "type": "Object", "tags": [], - "label": "Constructor", + "label": "timeRange", "description": [], "signature": [ - "any" + "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.Unnamed.$1", - "type": "Object", - "tags": [], - "label": "initialInput", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" - } - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.Unnamed.$2", - "type": "Object", - "tags": [], - "label": "parent", - "description": [], - "signature": [ - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.Container", - "text": "Container" - }, - "<{}, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerInput", - "text": "ContainerInput" - }, - "<{}>, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerOutput", - "text": "ContainerOutput" - }, - "> | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.Unnamed.$3", - "type": "CompoundType", - "tags": [], - "label": "controlGroup", - "description": [], - "signature": [ - { - "pluginId": "controls", - "scope": "public", - "docId": "kibControlsPluginApi", - "section": "def-public.ControlGroupContainer", - "text": "ControlGroupContainer" - }, - " | ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ErrorEmbeddable", - "text": "ErrorEmbeddable" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.createNewPanelState", - "type": "Function", + "id": "def-public.DashboardContainerInput.timeslice", + "type": "Object", "tags": [], - "label": "createNewPanelState", + "label": "timeslice", "description": [], "signature": [ - ">(factory: ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.EmbeddableFactory", - "text": "EmbeddableFactory" - }, - ", partial?: Partial) => ", - "DashboardPanelState", - "" + "[number, number] | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.createNewPanelState.$1", - "type": "Object", - "tags": [], - "label": "factory", - "description": [], - "signature": [ - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.EmbeddableFactory", - "text": "EmbeddableFactory" - }, - "" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.createNewPanelState.$2", - "type": "Object", - "tags": [], - "label": "partial", - "description": [], - "signature": [ - "Partial" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.showPlaceholderUntil", - "type": "Function", + "id": "def-public.DashboardContainerInput.timeRestore", + "type": "boolean", "tags": [], - "label": "showPlaceholderUntil", + "label": "timeRestore", "description": [], - "signature": [ - "(newStateComplete: Promise>>, placementMethod?: ", - "PanelPlacementMethod", - " | undefined, placementArgs?: TPlacementMethodArgs | undefined) => void" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.showPlaceholderUntil.$1", - "type": "Object", - "tags": [], - "label": "newStateComplete", - "description": [], - "signature": [ - "Promise>>" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.showPlaceholderUntil.$2", - "type": "Function", - "tags": [], - "label": "placementMethod", - "description": [], - "signature": [ - "PanelPlacementMethod", - " | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.showPlaceholderUntil.$3", - "type": "Uncategorized", - "tags": [], - "label": "placementArgs", - "description": [], - "signature": [ - "TPlacementMethodArgs | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.replacePanel", - "type": "Function", + "id": "def-public.DashboardContainerInput.description", + "type": "string", "tags": [], - "label": "replacePanel", + "label": "description", "description": [], "signature": [ - "(previousPanelState: ", - "DashboardPanelState", - "<", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableInput", - "text": "EmbeddableInput" - }, - ">, newPanelState: Partial<", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.PanelState", - "text": "PanelState" - }, - "<{ id: string; }>>, generateNewId?: boolean | undefined) => void" + "string | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.replacePanel.$1", - "type": "Object", - "tags": [], - "label": "previousPanelState", - "description": [], - "signature": [ - "DashboardPanelState", - "<", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableInput", - "text": "EmbeddableInput" - }, - ">" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.replacePanel.$2", - "type": "Object", - "tags": [], - "label": "newPanelState", - "description": [], - "signature": [ - "Partial<", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.PanelState", - "text": "PanelState" - }, - "<{ id: string; }>>" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.replacePanel.$3", - "type": "CompoundType", - "tags": [], - "label": "generateNewId", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.addOrUpdateEmbeddable", - "type": "Function", + "id": "def-public.DashboardContainerInput.useMargins", + "type": "boolean", "tags": [], - "label": "addOrUpdateEmbeddable", + "label": "useMargins", "description": [], - "signature": [ - " = ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.IEmbeddable", - "text": "IEmbeddable" - }, - ">(type: string, explicitInput: Partial, embeddableId?: string | undefined) => Promise" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.addOrUpdateEmbeddable.$1", - "type": "string", - "tags": [], - "label": "type", - "description": [], - "signature": [ - "string" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.addOrUpdateEmbeddable.$2", - "type": "Object", - "tags": [], - "label": "explicitInput", - "description": [], - "signature": [ - "Partial" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.addOrUpdateEmbeddable.$3", - "type": "string", - "tags": [], - "label": "embeddableId", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.render", - "type": "Function", + "id": "def-public.DashboardContainerInput.syncColors", + "type": "CompoundType", "tags": [], - "label": "render", + "label": "syncColors", "description": [], "signature": [ - "(dom: HTMLElement) => void" + "boolean | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.render.$1", - "type": "Object", - "tags": [], - "label": "dom", - "description": [], - "signature": [ - "HTMLElement" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.destroy", - "type": "Function", + "id": "def-public.DashboardContainerInput.syncTooltips", + "type": "CompoundType", "tags": [], - "label": "destroy", + "label": "syncTooltips", "description": [], "signature": [ - "() => void" + "boolean | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.getInheritedInput", - "type": "Function", + "id": "def-public.DashboardContainerInput.viewMode", + "type": "Enum", "tags": [], - "label": "getInheritedInput", + "label": "viewMode", "description": [], "signature": [ - "(id: string) => ", - "InheritedChildInput" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [ { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainer.getInheritedInput.$1", - "type": "string", - "tags": [], - "label": "id", - "description": [], - "signature": [ - "string" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.ViewMode", + "text": "ViewMode" } ], - "returnComment": [] - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition", - "type": "Class", - "tags": [], - "label": "DashboardContainerFactoryDefinition", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerFactoryDefinition", - "text": "DashboardContainerFactoryDefinition" - }, - " implements ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.EmbeddableFactoryDefinition", - "text": "EmbeddableFactoryDefinition" - }, - "<", - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" - }, - ", ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerOutput", - "text": "ContainerOutput" - }, - ", ", - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainer", - "text": "DashboardContainer" + "path": "src/plugins/dashboard/public/types.ts", + "deprecated": false, + "trackAdoption": false }, - ", unknown>" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.isContainerType", - "type": "boolean", + "id": "def-public.DashboardContainerInput.filters", + "type": "Array", "tags": [], - "label": "isContainerType", + "label": "filters", "description": [], "signature": [ - "true" + "Filter", + "[]" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.type", + "id": "def-public.DashboardContainerInput.title", "type": "string", "tags": [], - "label": "type", + "label": "title", "description": [], - "signature": [ - "\"dashboard\"" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.inject", - "type": "Function", + "id": "def-public.DashboardContainerInput.query", + "type": "Object", "tags": [], - "label": "inject", + "label": "query", "description": [], "signature": [ - "(state: ", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableStateWithType", - "text": "EmbeddableStateWithType" - }, - ", references: ", - "SavedObjectReference", - "[]) => ", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableStateWithType", - "text": "EmbeddableStateWithType" - } + "{ query: string | { [key: string]: any; }; language: string; }" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "returnComment": [], - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.inject.$1", - "type": "Uncategorized", - "tags": [], - "label": "state", - "description": [], - "signature": [ - "P" - ], - "path": "src/plugins/kibana_utils/common/persistable_state/types.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.inject.$2", - "type": "Array", - "tags": [], - "label": "references", - "description": [], - "signature": [ - "SavedObjectReference", - "[]" - ], - "path": "src/plugins/kibana_utils/common/persistable_state/types.ts", - "deprecated": false, - "trackAdoption": false - } - ] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.extract", - "type": "Function", + "id": "def-public.DashboardContainerInput.panels", + "type": "Object", "tags": [], - "label": "extract", + "label": "panels", "description": [], "signature": [ - "(state: ", + "{ [panelId: string]: ", { - "pluginId": "embeddable", + "pluginId": "dashboard", "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableStateWithType", - "text": "EmbeddableStateWithType" + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" }, - ") => { state: ", + "<", { "pluginId": "embeddable", "scope": "common", "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableStateWithType", - "text": "EmbeddableStateWithType" + "section": "def-common.EmbeddableInput", + "text": "EmbeddableInput" }, - "; references: ", - "SavedObjectReference", - "[]; }" + " & { [k: string]: unknown; }>; }" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "returnComment": [], - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.extract.$1", - "type": "Uncategorized", - "tags": [], - "label": "state", - "description": [], - "signature": [ - "P" - ], - "path": "src/plugins/kibana_utils/common/persistable_state/types.ts", - "deprecated": false, - "trackAdoption": false - } - ] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.Unnamed", - "type": "Function", + "id": "def-public.DashboardContainerInput.executionContext", + "type": "Object", "tags": [], - "label": "Constructor", + "label": "executionContext", "description": [], "signature": [ - "any" + "KibanaExecutionContext", + " | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/public/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.Unnamed.$1", - "type": "Object", - "tags": [], - "label": "persistableStateService", - "description": [], - "signature": [ - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddablePersistableStateService", - "text": "EmbeddablePersistableStateService" - } - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardFeatureFlagConfig", + "type": "Interface", + "tags": [], + "label": "DashboardFeatureFlagConfig", + "description": [], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardFeatureFlagConfig.allowByValueEmbeddables", + "type": "boolean", + "tags": [], + "label": "allowByValueEmbeddables", + "description": [], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.SavedDashboardPanel", + "type": "Interface", + "tags": [], + "label": "SavedDashboardPanel", + "description": [ + "\nA saved dashboard panel parsed directly from the Dashboard Attributes panels JSON" + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-public.SavedDashboardPanel.embeddableConfig", + "type": "Object", + "tags": [], + "label": "embeddableConfig", + "description": [], + "signature": [ + "{ [key: string]: ", + "Serializable", + "; }" ], - "returnComment": [] + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.isEditable", - "type": "Function", + "id": "def-public.SavedDashboardPanel.id", + "type": "string", "tags": [], - "label": "isEditable", + "label": "id", "description": [], "signature": [ - "() => Promise" + "string | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.SavedDashboardPanel.type", + "type": "string", + "tags": [], + "label": "type", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.getDisplayName", - "type": "Function", + "id": "def-public.SavedDashboardPanel.panelRefName", + "type": "string", "tags": [], - "label": "getDisplayName", + "label": "panelRefName", "description": [], "signature": [ - "() => string" + "string | undefined" ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.getDefaultInput", - "type": "Function", + "id": "def-public.SavedDashboardPanel.gridData", + "type": "Object", "tags": [], - "label": "getDefaultInput", + "label": "gridData", "description": [], "signature": [ - "() => Partial<", { "pluginId": "dashboard", - "scope": "public", + "scope": "common", "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" - }, - ">" + "section": "def-common.GridData", + "text": "GridData" + } ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.create", - "type": "Function", + "id": "def-public.SavedDashboardPanel.panelIndex", + "type": "string", "tags": [], - "label": "create", + "label": "panelIndex", "description": [], - "signature": [ - "(initialInput: ", - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" - }, - ", parent?: ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.Container", - "text": "Container" - }, - "<{}, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerInput", - "text": "ContainerInput" - }, - "<{}>, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerOutput", - "text": "ContainerOutput" - }, - "> | undefined) => Promise<", - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainer", - "text": "DashboardContainer" - }, - " | ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ErrorEmbeddable", - "text": "ErrorEmbeddable" - }, - ">" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.create.$1", - "type": "Object", - "tags": [], - "label": "initialInput", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" - } - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerFactoryDefinition.create.$2", - "type": "Object", - "tags": [], - "label": "parent", - "description": [], - "signature": [ - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.Container", - "text": "Container" - }, - "<{}, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerInput", - "text": "ContainerInput" - }, - "<{}>, ", - { - "pluginId": "embeddable", - "scope": "public", - "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerOutput", - "text": "ContainerOutput" - }, - "> | undefined" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.SavedDashboardPanel.version", + "type": "string", + "tags": [], + "label": "version", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.SavedDashboardPanel.title", + "type": "string", + "tags": [], + "label": "title", + "description": [], + "signature": [ + "string | undefined" ], - "returnComment": [] + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false } ], "initialIsOpen": false } ], - "functions": [ + "enums": [], + "misc": [ { "parentPluginId": "dashboard", - "id": "def-public.cleanEmptyKeys", - "type": "Function", + "id": "def-public.DASHBOARD_CONTAINER_TYPE", + "type": "string", "tags": [], - "label": "cleanEmptyKeys", + "label": "DASHBOARD_CONTAINER_TYPE", "description": [], "signature": [ - "(stateObj: Record) => Record" + "\"dashboard\"" ], - "path": "src/plugins/dashboard/public/locator.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.cleanEmptyKeys.$1", - "type": "Object", - "tags": [], - "label": "stateObj", - "description": [], - "signature": [ - "Record" - ], - "path": "src/plugins/dashboard/public/locator.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [], "initialIsOpen": false }, { "parentPluginId": "dashboard", - "id": "def-public.createDashboardEditUrl", - "type": "Function", + "id": "def-public.DashboardAppLocator", + "type": "Type", "tags": [], - "label": "createDashboardEditUrl", + "label": "DashboardAppLocator", "description": [], "signature": [ - "(id: string | undefined, editMode: boolean | undefined) => string" - ], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { - "parentPluginId": "dashboard", - "id": "def-public.createDashboardEditUrl.$1", - "type": "string", - "tags": [], - "label": "id", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": false + "pluginId": "share", + "scope": "common", + "docId": "kibSharePluginApi", + "section": "def-common.LocatorPublic", + "text": "LocatorPublic" }, + "<", { - "parentPluginId": "dashboard", - "id": "def-public.createDashboardEditUrl.$2", - "type": "CompoundType", - "tags": [], - "label": "editMode", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } + "pluginId": "dashboard", + "scope": "public", + "docId": "kibDashboardPluginApi", + "section": "def-public.DashboardAppLocatorParams", + "text": "DashboardAppLocatorParams" + }, + ">" ], - "returnComment": [], + "path": "src/plugins/dashboard/public/locator.ts", + "deprecated": false, + "trackAdoption": false, "initialIsOpen": false - } - ], - "interfaces": [ + }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput", - "type": "Interface", + "id": "def-public.DashboardAppLocatorParams", + "type": "Type", "tags": [], - "label": "DashboardContainerInput", - "description": [], + "label": "DashboardAppLocatorParams", + "description": [ + "\nWe use `type` instead of `interface` to avoid having to extend this type with\n`SerializableRecord`. See https://github.com/microsoft/TypeScript/issues/15300." + ], "signature": [ + "{ dashboardId?: string | undefined; timeRange?: ", + "TimeRange", + " | undefined; refreshInterval?: ", { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardContainerInput", - "text": "DashboardContainerInput" + "pluginId": "data", + "scope": "common", + "docId": "kibDataQueryPluginApi", + "section": "def-common.RefreshInterval", + "text": "RefreshInterval" }, - " extends ", + " | undefined; filters?: ", + "Filter", + "[] | undefined; query?: ", + "Query", + " | undefined; useHash?: boolean | undefined; preserveSavedFilters?: boolean | undefined; viewMode?: ", { "pluginId": "embeddable", - "scope": "public", + "scope": "common", "docId": "kibEmbeddablePluginApi", - "section": "def-public.ContainerInput", - "text": "ContainerInput" + "section": "def-common.ViewMode", + "text": "ViewMode" }, - "<{}>" + " | undefined; searchSessionId?: string | undefined; panels?: (", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" + }, + " & ", + "SerializableRecord", + ")[] | undefined; savedQuery?: string | undefined; tags?: string[] | undefined; options?: ", + "DashboardOptions", + " | undefined; controlGroupInput?: ", + { + "pluginId": "controls", + "scope": "common", + "docId": "kibControlsPluginApi", + "section": "def-common.SerializableControlGroupInput", + "text": "SerializableControlGroupInput" + }, + " | undefined; }" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/locator.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + } + ], + "objects": [ + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardConstants", + "type": "Object", + "tags": [], + "label": "DashboardConstants", + "description": [], + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.controlGroupInput", - "type": "Object", + "id": "def-public.DashboardConstants.LANDING_PAGE_PATH", + "type": "string", "tags": [], - "label": "controlGroupInput", + "label": "LANDING_PAGE_PATH", "description": [], - "signature": [ - { - "pluginId": "controls", - "scope": "common", - "docId": "kibControlsPluginApi", - "section": "def-common.PersistableControlGroupInput", - "text": "PersistableControlGroupInput" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.refreshConfig", - "type": "Object", + "id": "def-public.DashboardConstants.CREATE_NEW_DASHBOARD_URL", + "type": "string", "tags": [], - "label": "refreshConfig", + "label": "CREATE_NEW_DASHBOARD_URL", "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", - "section": "def-common.RefreshInterval", - "text": "RefreshInterval" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.isEmbeddedExternally", - "type": "CompoundType", + "id": "def-public.DashboardConstants.VIEW_DASHBOARD_URL", + "type": "string", "tags": [], - "label": "isEmbeddedExternally", + "label": "VIEW_DASHBOARD_URL", "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.isFullScreenMode", - "type": "boolean", + "id": "def-public.DashboardConstants.PRINT_DASHBOARD_URL", + "type": "string", "tags": [], - "label": "isFullScreenMode", + "label": "PRINT_DASHBOARD_URL", "description": [], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.expandedPanelId", + "id": "def-public.DashboardConstants.ADD_EMBEDDABLE_ID", "type": "string", "tags": [], - "label": "expandedPanelId", + "label": "ADD_EMBEDDABLE_ID", "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.timeRange", - "type": "Object", + "id": "def-public.DashboardConstants.ADD_EMBEDDABLE_TYPE", + "type": "string", "tags": [], - "label": "timeRange", + "label": "ADD_EMBEDDABLE_TYPE", "description": [], - "signature": [ - "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.timeslice", - "type": "Object", + "id": "def-public.DashboardConstants.DASHBOARDS_ID", + "type": "string", "tags": [], - "label": "timeslice", + "label": "DASHBOARDS_ID", "description": [], - "signature": [ - "[number, number] | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.timeRestore", - "type": "boolean", + "id": "def-public.DashboardConstants.DASHBOARD_ID", + "type": "string", "tags": [], - "label": "timeRestore", + "label": "DASHBOARD_ID", "description": [], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.description", + "id": "def-public.DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE", "type": "string", "tags": [], - "label": "description", + "label": "DASHBOARD_SAVED_OBJECT_TYPE", "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.useMargins", - "type": "boolean", + "id": "def-public.DashboardConstants.SEARCH_SESSION_ID", + "type": "string", "tags": [], - "label": "useMargins", + "label": "SEARCH_SESSION_ID", "description": [], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.syncColors", - "type": "CompoundType", + "id": "def-public.DashboardConstants.CHANGE_CHECK_DEBOUNCE", + "type": "number", "tags": [], - "label": "syncColors", + "label": "CHANGE_CHECK_DEBOUNCE", "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.syncTooltips", - "type": "CompoundType", + "id": "def-public.DashboardConstants.CHANGE_APPLY_DEBOUNCE", + "type": "number", "tags": [], - "label": "syncTooltips", + "label": "CHANGE_APPLY_DEBOUNCE", "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/public/dashboard_constants.ts", "deprecated": false, "trackAdoption": false - }, + } + ], + "initialIsOpen": false + } + ], + "setup": { + "parentPluginId": "dashboard", + "id": "def-public.DashboardSetup", + "type": "Interface", + "tags": [], + "label": "DashboardSetup", + "description": [], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardSetup.locator", + "type": "Object", + "tags": [], + "label": "locator", + "description": [], + "signature": [ + { + "pluginId": "dashboard", + "scope": "public", + "docId": "kibDashboardPluginApi", + "section": "def-public.DashboardAppLocator", + "text": "DashboardAppLocator" + }, + " | undefined" + ], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "lifecycle": "setup", + "initialIsOpen": true + }, + "start": { + "parentPluginId": "dashboard", + "id": "def-public.DashboardStart", + "type": "Interface", + "tags": [], + "label": "DashboardStart", + "description": [], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardStart.getDashboardContainerByValueRenderer", + "type": "Function", + "tags": [], + "label": "getDashboardContainerByValueRenderer", + "description": [], + "signature": [ + "() => React.FC" + ], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [], + "returnComment": [] + }, + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardStart.locator", + "type": "Object", + "tags": [], + "label": "locator", + "description": [], + "signature": [ + { + "pluginId": "dashboard", + "scope": "public", + "docId": "kibDashboardPluginApi", + "section": "def-public.DashboardAppLocator", + "text": "DashboardAppLocator" + }, + " | undefined" + ], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-public.DashboardStart.dashboardFeatureFlagConfig", + "type": "Object", + "tags": [], + "label": "dashboardFeatureFlagConfig", + "description": [], + "signature": [ + { + "pluginId": "dashboard", + "scope": "public", + "docId": "kibDashboardPluginApi", + "section": "def-public.DashboardFeatureFlagConfig", + "text": "DashboardFeatureFlagConfig" + } + ], + "path": "src/plugins/dashboard/public/plugin.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "lifecycle": "start", + "initialIsOpen": true + } + }, + "server": { + "classes": [], + "functions": [ + { + "parentPluginId": "dashboard", + "id": "def-server.findByValueEmbeddables", + "type": "Function", + "tags": [], + "label": "findByValueEmbeddables", + "description": [], + "signature": [ + "(savedObjectClient: Pick<", + "ISavedObjectsRepository", + ", \"find\">, embeddableType: string) => Promise<{ [key: string]: ", + "Serializable", + "; }[]>" + ], + "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.viewMode", - "type": "Enum", + "id": "def-server.findByValueEmbeddables.$1", + "type": "Object", "tags": [], - "label": "viewMode", + "label": "savedObjectClient", "description": [], "signature": [ - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.ViewMode", - "text": "ViewMode" - } + "Pick<", + "ISavedObjectsRepository", + ", \"find\">" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.filters", - "type": "Array", + "id": "def-server.findByValueEmbeddables.$2", + "type": "string", "tags": [], - "label": "filters", + "label": "embeddableType", "description": [], "signature": [ - "Filter", - "[]" + "string" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + } + ], + "interfaces": [], + "enums": [], + "misc": [], + "objects": [], + "setup": { + "parentPluginId": "dashboard", + "id": "def-server.DashboardPluginSetup", + "type": "Interface", + "tags": [], + "label": "DashboardPluginSetup", + "description": [], + "path": "src/plugins/dashboard/server/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "lifecycle": "setup", + "initialIsOpen": true + }, + "start": { + "parentPluginId": "dashboard", + "id": "def-server.DashboardPluginStart", + "type": "Interface", + "tags": [], + "label": "DashboardPluginStart", + "description": [], + "path": "src/plugins/dashboard/server/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "lifecycle": "start", + "initialIsOpen": true + } + }, + "common": { + "classes": [], + "functions": [ + { + "parentPluginId": "dashboard", + "id": "def-common.convertPanelMapToSavedPanels", + "type": "Function", + "tags": [], + "label": "convertPanelMapToSavedPanels", + "description": [], + "signature": [ + "(panels: ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelMap", + "text": "DashboardPanelMap" + }, + ", version: string) => ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" }, + "[]" + ], + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.title", - "type": "string", + "id": "def-common.convertPanelMapToSavedPanels.$1", + "type": "Object", "tags": [], - "label": "title", + "label": "panels", "description": [], - "path": "src/plugins/dashboard/public/types.ts", + "signature": [ + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelMap", + "text": "DashboardPanelMap" + } + ], + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.query", - "type": "Object", + "id": "def-common.convertPanelMapToSavedPanels.$2", + "type": "string", "tags": [], - "label": "query", + "label": "version", "description": [], "signature": [ - "{ query: string | { [key: string]: any; }; language: string; }" + "string" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.convertPanelStateToSavedDashboardPanel", + "type": "Function", + "tags": [], + "label": "convertPanelStateToSavedDashboardPanel", + "description": [], + "signature": [ + "(panelState: ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" + }, + "<", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.SavedObjectEmbeddableInput", + "text": "SavedObjectEmbeddableInput" }, + ">, version: string) => ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" + } + ], + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.panels", + "id": "def-common.convertPanelStateToSavedDashboardPanel.$1", "type": "Object", "tags": [], - "label": "panels", + "label": "panelState", "description": [], "signature": [ - "{ [panelId: string]: ", - "DashboardPanelState", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" + }, "<", { "pluginId": "embeddable", "scope": "common", "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableInput", - "text": "EmbeddableInput" + "section": "def-common.SavedObjectEmbeddableInput", + "text": "SavedObjectEmbeddableInput" }, - " & { [k: string]: unknown; }>; }" + ">" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardContainerInput.executionContext", - "type": "Object", + "id": "def-common.convertPanelStateToSavedDashboardPanel.$2", + "type": "string", "tags": [], - "label": "executionContext", + "label": "version", "description": [], "signature": [ - "KibanaExecutionContext", - " | undefined" + "string" ], - "path": "src/plugins/dashboard/public/types.ts", + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true } ], + "returnComment": [], "initialIsOpen": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardFeatureFlagConfig", - "type": "Interface", + "id": "def-common.convertSavedDashboardPanelToPanelState", + "type": "Function", "tags": [], - "label": "DashboardFeatureFlagConfig", + "label": "convertSavedDashboardPanelToPanelState", "description": [], - "path": "src/plugins/dashboard/public/plugin.tsx", + "signature": [ + "(savedDashboardPanel: ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" + }, + ") => ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" + }, + "" + ], + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardFeatureFlagConfig.allowByValueEmbeddables", - "type": "boolean", + "id": "def-common.convertSavedDashboardPanelToPanelState.$1", + "type": "Object", "tags": [], - "label": "allowByValueEmbeddables", + "label": "savedDashboardPanel", "description": [], - "path": "src/plugins/dashboard/public/plugin.tsx", + "signature": [ + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" + } + ], + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true } ], + "returnComment": [], "initialIsOpen": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject", - "type": "Interface", + "id": "def-common.convertSavedPanelsToPanelMap", + "type": "Function", "tags": [], - "label": "DashboardSavedObject", + "label": "convertSavedPanelsToPanelMap", "description": [], "signature": [ + "(panels?: ", { "pluginId": "dashboard", - "scope": "public", + "scope": "common", "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardSavedObject", - "text": "DashboardSavedObject" + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" }, - " extends ", + "[] | undefined) => ", { - "pluginId": "savedObjects", - "scope": "public", - "docId": "kibSavedObjectsPluginApi", - "section": "def-public.SavedObject", - "text": "SavedObject" - }, - "<", - "SavedObjectAttributes", - ">" + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelMap", + "text": "DashboardPanelMap" + } ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.id", - "type": "string", + "id": "def-common.convertSavedPanelsToPanelMap.$1", + "type": "Array", "tags": [], - "label": "id", + "label": "panels", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.SavedDashboardPanel", + "text": "SavedDashboardPanel" + }, + "[] | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/lib/dashboard_panel_converters.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": false + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.createExtract", + "type": "Function", + "tags": [], + "label": "createExtract", + "description": [], + "signature": [ + "(persistableStateService: ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddablePersistableStateService", + "text": "EmbeddablePersistableStateService" }, + ") => (state: ", { - "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.timeRestore", - "type": "boolean", - "tags": [], - "label": "timeRestore", - "description": [], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", - "deprecated": false, - "trackAdoption": false + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableStateWithType", + "text": "EmbeddableStateWithType" + }, + ") => { state: ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableStateWithType", + "text": "EmbeddableStateWithType" }, + "; references: ", + "SavedObjectReference", + "[]; }" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.timeTo", - "type": "string", + "id": "def-common.createExtract.$1", + "type": "Object", "tags": [], - "label": "timeTo", + "label": "persistableStateService", "description": [], "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", - "deprecated": false, - "trackAdoption": false - }, + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddablePersistableStateService", + "text": "EmbeddablePersistableStateService" + } + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.createInject", + "type": "Function", + "tags": [], + "label": "createInject", + "description": [], + "signature": [ + "(persistableStateService: ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddablePersistableStateService", + "text": "EmbeddablePersistableStateService" + }, + ") => (state: ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableStateWithType", + "text": "EmbeddableStateWithType" + }, + ", references: ", + "SavedObjectReference", + "[]) => ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableStateWithType", + "text": "EmbeddableStateWithType" + } + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.timeFrom", - "type": "string", + "id": "def-common.createInject.$1", + "type": "Object", "tags": [], - "label": "timeFrom", + "label": "persistableStateService", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddablePersistableStateService", + "text": "EmbeddablePersistableStateService" + } + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.extractReferences", + "type": "Function", + "tags": [], + "label": "extractReferences", + "description": [], + "signature": [ + "({ attributes, references = [] }: SavedObjectAttributesAndReferences, deps: ", + "ExtractDeps", + ") => SavedObjectAttributesAndReferences" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-common.extractReferences.$1", + "type": "Object", + "tags": [], + "label": "{ attributes, references = [] }", + "description": [], + "signature": [ + "SavedObjectAttributesAndReferences" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "dashboard", + "id": "def-common.extractReferences.$2", + "type": "Object", + "tags": [], + "label": "deps", + "description": [], + "signature": [ + "ExtractDeps" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.injectReferences", + "type": "Function", + "tags": [], + "label": "injectReferences", + "description": [], + "signature": [ + "({ attributes, references = [] }: SavedObjectAttributesAndReferences, deps: ", + "InjectDeps", + ") => ", + "SavedObjectAttributes" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-common.injectReferences.$1", + "type": "Object", + "tags": [], + "label": "{ attributes, references = [] }", + "description": [], + "signature": [ + "SavedObjectAttributesAndReferences" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "dashboard", + "id": "def-common.injectReferences.$2", + "type": "Object", + "tags": [], + "label": "deps", + "description": [], + "signature": [ + "InjectDeps" + ], + "path": "src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + } + ], + "interfaces": [ + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes", + "type": "Interface", + "tags": [], + "label": "DashboardAttributes", + "description": [ + "\nThe attributes of the dashboard saved object. This interface should be the\nsource of truth for the latest dashboard attributes shape after all migrations." + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes.controlGroupInput", + "type": "CompoundType", + "tags": [], + "label": "controlGroupInput", + "description": [], + "signature": [ + { + "pluginId": "controls", + "scope": "common", + "docId": "kibControlsPluginApi", + "section": "def-common.RawControlGroupAttributes", + "text": "RawControlGroupAttributes" + }, + " | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.description", - "type": "string", + "id": "def-common.DashboardAttributes.refreshInterval", + "type": "Object", "tags": [], - "label": "description", + "label": "refreshInterval", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataQueryPluginApi", + "section": "def-common.RefreshInterval", + "text": "RefreshInterval" + }, + " | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.panelsJSON", - "type": "string", + "id": "def-common.DashboardAttributes.timeRestore", + "type": "boolean", "tags": [], - "label": "panelsJSON", + "label": "timeRestore", "description": [], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.optionsJSON", + "id": "def-common.DashboardAttributes.optionsJSON", "type": "string", "tags": [], "label": "optionsJSON", @@ -1710,687 +1581,501 @@ "signature": [ "string | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes.useMargins", + "type": "CompoundType", + "tags": [], + "label": "useMargins", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes.description", + "type": "string", + "tags": [], + "label": "description", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes.panelsJSON", + "type": "string", + "tags": [], + "label": "panelsJSON", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.uiStateJSON", + "id": "def-common.DashboardAttributes.timeFrom", "type": "string", "tags": [], - "label": "uiStateJSON", + "label": "timeFrom", "description": [], "signature": [ "string | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.lastSavedTitle", - "type": "string", + "id": "def-common.DashboardAttributes.version", + "type": "number", "tags": [], - "label": "lastSavedTitle", + "label": "version", "description": [], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.refreshInterval", - "type": "Object", + "id": "def-common.DashboardAttributes.timeTo", + "type": "string", "tags": [], - "label": "refreshInterval", + "label": "timeTo", "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", - "section": "def-common.RefreshInterval", - "text": "RefreshInterval" - }, - " | undefined" + "string | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardAttributes.title", + "type": "string", + "tags": [], + "label": "title", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.searchSource", + "id": "def-common.DashboardAttributes.kibanaSavedObjectMeta", "type": "Object", "tags": [], - "label": "searchSource", + "label": "kibanaSavedObjectMeta", "description": [], "signature": [ - "{ create: () => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; history: ", - "SearchRequest", - "[]; setOverwriteDataViewType: (overwriteType: string | false | undefined) => void; setField: (field: K, value: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceFields", - "text": "SearchSourceFields" - }, - "[K]) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; removeField: (field: K) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; setFields: (newFields: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceFields", - "text": "SearchSourceFields" - }, - ") => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; getId: () => string; getFields: () => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceFields", - "text": "SearchSourceFields" - }, - "; getField: (field: K, recurse?: boolean) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceFields", - "text": "SearchSourceFields" - }, - "[K]; getActiveIndexFilter: () => string[]; getOwnField: (field: K) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceFields", - "text": "SearchSourceFields" - }, - "[K]; createCopy: () => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; createChild: (options?: {}) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; setParent: (parent?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.ISearchSource", - "text": "ISearchSource" - }, - " | undefined, options?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceOptions", - "text": "SearchSourceOptions" - }, - ") => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - "; getParent: () => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - " | undefined; fetch$: (options?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceSearchOptions", - "text": "SearchSourceSearchOptions" - }, - ") => ", - "Observable", - "<", + "{ searchSourceJSON: string; }" + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardContainerStateWithType", + "type": "Interface", + "tags": [], + "label": "DashboardContainerStateWithType", + "description": [ + "--------------------------------------------------------------------\nDashboard container types\n -----------------------------------------------------------------------\n\nTypes below this line are copied here because so many important types are tied up in public. These types should be\nmoved from public into common." + ], + "signature": [ + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardContainerStateWithType", + "text": "DashboardContainerStateWithType" + }, + " extends ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableStateWithType", + "text": "EmbeddableStateWithType" + } + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardContainerStateWithType.panels", + "type": "Object", + "tags": [], + "label": "panels", + "description": [], + "signature": [ + "{ [panelId: string]: ", { - "pluginId": "data", + "pluginId": "dashboard", "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.IKibanaSearchResponse", - "text": "IKibanaSearchResponse" + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" }, "<", - "SearchResponse", - ">>>; fetch: (options?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceSearchOptions", - "text": "SearchSourceSearchOptions" - }, - ") => Promise<", - "SearchResponse", - ">>; onRequestStart: (handler: (searchSource: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSource", - "text": "SearchSource" - }, - ", options?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SearchSourceSearchOptions", - "text": "SearchSourceSearchOptions" - }, - " | undefined) => Promise) => void; getSearchRequestBody: () => any; destroy: () => void; getSerializedFields: (recurse?: boolean) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.SerializedSearchSourceFields", - "text": "SerializedSearchSourceFields" - }, - "; serialize: () => { searchSourceJSON: string; references: ", - "SavedObjectReference", - "[]; }; toExpressionAst: ({ asDatatable }?: ExpressionAstOptions) => ", { - "pluginId": "expressions", + "pluginId": "embeddable", "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.ExpressionAstExpression", - "text": "ExpressionAstExpression" + "docId": "kibEmbeddablePluginApi", + "section": "def-common.EmbeddableInput", + "text": "EmbeddableInput" }, - "; parseActiveIndexPatternFromQueryString: (queryString: string) => string[]; }" + " & { [k: string]: unknown; }>; }" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.getQuery", - "type": "Function", + "id": "def-common.DashboardContainerStateWithType.controlGroupInput", + "type": "Object", "tags": [], - "label": "getQuery", + "label": "controlGroupInput", "description": [], "signature": [ - "() => ", - "Query" + { + "pluginId": "controls", + "scope": "common", + "docId": "kibControlsPluginApi", + "section": "def-common.PersistableControlGroupInput", + "text": "PersistableControlGroupInput" + }, + " | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] - }, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardPanelMap", + "type": "Interface", + "tags": [], + "label": "DashboardPanelMap", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.getFilters", - "type": "Function", + "id": "def-common.DashboardPanelMap.Unnamed", + "type": "IndexSignature", "tags": [], - "label": "getFilters", + "label": "[key: string]: DashboardPanelState", "description": [], "signature": [ - "() => ", - "Filter", - "[]" + "[key: string]: ", + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" + }, + "<", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.SavedObjectEmbeddableInput", + "text": "SavedObjectEmbeddableInput" + }, + ">" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.DashboardPanelState", + "type": "Interface", + "tags": [], + "label": "DashboardPanelState", + "description": [ + "--------------------------------------------------------------------\nDashboard panel types\n -----------------------------------------------------------------------\n\nThe dashboard panel format expected by the embeddable container." + ], + "signature": [ + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.DashboardPanelState", + "text": "DashboardPanelState" }, + " extends ", + { + "pluginId": "embeddable", + "scope": "common", + "docId": "kibEmbeddablePluginApi", + "section": "def-common.PanelState", + "text": "PanelState" + }, + "" + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.getFullEditPath", - "type": "Function", + "id": "def-common.DashboardPanelState.gridData", + "type": "Object", "tags": [], - "label": "getFullEditPath", + "label": "gridData", "description": [], "signature": [ - "(editMode?: boolean | undefined) => string" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { - "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.getFullEditPath.$1", - "type": "CompoundType", - "tags": [], - "label": "editMode", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": false + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.GridData", + "text": "GridData" } ], - "returnComment": [] + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.outcome", - "type": "CompoundType", + "id": "def-common.DashboardPanelState.panelRefName", + "type": "string", "tags": [], - "label": "outcome", + "label": "panelRefName", "description": [], "signature": [ - "\"exactMatch\" | \"aliasMatch\" | \"conflict\" | undefined" + "string | undefined" ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false - }, + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "dashboard", + "id": "def-common.GridData", + "type": "Interface", + "tags": [], + "label": "GridData", + "description": [ + "\nGrid type for React Grid Layout" + ], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.aliasId", - "type": "string", + "id": "def-common.GridData.w", + "type": "number", "tags": [], - "label": "aliasId", + "label": "w", "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.aliasPurpose", - "type": "CompoundType", + "id": "def-common.GridData.h", + "type": "number", "tags": [], - "label": "aliasPurpose", + "label": "h", "description": [], - "signature": [ - "\"savedObjectConversion\" | \"savedObjectImport\" | undefined" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardSavedObject.controlGroupInput", - "type": "Object", + "id": "def-common.GridData.x", + "type": "number", "tags": [], - "label": "controlGroupInput", + "label": "x", "description": [], - "signature": [ - "Omit<", - { - "pluginId": "controls", - "scope": "common", - "docId": "kibControlsPluginApi", - "section": "def-common.RawControlGroupAttributes", - "text": "RawControlGroupAttributes" - }, - ", \"id\"> | undefined" - ], - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - } - ], - "enums": [], - "misc": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DASHBOARD_CONTAINER_TYPE", - "type": "string", - "tags": [], - "label": "DASHBOARD_CONTAINER_TYPE", - "description": [], - "signature": [ - "\"dashboard\"" - ], - "path": "src/plugins/dashboard/public/application/embeddable/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardAppLocator", - "type": "Type", - "tags": [], - "label": "DashboardAppLocator", - "description": [], - "signature": [ - { - "pluginId": "share", - "scope": "common", - "docId": "kibSharePluginApi", - "section": "def-common.LocatorPublic", - "text": "LocatorPublic" - }, - "<", - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardAppLocatorParams", - "text": "DashboardAppLocatorParams" - }, - ">" - ], - "path": "src/plugins/dashboard/public/locator.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardAppLocatorParams", - "type": "Type", - "tags": [], - "label": "DashboardAppLocatorParams", - "description": [ - "\nWe use `type` instead of `interface` to avoid having to extend this type with\n`SerializableRecord`. See https://github.com/microsoft/TypeScript/issues/15300." - ], - "signature": [ - "{ dashboardId?: string | undefined; timeRange?: ", - "TimeRange", - " | undefined; refreshInterval?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", - "section": "def-common.RefreshInterval", - "text": "RefreshInterval" - }, - " | undefined; filters?: ", - "Filter", - "[] | undefined; query?: ", - "Query", - " | undefined; useHash?: boolean | undefined; preserveSavedFilters?: boolean | undefined; viewMode?: ", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.ViewMode", - "text": "ViewMode" }, - " | undefined; searchSessionId?: string | undefined; panels?: ", { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel730ToLatest", - "text": "SavedDashboardPanel730ToLatest" + "parentPluginId": "dashboard", + "id": "def-common.GridData.y", + "type": "number", + "tags": [], + "label": "y", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false }, - "[] | undefined; savedQuery?: string | undefined; tags?: string[] | undefined; options?: ", - "DashboardOptions", - " | undefined; controlGroupInput?: ", { - "pluginId": "controls", - "scope": "common", - "docId": "kibControlsPluginApi", - "section": "def-common.SerializableControlGroupInput", - "text": "SerializableControlGroupInput" - }, - " | undefined; }" + "parentPluginId": "dashboard", + "id": "def-common.GridData.i", + "type": "string", + "tags": [], + "label": "i", + "description": [], + "path": "src/plugins/dashboard/common/types.ts", + "deprecated": false, + "trackAdoption": false + } ], - "path": "src/plugins/dashboard/public/locator.ts", - "deprecated": false, - "trackAdoption": false, "initialIsOpen": false }, { "parentPluginId": "dashboard", - "id": "def-public.SavedDashboardPanel", - "type": "Type", + "id": "def-common.SavedDashboardPanel", + "type": "Interface", "tags": [], "label": "SavedDashboardPanel", "description": [ - "\nThis should always represent the latest dashboard panel shape, after all possible migrations." - ], - "signature": [ - "Pick<", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.RawSavedDashboardPanel730ToLatest", - "text": "RawSavedDashboardPanel730ToLatest" - }, - ", \"type\" | \"title\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\" | \"panelRefName\"> & { readonly id?: string | undefined; readonly type: string; }" + "\nA saved dashboard panel parsed directly from the Dashboard Attributes panels JSON" ], "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false, - "initialIsOpen": false - } - ], - "objects": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants", - "type": "Object", - "tags": [], - "label": "DashboardConstants", - "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false, "children": [ { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.LANDING_PAGE_PATH", - "type": "string", - "tags": [], - "label": "LANDING_PAGE_PATH", - "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.CREATE_NEW_DASHBOARD_URL", - "type": "string", + "id": "def-common.SavedDashboardPanel.embeddableConfig", + "type": "Object", "tags": [], - "label": "CREATE_NEW_DASHBOARD_URL", + "label": "embeddableConfig", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "signature": [ + "{ [key: string]: ", + "Serializable", + "; }" + ], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.VIEW_DASHBOARD_URL", + "id": "def-common.SavedDashboardPanel.id", "type": "string", "tags": [], - "label": "VIEW_DASHBOARD_URL", + "label": "id", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "signature": [ + "string | undefined" + ], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.PRINT_DASHBOARD_URL", + "id": "def-common.SavedDashboardPanel.type", "type": "string", "tags": [], - "label": "PRINT_DASHBOARD_URL", + "label": "type", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.ADD_EMBEDDABLE_ID", + "id": "def-common.SavedDashboardPanel.panelRefName", "type": "string", "tags": [], - "label": "ADD_EMBEDDABLE_ID", + "label": "panelRefName", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "signature": [ + "string | undefined" + ], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.ADD_EMBEDDABLE_TYPE", - "type": "string", + "id": "def-common.SavedDashboardPanel.gridData", + "type": "Object", "tags": [], - "label": "ADD_EMBEDDABLE_TYPE", + "label": "gridData", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "signature": [ + { + "pluginId": "dashboard", + "scope": "common", + "docId": "kibDashboardPluginApi", + "section": "def-common.GridData", + "text": "GridData" + } + ], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.DASHBOARDS_ID", + "id": "def-common.SavedDashboardPanel.panelIndex", "type": "string", "tags": [], - "label": "DASHBOARDS_ID", + "label": "panelIndex", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.DASHBOARD_ID", + "id": "def-common.SavedDashboardPanel.version", "type": "string", "tags": [], - "label": "DASHBOARD_ID", + "label": "version", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.SEARCH_SESSION_ID", + "id": "def-common.SavedDashboardPanel.title", "type": "string", "tags": [], - "label": "SEARCH_SESSION_ID", - "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.CHANGE_CHECK_DEBOUNCE", - "type": "number", - "tags": [], - "label": "CHANGE_CHECK_DEBOUNCE", - "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardConstants.CHANGE_APPLY_DEBOUNCE", - "type": "number", - "tags": [], - "label": "CHANGE_APPLY_DEBOUNCE", + "label": "title", "description": [], - "path": "src/plugins/dashboard/public/dashboard_constants.ts", + "signature": [ + "string | undefined" + ], + "path": "src/plugins/dashboard/common/types.ts", "deprecated": false, "trackAdoption": false } @@ -2398,674 +2083,8 @@ "initialIsOpen": false } ], - "setup": { - "parentPluginId": "dashboard", - "id": "def-public.DashboardSetup", - "type": "Interface", - "tags": [], - "label": "DashboardSetup", - "description": [], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardSetup.locator", - "type": "Object", - "tags": [], - "label": "locator", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardAppLocator", - "text": "DashboardAppLocator" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false - } - ], - "lifecycle": "setup", - "initialIsOpen": true - }, - "start": { - "parentPluginId": "dashboard", - "id": "def-public.DashboardStart", - "type": "Interface", - "tags": [], - "label": "DashboardStart", - "description": [], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardStart.getSavedDashboardLoader", - "type": "Function", - "tags": [], - "label": "getSavedDashboardLoader", - "description": [], - "signature": [ - "() => ", - "SavedObjectLoader" - ], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardStart.getDashboardContainerByValueRenderer", - "type": "Function", - "tags": [], - "label": "getDashboardContainerByValueRenderer", - "description": [], - "signature": [ - "() => React.FC" - ], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardStart.locator", - "type": "Object", - "tags": [], - "label": "locator", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardAppLocator", - "text": "DashboardAppLocator" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-public.DashboardStart.dashboardFeatureFlagConfig", - "type": "Object", - "tags": [], - "label": "dashboardFeatureFlagConfig", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "public", - "docId": "kibDashboardPluginApi", - "section": "def-public.DashboardFeatureFlagConfig", - "text": "DashboardFeatureFlagConfig" - } - ], - "path": "src/plugins/dashboard/public/plugin.tsx", - "deprecated": false, - "trackAdoption": false - } - ], - "lifecycle": "start", - "initialIsOpen": true - } - }, - "server": { - "classes": [], - "functions": [ - { - "parentPluginId": "dashboard", - "id": "def-server.findByValueEmbeddables", - "type": "Function", - "tags": [], - "label": "findByValueEmbeddables", - "description": [], - "signature": [ - "(savedObjectClient: Pick<", - "ISavedObjectsRepository", - ", \"find\">, embeddableType: string) => Promise<{ [key: string]: ", - "Serializable", - "; }[]>" - ], - "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-server.findByValueEmbeddables.$1", - "type": "Object", - "tags": [], - "label": "savedObjectClient", - "description": [], - "signature": [ - "Pick<", - "ISavedObjectsRepository", - ", \"find\">" - ], - "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-server.findByValueEmbeddables.$2", - "type": "string", - "tags": [], - "label": "embeddableType", - "description": [], - "signature": [ - "string" - ], - "path": "src/plugins/dashboard/server/usage/find_by_value_embeddables.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [], - "initialIsOpen": false - } - ], - "interfaces": [], "enums": [], "misc": [], - "objects": [], - "setup": { - "parentPluginId": "dashboard", - "id": "def-server.DashboardPluginSetup", - "type": "Interface", - "tags": [], - "label": "DashboardPluginSetup", - "description": [], - "path": "src/plugins/dashboard/server/types.ts", - "deprecated": false, - "trackAdoption": false, - "children": [], - "lifecycle": "setup", - "initialIsOpen": true - }, - "start": { - "parentPluginId": "dashboard", - "id": "def-server.DashboardPluginStart", - "type": "Interface", - "tags": [], - "label": "DashboardPluginStart", - "description": [], - "path": "src/plugins/dashboard/server/types.ts", - "deprecated": false, - "trackAdoption": false, - "children": [], - "lifecycle": "start", - "initialIsOpen": true - } - }, - "common": { - "classes": [], - "functions": [ - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730", - "type": "Function", - "tags": [], - "label": "migratePanelsTo730", - "description": [], - "signature": [ - "(panels: (", - "RawSavedDashboardPanelTo60", - " | ", - "RawSavedDashboardPanel610", - " | ", - "RawSavedDashboardPanel620", - " | ", - "RawSavedDashboardPanel640To720", - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanelTo60", - "text": "SavedDashboardPanelTo60" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel610", - "text": "SavedDashboardPanel610" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel620", - "text": "SavedDashboardPanel620" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel630", - "text": "SavedDashboardPanel630" - }, - ")[], version: string, useMargins: boolean, uiState: { [key: string]: ", - "SerializableRecord", - "; } | undefined) => ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.RawSavedDashboardPanel730ToLatest", - "text": "RawSavedDashboardPanel730ToLatest" - }, - "[]" - ], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730.$1", - "type": "Array", - "tags": [], - "label": "panels", - "description": [], - "signature": [ - "(", - "RawSavedDashboardPanelTo60", - " | ", - "RawSavedDashboardPanel610", - " | ", - "RawSavedDashboardPanel620", - " | ", - "RawSavedDashboardPanel640To720", - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanelTo60", - "text": "SavedDashboardPanelTo60" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel610", - "text": "SavedDashboardPanel610" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel620", - "text": "SavedDashboardPanel620" - }, - " | ", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.SavedDashboardPanel630", - "text": "SavedDashboardPanel630" - }, - ")[]" - ], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730.$2", - "type": "string", - "tags": [], - "label": "version", - "description": [], - "signature": [ - "string" - ], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730.$3", - "type": "boolean", - "tags": [], - "label": "useMargins", - "description": [], - "signature": [ - "boolean" - ], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730.$4", - "type": "Object", - "tags": [], - "label": "uiState", - "description": [], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-common.migratePanelsTo730.$4.Unnamed", - "type": "IndexSignature", - "tags": [], - "label": "[key: string]: SerializableRecord", - "description": [], - "signature": [ - "[key: string]: ", - "SerializableRecord" - ], - "path": "src/plugins/dashboard/common/migrate_to_730_panels.ts", - "deprecated": false, - "trackAdoption": false - } - ] - } - ], - "returnComment": [], - "initialIsOpen": false - } - ], - "interfaces": [ - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardContainerStateWithType", - "type": "Interface", - "tags": [], - "label": "DashboardContainerStateWithType", - "description": [], - "signature": [ - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.DashboardContainerStateWithType", - "text": "DashboardContainerStateWithType" - }, - " extends ", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableStateWithType", - "text": "EmbeddableStateWithType" - } - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardContainerStateWithType.panels", - "type": "Object", - "tags": [], - "label": "panels", - "description": [], - "signature": [ - "{ [panelId: string]: ", - "DashboardPanelState", - "<", - { - "pluginId": "embeddable", - "scope": "common", - "docId": "kibEmbeddablePluginApi", - "section": "def-common.EmbeddableInput", - "text": "EmbeddableInput" - }, - " & { [k: string]: unknown; }>; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardContainerStateWithType.controlGroupInput", - "type": "Object", - "tags": [], - "label": "controlGroupInput", - "description": [], - "signature": [ - { - "pluginId": "controls", - "scope": "common", - "docId": "kibControlsPluginApi", - "section": "def-common.PersistableControlGroupInput", - "text": "PersistableControlGroupInput" - }, - " | undefined" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false - } - ], - "initialIsOpen": false - } - ], - "enums": [], - "misc": [ - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardDoc700To720", - "type": "Type", - "tags": [], - "label": "DashboardDoc700To720", - "description": [], - "signature": [ - "Doc" - ], - "path": "src/plugins/dashboard/common/bwc/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardDoc730ToLatest", - "type": "Type", - "tags": [], - "label": "DashboardDoc730ToLatest", - "description": [], - "signature": [ - "Doc" - ], - "path": "src/plugins/dashboard/common/bwc/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.DashboardDocPre700", - "type": "Type", - "tags": [], - "label": "DashboardDocPre700", - "description": [], - "signature": [ - "DocPre700" - ], - "path": "src/plugins/dashboard/common/bwc/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.GridData", - "type": "Type", - "tags": [], - "label": "GridData", - "description": [], - "signature": [ - "{ w: number; h: number; x: number; y: number; i: string; }" - ], - "path": "src/plugins/dashboard/common/embeddable/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.RawSavedDashboardPanel730ToLatest", - "type": "Type", - "tags": [], - "label": "RawSavedDashboardPanel730ToLatest", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanel640To720", - ", \"title\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\"> & { readonly type?: string | undefined; readonly name?: string | undefined; panelIndex: string; panelRefName?: string | undefined; }" - ], - "path": "src/plugins/dashboard/common/bwc/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanel610", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanel610", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanel610", - ", \"columns\" | \"title\" | \"sort\" | \"panelIndex\" | \"gridData\" | \"version\"> & { readonly id: string; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanel620", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanel620", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanel620", - ", \"columns\" | \"title\" | \"sort\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\"> & { readonly id: string; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanel630", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanel630", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanel620", - ", \"columns\" | \"title\" | \"sort\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\"> & { readonly id: string; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanel640To720", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanel640To720", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanel640To720", - ", \"title\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\"> & { readonly id: string; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanel730ToLatest", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanel730ToLatest", - "description": [], - "signature": [ - "Pick<", - { - "pluginId": "dashboard", - "scope": "common", - "docId": "kibDashboardPluginApi", - "section": "def-common.RawSavedDashboardPanel730ToLatest", - "text": "RawSavedDashboardPanel730ToLatest" - }, - ", \"type\" | \"title\" | \"panelIndex\" | \"gridData\" | \"version\" | \"embeddableConfig\" | \"panelRefName\"> & { readonly id?: string | undefined; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "dashboard", - "id": "def-common.SavedDashboardPanelTo60", - "type": "Type", - "tags": [], - "label": "SavedDashboardPanelTo60", - "description": [], - "signature": [ - "Pick<", - "RawSavedDashboardPanelTo60", - ", \"columns\" | \"title\" | \"sort\" | \"size_x\" | \"size_y\" | \"row\" | \"col\" | \"panelIndex\"> & { readonly id: string; readonly type: string; }" - ], - "path": "src/plugins/dashboard/common/types.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - } - ], "objects": [ { "parentPluginId": "dashboard", diff --git a/api_docs/dashboard.mdx b/api_docs/dashboard.mdx index 4c0545dc4bbe4..7a36e763bfeac 100644 --- a/api_docs/dashboard.mdx +++ b/api_docs/dashboard.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dashboard title: "dashboard" image: https://source.unsplash.com/400x175/?github description: API docs for the dashboard plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dashboard'] --- import dashboardObj from './dashboard.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-prese | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 144 | 0 | 139 | 10 | +| 120 | 0 | 113 | 3 | ## Client @@ -37,9 +37,6 @@ Contact [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-prese ### Functions -### Classes - - ### Interfaces @@ -68,6 +65,3 @@ Contact [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-prese ### Interfaces -### Consts, variables and types - - diff --git a/api_docs/dashboard_enhanced.mdx b/api_docs/dashboard_enhanced.mdx index 98f3e7141a10c..06821933db670 100644 --- a/api_docs/dashboard_enhanced.mdx +++ b/api_docs/dashboard_enhanced.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dashboardEnhanced title: "dashboardEnhanced" image: https://source.unsplash.com/400x175/?github description: API docs for the dashboardEnhanced plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dashboardEnhanced'] --- import dashboardEnhancedObj from './dashboard_enhanced.devdocs.json'; diff --git a/api_docs/data.devdocs.json b/api_docs/data.devdocs.json index bed0278714e2a..10ca74caf4ce6 100644 --- a/api_docs/data.devdocs.json +++ b/api_docs/data.devdocs.json @@ -9057,6 +9057,102 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "data", + "id": "def-public.ExpressionFunctionKql", + "type": "Type", + "tags": [], + "label": "ExpressionFunctionKql", + "description": [], + "signature": [ + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.ExpressionFunctionDefinition", + "text": "ExpressionFunctionDefinition" + }, + "<\"kql\", null, Arguments, ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.KibanaQueryOutput", + "text": "KibanaQueryOutput" + }, + ", ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.ExecutionContext", + "text": "ExecutionContext" + }, + "<", + { + "pluginId": "inspector", + "scope": "common", + "docId": "kibInspectorPluginApi", + "section": "def-common.Adapters", + "text": "Adapters" + }, + ", ", + "SerializableRecord", + ">>" + ], + "path": "src/plugins/data/common/search/expressions/kql.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-public.ExpressionFunctionLucene", + "type": "Type", + "tags": [], + "label": "ExpressionFunctionLucene", + "description": [], + "signature": [ + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.ExpressionFunctionDefinition", + "text": "ExpressionFunctionDefinition" + }, + "<\"lucene\", null, Arguments, ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.KibanaQueryOutput", + "text": "KibanaQueryOutput" + }, + ", ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.ExecutionContext", + "text": "ExecutionContext" + }, + "<", + { + "pluginId": "inspector", + "scope": "common", + "docId": "kibInspectorPluginApi", + "section": "def-common.Adapters", + "text": "Adapters" + }, + ", ", + "SerializableRecord", + ">>" + ], + "path": "src/plugins/data/common/search/expressions/lucene.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "data", "id": "def-public.ExpressionValueSearchContext", diff --git a/api_docs/data.mdx b/api_docs/data.mdx index e0f8e807ffb40..e5c75be5fa094 100644 --- a/api_docs/data.mdx +++ b/api_docs/data.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/data title: "data" image: https://source.unsplash.com/400x175/?github description: API docs for the data plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'data'] --- import dataObj from './data.devdocs.json'; @@ -21,7 +21,7 @@ Contact [App Services](https://github.com/orgs/elastic/teams/kibana-app-services | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 3132 | 33 | 2429 | 23 | +| 3213 | 33 | 2509 | 23 | ## Client diff --git a/api_docs/data_query.devdocs.json b/api_docs/data_query.devdocs.json index 2507050e905fc..051270f939554 100644 --- a/api_docs/data_query.devdocs.json +++ b/api_docs/data_query.devdocs.json @@ -1855,14 +1855,6 @@ "plugin": "discover", "path": "src/plugins/discover/public/application/main/services/discover_state.ts" }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts" - }, { "plugin": "maps", "path": "x-pack/plugins/maps/public/routes/map_page/url_state/global_sync.ts" @@ -3785,10 +3777,10 @@ }, { "parentPluginId": "data", - "id": "def-common.queryStateToExpressionAst", + "id": "def-common.textBasedQueryStateToAstWithValidation", "type": "Function", "tags": [], - "label": "queryStateToExpressionAst", + "label": "textBasedQueryStateToAstWithValidation", "description": [ "\nConverts QueryState to expression AST" ], @@ -3801,15 +3793,15 @@ "section": "def-common.ExpressionAstExpression", "text": "ExpressionAstExpression" }, - ">" + " | undefined>" ], - "path": "src/plugins/data/common/query/to_expression_ast.ts", + "path": "src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.queryStateToExpressionAst.$1", + "id": "def-common.textBasedQueryStateToAstWithValidation.$1", "type": "Object", "tags": [], "label": "{\n filters,\n query,\n inputQuery,\n time,\n dataViewsService,\n}", @@ -3817,7 +3809,49 @@ "signature": [ "Args" ], - "path": "src/plugins/data/common/query/to_expression_ast.ts", + "path": "src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.textBasedQueryStateToExpressionAst", + "type": "Function", + "tags": [], + "label": "textBasedQueryStateToExpressionAst", + "description": [ + "\nConverts QueryState to expression AST" + ], + "signature": [ + "({\n filters,\n query,\n inputQuery,\n time,\n timeFieldName,\n}: Args) => ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.ExpressionAstExpression", + "text": "ExpressionAstExpression" + } + ], + "path": "src/plugins/data/common/query/text_based_query_state_to_ast.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.textBasedQueryStateToExpressionAst.$1", + "type": "Object", + "tags": [], + "label": "{\n filters,\n query,\n inputQuery,\n time,\n timeFieldName,\n}", + "description": [], + "signature": [ + "Args" + ], + "path": "src/plugins/data/common/query/text_based_query_state_to_ast.ts", "deprecated": false, "trackAdoption": false, "isRequired": true diff --git a/api_docs/data_query.mdx b/api_docs/data_query.mdx index aefb0e297c65b..fdd7cb4298da4 100644 --- a/api_docs/data_query.mdx +++ b/api_docs/data_query.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/data-query title: "data.query" image: https://source.unsplash.com/400x175/?github description: API docs for the data.query plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'data.query'] --- import dataQueryObj from './data_query.devdocs.json'; @@ -21,7 +21,7 @@ Contact [App Services](https://github.com/orgs/elastic/teams/kibana-app-services | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 3132 | 33 | 2429 | 23 | +| 3213 | 33 | 2509 | 23 | ## Client diff --git a/api_docs/data_search.devdocs.json b/api_docs/data_search.devdocs.json index c3cfd123f1166..3be2133617864 100644 --- a/api_docs/data_search.devdocs.json +++ b/api_docs/data_search.devdocs.json @@ -2794,9 +2794,9 @@ "label": "options", "description": [], "signature": [ - "{ filter?: any; search?: string | undefined; aggs?: Record | undefined; fields?: string[] | undefined; searchAfter?: string[] | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", + "> | undefined; searchAfter?: string[] | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", "SortOrder", " | undefined; searchFields?: string[] | undefined; rootSearchFields?: string[] | undefined; hasReference?: ", "SavedObjectsFindOptionsReference", @@ -3475,13 +3475,7 @@ "label": "DataRequestHandlerContext", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { search: Promise<", { "pluginId": "data", @@ -18687,9 +18681,14 @@ "label": "customMetric", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], "path": "src/plugins/data/common/search/aggs/metrics/bucket_avg.ts", "deprecated": false, @@ -18703,9 +18702,14 @@ "label": "customBucket", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], "path": "src/plugins/data/common/search/aggs/metrics/bucket_avg.ts", "deprecated": false, @@ -18716,18 +18720,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMax", + "id": "def-common.AggParamsBucketAvgSerialized", "type": "Interface", "tags": [], - "label": "AggParamsBucketMax", + "label": "AggParamsBucketAvgSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsBucketMax", - "text": "AggParamsBucketMax" + "section": "def-common.AggParamsBucketAvgSerialized", + "text": "AggParamsBucketAvgSerialized" }, " extends ", { @@ -18738,13 +18742,13 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_avg.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMax.customMetric", + "id": "def-common.AggParamsBucketAvgSerialized.customMetric", "type": "Object", "tags": [], "label": "customMetric", @@ -18754,13 +18758,13 @@ "SerializableRecord", " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_avg.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMax.customBucket", + "id": "def-common.AggParamsBucketAvgSerialized.customBucket", "type": "Object", "tags": [], "label": "customBucket", @@ -18770,7 +18774,7 @@ "SerializableRecord", " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_avg.ts", "deprecated": false, "trackAdoption": false } @@ -18779,18 +18783,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMin", + "id": "def-common.AggParamsBucketMax", "type": "Interface", "tags": [], - "label": "AggParamsBucketMin", + "label": "AggParamsBucketMax", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsBucketMin", - "text": "AggParamsBucketMin" + "section": "def-common.AggParamsBucketMax", + "text": "AggParamsBucketMax" }, " extends ", { @@ -18801,39 +18805,49 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMin.customMetric", + "id": "def-common.AggParamsBucketMax.customMetric", "type": "Object", "tags": [], "label": "customMetric", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketMin.customBucket", + "id": "def-common.AggParamsBucketMax.customBucket", "type": "Object", "tags": [], "label": "customBucket", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false } @@ -18842,18 +18856,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketSum", + "id": "def-common.AggParamsBucketMaxSerialized", "type": "Interface", "tags": [], - "label": "AggParamsBucketSum", + "label": "AggParamsBucketMaxSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsBucketSum", - "text": "AggParamsBucketSum" + "section": "def-common.AggParamsBucketMaxSerialized", + "text": "AggParamsBucketMaxSerialized" }, " extends ", { @@ -18864,13 +18878,13 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsBucketSum.customMetric", + "id": "def-common.AggParamsBucketMaxSerialized.customMetric", "type": "Object", "tags": [], "label": "customMetric", @@ -18880,13 +18894,13 @@ "SerializableRecord", " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsBucketSum.customBucket", + "id": "def-common.AggParamsBucketMaxSerialized.customBucket", "type": "Object", "tags": [], "label": "customBucket", @@ -18896,7 +18910,7 @@ "SerializableRecord", " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_max.ts", "deprecated": false, "trackAdoption": false } @@ -18905,18 +18919,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsCardinality", + "id": "def-common.AggParamsBucketMin", "type": "Interface", "tags": [], - "label": "AggParamsCardinality", + "label": "AggParamsBucketMin", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsCardinality", - "text": "AggParamsCardinality" + "section": "def-common.AggParamsBucketMin", + "text": "AggParamsBucketMin" }, " extends ", { @@ -18927,32 +18941,49 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsCardinality.field", - "type": "string", + "id": "def-common.AggParamsBucketMin.customMetric", + "type": "Object", "tags": [], - "label": "field", + "label": "customMetric", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsCardinality.emptyAsNull", - "type": "CompoundType", + "id": "def-common.AggParamsBucketMin.customBucket", + "type": "Object", "tags": [], - "label": "emptyAsNull", + "label": "customBucket", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", "deprecated": false, "trackAdoption": false } @@ -18961,18 +18992,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsCount", + "id": "def-common.AggParamsBucketMinSerialized", "type": "Interface", "tags": [], - "label": "AggParamsCount", + "label": "AggParamsBucketMinSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsCount", - "text": "AggParamsCount" + "section": "def-common.AggParamsBucketMinSerialized", + "text": "AggParamsBucketMinSerialized" }, " extends ", { @@ -18983,21 +19014,39 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/count.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsCount.emptyAsNull", - "type": "CompoundType", + "id": "def-common.AggParamsBucketMinSerialized.customMetric", + "type": "Object", "tags": [], - "label": "emptyAsNull", + "label": "customMetric", "description": [], "signature": [ - "boolean | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/count.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsBucketMinSerialized.customBucket", + "type": "Object", + "tags": [], + "label": "customBucket", + "description": [], + "signature": [ + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/bucket_min.ts", "deprecated": false, "trackAdoption": false } @@ -19006,18 +19055,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsCumulativeSum", + "id": "def-common.AggParamsBucketSum", "type": "Interface", "tags": [], - "label": "AggParamsCumulativeSum", + "label": "AggParamsBucketSum", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsCumulativeSum", - "text": "AggParamsCumulativeSum" + "section": "def-common.AggParamsBucketSum", + "text": "AggParamsBucketSum" }, " extends ", { @@ -19028,51 +19077,49 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsCumulativeSum.buckets_path", - "type": "string", - "tags": [], - "label": "buckets_path", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsCumulativeSum.customMetric", + "id": "def-common.AggParamsBucketSum.customMetric", "type": "Object", "tags": [], "label": "customMetric", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsCumulativeSum.metricAgg", - "type": "string", + "id": "def-common.AggParamsBucketSum.customBucket", + "type": "Object", "tags": [], - "label": "metricAgg", + "label": "customBucket", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false } @@ -19081,18 +19128,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram", + "id": "def-common.AggParamsBucketSumSerialized", "type": "Interface", "tags": [], - "label": "AggParamsDateHistogram", + "label": "AggParamsBucketSumSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsDateHistogram", - "text": "AggParamsDateHistogram" + "section": "def-common.AggParamsBucketSumSerialized", + "text": "AggParamsBucketSumSerialized" }, " extends ", { @@ -19103,199 +19150,140 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.field", - "type": "CompoundType", + "id": "def-common.AggParamsBucketSumSerialized.customMetric", + "type": "Object", "tags": [], - "label": "field", + "label": "customMetric", "description": [], "signature": [ - "string | ", - "DataViewFieldBase", - " | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.timeRange", + "id": "def-common.AggParamsBucketSumSerialized.customBucket", "type": "Object", "tags": [], - "label": "timeRange", + "label": "customBucket", "description": [], "signature": [ - "TimeRange", - " | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/bucket_sum.ts", "deprecated": false, "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.useNormalizedEsInterval", - "type": "CompoundType", - "tags": [], - "label": "useNormalizedEsInterval", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.scaleMetricValues", - "type": "CompoundType", - "tags": [], - "label": "scaleMetricValues", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.interval", - "type": "string", - "tags": [], - "label": "interval", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsCardinality", + "type": "Interface", + "tags": [], + "label": "AggParamsCardinality", + "description": [], + "signature": [ { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.used_interval", - "type": "string", - "tags": [], - "label": "used_interval", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsCardinality", + "text": "AggParamsCardinality" }, + " extends ", { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.time_zone", - "type": "string", - "tags": [], - "label": "time_zone", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.used_time_zone", + "id": "def-common.AggParamsCardinality.field", "type": "string", "tags": [], - "label": "used_time_zone", + "label": "field", "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.drop_partials", + "id": "def-common.AggParamsCardinality.emptyAsNull", "type": "CompoundType", "tags": [], - "label": "drop_partials", + "label": "emptyAsNull", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.format", - "type": "string", - "tags": [], - "label": "format", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cardinality.ts", "deprecated": false, "trackAdoption": false - }, + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsCount", + "type": "Interface", + "tags": [], + "label": "AggParamsCount", + "description": [], + "signature": [ { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.min_doc_count", - "type": "number", - "tags": [], - "label": "min_doc_count", - "description": [], - "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsCount", + "text": "AggParamsCount" }, + " extends ", { - "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.extended_bounds", - "type": "Object", - "tags": [], - "label": "extended_bounds", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.ExtendedBounds", - "text": "ExtendedBounds" - }, - " | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - }, + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/count.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDateHistogram.extendToTimeRange", + "id": "def-common.AggParamsCount.emptyAsNull", "type": "CompoundType", "tags": [], - "label": "extendToTimeRange", + "label": "emptyAsNull", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/count.ts", "deprecated": false, "trackAdoption": false } @@ -19304,78 +19292,50 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsDateRange", + "id": "def-common.AggParamsCumulativeSum", "type": "Interface", "tags": [], - "label": "AggParamsDateRange", + "label": "AggParamsCumulativeSum", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsDateRange", - "text": "AggParamsDateRange" + "section": "def-common.AggParamsCumulativeSum", + "text": "AggParamsCumulativeSum" }, " extends ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" + "section": "def-common.CommonAggParamsCumulativeSum", + "text": "CommonAggParamsCumulativeSum" } ], - "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDateRange.field", - "type": "string", - "tags": [], - "label": "field", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateRange.ranges", - "type": "Array", + "id": "def-common.AggParamsCumulativeSum.customMetric", + "type": "Object", "tags": [], - "label": "ranges", + "label": "customMetric", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.DateRange", - "text": "DateRange" + "section": "def-common.AggConfig", + "text": "AggConfig" }, - "[] | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDateRange.time_zone", - "type": "string", - "tags": [], - "label": "time_zone", - "description": [], - "signature": [ - "string | undefined" + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, "trackAdoption": false } @@ -19384,73 +19344,45 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsDerivative", + "id": "def-common.AggParamsCumulativeSumSerialized", "type": "Interface", "tags": [], - "label": "AggParamsDerivative", + "label": "AggParamsCumulativeSumSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsDerivative", - "text": "AggParamsDerivative" + "section": "def-common.AggParamsCumulativeSumSerialized", + "text": "AggParamsCumulativeSumSerialized" }, " extends ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" + "section": "def-common.CommonAggParamsCumulativeSum", + "text": "CommonAggParamsCumulativeSum" } ], - "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDerivative.buckets_path", - "type": "string", + "id": "def-common.AggParamsCumulativeSumSerialized.customMetric", + "type": "Object", "tags": [], - "label": "buckets_path", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDerivative.customMetric", - "type": "Object", - "tags": [], - "label": "customMetric", + "label": "customMetric", "description": [], "signature": [ "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", "SerializableRecord", " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsDerivative.metricAgg", - "type": "string", - "tags": [], - "label": "metricAgg", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, "trackAdoption": false } @@ -19459,18 +19391,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsDiversifiedSampler", + "id": "def-common.AggParamsDateHistogram", "type": "Interface", "tags": [], - "label": "AggParamsDiversifiedSampler", + "label": "AggParamsDateHistogram", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsDiversifiedSampler", - "text": "AggParamsDiversifiedSampler" + "section": "def-common.AggParamsDateHistogram", + "text": "AggParamsDateHistogram" }, " extends ", { @@ -19481,139 +19413,199 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsDiversifiedSampler.field", - "type": "string", + "id": "def-common.AggParamsDateHistogram.field", + "type": "CompoundType", "tags": [], "label": "field", - "description": [ - "\nIs used to provide values used for de-duplication" + "description": [], + "signature": [ + "string | ", + "DataViewFieldBase", + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsDiversifiedSampler.shard_size", - "type": "number", + "id": "def-common.AggParamsDateHistogram.timeRange", + "type": "Object", "tags": [], - "label": "shard_size", - "description": [ - "\nLimits how many top-scoring documents are collected in the sample processed on each shard." + "label": "timeRange", + "description": [], + "signature": [ + "TimeRange", + " | undefined" ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.useNormalizedEsInterval", + "type": "CompoundType", + "tags": [], + "label": "useNormalizedEsInterval", + "description": [], "signature": [ - "number | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsDiversifiedSampler.max_docs_per_value", - "type": "number", + "id": "def-common.AggParamsDateHistogram.scaleMetricValues", + "type": "CompoundType", "tags": [], - "label": "max_docs_per_value", - "description": [ - "\nLimits how many documents are permitted per choice of de-duplicating value" + "label": "scaleMetricValues", + "description": [], + "signature": [ + "boolean | undefined" ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.interval", + "type": "string", + "tags": [], + "label": "interval", + "description": [], "signature": [ - "number | undefined" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsFilter", - "type": "Interface", - "tags": [], - "label": "AggParamsFilter", - "description": [], - "signature": [ + }, { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsFilter", - "text": "AggParamsFilter" + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.used_interval", + "type": "string", + "tags": [], + "label": "used_interval", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false }, - " extends ", { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.time_zone", + "type": "string", + "tags": [], + "label": "time_zone", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilter.geo_bounding_box", + "id": "def-common.AggParamsDateHistogram.used_time_zone", + "type": "string", + "tags": [], + "label": "used_time_zone", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.drop_partials", "type": "CompoundType", "tags": [], - "label": "geo_bounding_box", + "label": "drop_partials", "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.GeoBoundingBox", - "text": "GeoBoundingBox" - }, - " | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilter.filter", + "id": "def-common.AggParamsDateHistogram.format", + "type": "string", + "tags": [], + "label": "format", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.min_doc_count", + "type": "number", + "tags": [], + "label": "min_doc_count", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateHistogram.extended_bounds", "type": "Object", "tags": [], - "label": "filter", + "label": "extended_bounds", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.QueryFilter", - "text": "QueryFilter" + "section": "def-common.ExtendedBounds", + "text": "ExtendedBounds" }, " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilter.timeWindow", - "type": "string", + "id": "def-common.AggParamsDateHistogram.extendToTimeRange", + "type": "CompoundType", "tags": [], - "label": "timeWindow", + "label": "extendToTimeRange", "description": [], "signature": [ - "string | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, "trackAdoption": false } @@ -19622,18 +19614,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilteredMetric", + "id": "def-common.AggParamsDateRange", "type": "Interface", "tags": [], - "label": "AggParamsFilteredMetric", + "label": "AggParamsDateRange", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsFilteredMetric", - "text": "AggParamsFilteredMetric" + "section": "def-common.AggParamsDateRange", + "text": "AggParamsDateRange" }, " extends ", { @@ -19644,39 +19636,56 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsFilteredMetric.customMetric", - "type": "Object", + "id": "def-common.AggParamsDateRange.field", + "type": "string", "tags": [], - "label": "customMetric", + "label": "field", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilteredMetric.customBucket", - "type": "Object", + "id": "def-common.AggParamsDateRange.ranges", + "type": "Array", "tags": [], - "label": "customBucket", + "label": "ranges", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.DateRange", + "text": "DateRange" + }, + "[] | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDateRange.time_zone", + "type": "string", + "tags": [], + "label": "time_zone", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_range.ts", "deprecated": false, "trackAdoption": false } @@ -19685,51 +19694,50 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsFilters", + "id": "def-common.AggParamsDerivative", "type": "Interface", "tags": [], - "label": "AggParamsFilters", + "label": "AggParamsDerivative", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsFilters", - "text": "AggParamsFilters" + "section": "def-common.AggParamsDerivative", + "text": "AggParamsDerivative" }, - " extends Omit<", + " extends ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - }, - ", \"customLabel\">" + "section": "def-common.CommonAggParamsDerivative", + "text": "CommonAggParamsDerivative" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/filters.ts", + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsFilters.filters", - "type": "Array", + "id": "def-common.AggParamsDerivative.customMetric", + "type": "Object", "tags": [], - "label": "filters", + "label": "customMetric", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.QueryFilter", - "text": "QueryFilter" + "section": "def-common.AggConfig", + "text": "AggConfig" }, - "[] | undefined" + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/filters.ts", + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, "trackAdoption": false } @@ -19738,40 +19746,45 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoBounds", + "id": "def-common.AggParamsDerivativeSerialized", "type": "Interface", "tags": [], - "label": "AggParamsGeoBounds", + "label": "AggParamsDerivativeSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsGeoBounds", - "text": "AggParamsGeoBounds" + "section": "def-common.AggParamsDerivativeSerialized", + "text": "AggParamsDerivativeSerialized" }, " extends ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" + "section": "def-common.CommonAggParamsDerivative", + "text": "CommonAggParamsDerivative" } ], - "path": "src/plugins/data/common/search/aggs/metrics/geo_bounds.ts", + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsGeoBounds.field", - "type": "string", + "id": "def-common.AggParamsDerivativeSerialized.customMetric", + "type": "Object", "tags": [], - "label": "field", + "label": "customMetric", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/geo_bounds.ts", + "signature": [ + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, "trackAdoption": false } @@ -19780,18 +19793,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoCentroid", + "id": "def-common.AggParamsDiversifiedSampler", "type": "Interface", "tags": [], - "label": "AggParamsGeoCentroid", + "label": "AggParamsDiversifiedSampler", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsGeoCentroid", - "text": "AggParamsGeoCentroid" + "section": "def-common.AggParamsDiversifiedSampler", + "text": "AggParamsDiversifiedSampler" }, " extends ", { @@ -19802,18 +19815,52 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/geo_centroid.ts", + "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsGeoCentroid.field", + "id": "def-common.AggParamsDiversifiedSampler.field", "type": "string", "tags": [], "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/geo_centroid.ts", + "description": [ + "\nIs used to provide values used for de-duplication" + ], + "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDiversifiedSampler.shard_size", + "type": "number", + "tags": [], + "label": "shard_size", + "description": [ + "\nLimits how many top-scoring documents are collected in the sample processed on each shard." + ], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsDiversifiedSampler.max_docs_per_value", + "type": "number", + "tags": [], + "label": "max_docs_per_value", + "description": [ + "\nLimits how many documents are permitted per choice of de-duplicating value" + ], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/diversified_sampler.ts", "deprecated": false, "trackAdoption": false } @@ -19822,18 +19869,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash", + "id": "def-common.AggParamsFilter", "type": "Interface", "tags": [], - "label": "AggParamsGeoHash", + "label": "AggParamsFilter", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsGeoHash", - "text": "AggParamsGeoHash" + "section": "def-common.AggParamsFilter", + "text": "AggParamsFilter" }, " extends ", { @@ -19844,95 +19891,63 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.field", - "type": "string", - "tags": [], - "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.autoPrecision", - "type": "CompoundType", - "tags": [], - "label": "autoPrecision", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.precision", - "type": "number", - "tags": [], - "label": "precision", - "description": [], - "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.useGeocentroid", + "id": "def-common.AggParamsFilter.geo_bounding_box", "type": "CompoundType", "tags": [], - "label": "useGeocentroid", + "label": "geo_bounding_box", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.GeoBoundingBox", + "text": "GeoBoundingBox" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.isFilteredByCollar", - "type": "CompoundType", + "id": "def-common.AggParamsFilter.filter", + "type": "Object", "tags": [], - "label": "isFilteredByCollar", + "label": "filter", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.QueryFilter", + "text": "QueryFilter" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoHash.boundingBox", - "type": "CompoundType", + "id": "def-common.AggParamsFilter.timeWindow", + "type": "string", "tags": [], - "label": "boundingBox", + "label": "timeWindow", "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.GeoBoundingBox", - "text": "GeoBoundingBox" - }, - " | undefined" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filter.ts", "deprecated": false, "trackAdoption": false } @@ -19941,18 +19956,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoTile", + "id": "def-common.AggParamsFilteredMetric", "type": "Interface", "tags": [], - "label": "AggParamsGeoTile", + "label": "AggParamsFilteredMetric", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsGeoTile", - "text": "AggParamsGeoTile" + "section": "def-common.AggParamsFilteredMetric", + "text": "AggParamsFilteredMetric" }, " extends ", { @@ -19963,46 +19978,49 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsGeoTile.field", - "type": "string", + "id": "def-common.AggParamsFilteredMetric.customMetric", + "type": "Object", "tags": [], - "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsGeoTile.useGeocentroid", - "type": "CompoundType", - "tags": [], - "label": "useGeocentroid", + "label": "customMetric", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsGeoTile.precision", - "type": "number", + "id": "def-common.AggParamsFilteredMetric.customBucket", + "type": "Object", "tags": [], - "label": "precision", + "label": "customBucket", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false } @@ -20011,18 +20029,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsHistogram", + "id": "def-common.AggParamsFilteredMetricSerialized", "type": "Interface", "tags": [], - "label": "AggParamsHistogram", + "label": "AggParamsFilteredMetricSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsHistogram", - "text": "AggParamsHistogram" + "section": "def-common.AggParamsFilteredMetricSerialized", + "text": "AggParamsFilteredMetricSerialized" }, " extends ", { @@ -20033,137 +20051,39 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.field", - "type": "string", - "tags": [], - "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.interval", - "type": "CompoundType", - "tags": [], - "label": "interval", - "description": [], - "signature": [ - "string | number" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.used_interval", - "type": "CompoundType", - "tags": [], - "label": "used_interval", - "description": [], - "signature": [ - "string | number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.maxBars", - "type": "number", - "tags": [], - "label": "maxBars", - "description": [], - "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.intervalBase", - "type": "number", - "tags": [], - "label": "intervalBase", - "description": [], - "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.min_doc_count", - "type": "CompoundType", - "tags": [], - "label": "min_doc_count", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.has_extended_bounds", - "type": "CompoundType", - "tags": [], - "label": "has_extended_bounds", - "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.extended_bounds", + "id": "def-common.AggParamsFilteredMetricSerialized.customMetric", "type": "Object", "tags": [], - "label": "extended_bounds", + "label": "customMetric", "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.ExtendedBounds", - "text": "ExtendedBounds" - }, - " | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsHistogram.autoExtendBounds", - "type": "CompoundType", + "id": "def-common.AggParamsFilteredMetricSerialized.customBucket", + "type": "Object", "tags": [], - "label": "autoExtendBounds", + "label": "customBucket", "description": [], "signature": [ - "boolean | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "path": "src/plugins/data/common/search/aggs/metrics/filtered_metric.ts", "deprecated": false, "trackAdoption": false } @@ -20172,91 +20092,51 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsIpRange", + "id": "def-common.AggParamsFilters", "type": "Interface", "tags": [], - "label": "AggParamsIpRange", + "label": "AggParamsFilters", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsIpRange", - "text": "AggParamsIpRange" + "section": "def-common.AggParamsFilters", + "text": "AggParamsFilters" }, - " extends ", + " extends Omit<", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", "section": "def-common.BaseAggParams", "text": "BaseAggParams" - } + }, + ", \"customLabel\">" ], - "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filters.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsIpRange.field", - "type": "string", - "tags": [], - "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsIpRange.ipRangeType", - "type": "CompoundType", - "tags": [], - "label": "ipRangeType", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.IP_RANGE_TYPES", - "text": "IP_RANGE_TYPES" - }, - " | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsIpRange.ranges", - "type": "Object", + "id": "def-common.AggParamsFilters.filters", + "type": "Array", "tags": [], - "label": "ranges", + "label": "filters", "description": [], "signature": [ - "Partial<{ fromTo: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.RangeIpRangeAggKey", - "text": "RangeIpRangeAggKey" - }, - "[]; mask: ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.CidrMaskIpRangeAggKey", - "text": "CidrMaskIpRangeAggKey" + "section": "def-common.QueryFilter", + "text": "QueryFilter" }, - "[]; }> | undefined" + "[] | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", + "path": "src/plugins/data/common/search/aggs/buckets/filters.ts", "deprecated": false, "trackAdoption": false } @@ -20265,18 +20145,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsMax", + "id": "def-common.AggParamsGeoBounds", "type": "Interface", "tags": [], - "label": "AggParamsMax", + "label": "AggParamsGeoBounds", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsMax", - "text": "AggParamsMax" + "section": "def-common.AggParamsGeoBounds", + "text": "AggParamsGeoBounds" }, " extends ", { @@ -20287,18 +20167,18 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/max.ts", + "path": "src/plugins/data/common/search/aggs/metrics/geo_bounds.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMax.field", + "id": "def-common.AggParamsGeoBounds.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/max.ts", + "path": "src/plugins/data/common/search/aggs/metrics/geo_bounds.ts", "deprecated": false, "trackAdoption": false } @@ -20307,18 +20187,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsMedian", + "id": "def-common.AggParamsGeoCentroid", "type": "Interface", "tags": [], - "label": "AggParamsMedian", + "label": "AggParamsGeoCentroid", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsMedian", - "text": "AggParamsMedian" + "section": "def-common.AggParamsGeoCentroid", + "text": "AggParamsGeoCentroid" }, " extends ", { @@ -20329,18 +20209,18 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/median.ts", + "path": "src/plugins/data/common/search/aggs/metrics/geo_centroid.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMedian.field", + "id": "def-common.AggParamsGeoCentroid.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/median.ts", + "path": "src/plugins/data/common/search/aggs/metrics/geo_centroid.ts", "deprecated": false, "trackAdoption": false } @@ -20349,18 +20229,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsMin", + "id": "def-common.AggParamsGeoHash", "type": "Interface", "tags": [], - "label": "AggParamsMin", + "label": "AggParamsGeoHash", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsMin", - "text": "AggParamsMin" + "section": "def-common.AggParamsGeoHash", + "text": "AggParamsGeoHash" }, " extends ", { @@ -20371,121 +20251,95 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/min.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMin.field", + "id": "def-common.AggParamsGeoHash.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/min.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg", - "type": "Interface", - "tags": [], - "label": "AggParamsMovingAvg", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsMovingAvg", - "text": "AggParamsMovingAvg" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg.buckets_path", - "type": "string", + "id": "def-common.AggParamsGeoHash.autoPrecision", + "type": "CompoundType", "tags": [], - "label": "buckets_path", + "label": "autoPrecision", "description": [], "signature": [ - "string | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg.window", + "id": "def-common.AggParamsGeoHash.precision", "type": "number", "tags": [], - "label": "window", + "label": "precision", "description": [], "signature": [ "number | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg.script", - "type": "string", + "id": "def-common.AggParamsGeoHash.useGeocentroid", + "type": "CompoundType", "tags": [], - "label": "script", + "label": "useGeocentroid", "description": [], "signature": [ - "string | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg.customMetric", - "type": "Object", + "id": "def-common.AggParamsGeoHash.isFilteredByCollar", + "type": "CompoundType", "tags": [], - "label": "customMetric", + "label": "isFilteredByCollar", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMovingAvg.metricAgg", - "type": "string", + "id": "def-common.AggParamsGeoHash.boundingBox", + "type": "CompoundType", "tags": [], - "label": "metricAgg", + "label": "boundingBox", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.GeoBoundingBox", + "text": "GeoBoundingBox" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_hash.ts", "deprecated": false, "trackAdoption": false } @@ -20494,18 +20348,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms", + "id": "def-common.AggParamsGeoTile", "type": "Interface", "tags": [], - "label": "AggParamsMultiTerms", + "label": "AggParamsGeoTile", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsMultiTerms", - "text": "AggParamsMultiTerms" + "section": "def-common.AggParamsGeoTile", + "text": "AggParamsGeoTile" }, " extends ", { @@ -20516,132 +20370,207 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.fields", - "type": "Array", + "id": "def-common.AggParamsGeoTile.field", + "type": "string", "tags": [], - "label": "fields", + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsGeoTile.useGeocentroid", + "type": "CompoundType", + "tags": [], + "label": "useGeocentroid", "description": [], "signature": [ - "string[]" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsGeoTile.precision", + "type": "number", + "tags": [], + "label": "precision", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/geo_tile.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsHistogram", + "type": "Interface", + "tags": [], + "label": "AggParamsHistogram", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsHistogram", + "text": "AggParamsHistogram" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.orderBy", + "id": "def-common.AggParamsHistogram.field", "type": "string", "tags": [], - "label": "orderBy", + "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.orderAgg", - "type": "Object", + "id": "def-common.AggParamsHistogram.interval", + "type": "CompoundType", "tags": [], - "label": "orderAgg", + "label": "interval", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + "string | number" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.order", + "id": "def-common.AggParamsHistogram.used_interval", "type": "CompoundType", "tags": [], - "label": "order", + "label": "used_interval", "description": [], "signature": [ - "\"asc\" | \"desc\" | undefined" + "string | number | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.size", + "id": "def-common.AggParamsHistogram.maxBars", "type": "number", "tags": [], - "label": "size", + "label": "maxBars", "description": [], "signature": [ "number | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.shardSize", + "id": "def-common.AggParamsHistogram.intervalBase", "type": "number", "tags": [], - "label": "shardSize", + "label": "intervalBase", "description": [], "signature": [ "number | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.otherBucket", + "id": "def-common.AggParamsHistogram.min_doc_count", "type": "CompoundType", "tags": [], - "label": "otherBucket", + "label": "min_doc_count", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.otherBucketLabel", - "type": "string", + "id": "def-common.AggParamsHistogram.has_extended_bounds", + "type": "CompoundType", "tags": [], - "label": "otherBucketLabel", + "label": "has_extended_bounds", "description": [], "signature": [ - "string | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsMultiTerms.separatorLabel", - "type": "string", + "id": "def-common.AggParamsHistogram.extended_bounds", + "type": "Object", + "tags": [], + "label": "extended_bounds", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.ExtendedBounds", + "text": "ExtendedBounds" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsHistogram.autoExtendBounds", + "type": "CompoundType", "tags": [], - "label": "separatorLabel", + "label": "autoExtendBounds", "description": [], "signature": [ - "string | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", "deprecated": false, "trackAdoption": false } @@ -20650,19 +20579,19 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsPercentileRanks", + "id": "def-common.AggParamsIpRange", "type": "Interface", "tags": [], - "label": "AggParamsPercentileRanks", + "label": "AggParamsIpRange", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsPercentileRanks", - "text": "AggParamsPercentileRanks" - }, + "section": "def-common.AggParamsIpRange", + "text": "AggParamsIpRange" + }, " extends ", { "pluginId": "data", @@ -20672,32 +20601,69 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsPercentileRanks.field", + "id": "def-common.AggParamsIpRange.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsPercentileRanks.values", - "type": "Array", + "id": "def-common.AggParamsIpRange.ipRangeType", + "type": "CompoundType", "tags": [], - "label": "values", + "label": "ipRangeType", "description": [], "signature": [ - "number[] | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.IP_RANGE_TYPES", + "text": "IP_RANGE_TYPES" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsIpRange.ranges", + "type": "Object", + "tags": [], + "label": "ranges", + "description": [], + "signature": [ + "Partial<{ fromTo: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.RangeIpRangeAggKey", + "text": "RangeIpRangeAggKey" + }, + "[]; mask: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CidrMaskIpRangeAggKey", + "text": "CidrMaskIpRangeAggKey" + }, + "[]; }> | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/ip_range.ts", "deprecated": false, "trackAdoption": false } @@ -20706,932 +20672,852 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsPercentiles", + "id": "def-common.AggParamsMapping", "type": "Interface", "tags": [], - "label": "AggParamsPercentiles", + "label": "AggParamsMapping", "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsPercentiles", - "text": "AggParamsPercentiles" - }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsPercentiles.field", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.RANGE", + "type": "Object", "tags": [], - "label": "field", + "label": "[BUCKET_TYPES.RANGE]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsRange", + "text": "AggParamsRange" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsPercentiles.percents", - "type": "Array", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.IP_RANGE", + "type": "Object", "tags": [], - "label": "percents", + "label": "[BUCKET_TYPES.IP_RANGE]", "description": [], "signature": [ - "number[] | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsIpRange", + "text": "AggParamsIpRange" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsRange", - "type": "Interface", - "tags": [], - "label": "AggParamsRange", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsRange", - "text": "AggParamsRange" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/range.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsRange.field", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.DATE_RANGE", + "type": "Object", "tags": [], - "label": "field", + "label": "[BUCKET_TYPES.DATE_RANGE]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/range.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsDateRange", + "text": "AggParamsDateRange" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsRange.ranges", - "type": "Array", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.FILTER", + "type": "Object", "tags": [], - "label": "ranges", + "label": "[BUCKET_TYPES.FILTER]", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.NumericalRange", - "text": "NumericalRange" - }, - "[] | undefined" + "section": "def-common.AggParamsFilter", + "text": "AggParamsFilter" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/range.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsRareTerms", - "type": "Interface", - "tags": [], - "label": "AggParamsRareTerms", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsRareTerms", - "text": "AggParamsRareTerms" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsRareTerms.field", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.FILTERS", + "type": "Object", "tags": [], - "label": "field", + "label": "[BUCKET_TYPES.FILTERS]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsFilters", + "text": "AggParamsFilters" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsRareTerms.max_doc_count", - "type": "number", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.SIGNIFICANT_TERMS", + "type": "Object", "tags": [], - "label": "max_doc_count", + "label": "[BUCKET_TYPES.SIGNIFICANT_TERMS]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSignificantTerms", + "text": "AggParamsSignificantTerms" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSampler", - "type": "Interface", - "tags": [], - "label": "AggParamsSampler", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSampler", - "text": "AggParamsSampler" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/sampler.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSampler.shard_size", - "type": "number", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.SIGNIFICANT_TEXT", + "type": "Object", "tags": [], - "label": "shard_size", - "description": [ - "\nLimits how many top-scoring documents are collected in the sample processed on each shard." - ], + "label": "[BUCKET_TYPES.SIGNIFICANT_TEXT]", + "description": [], "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/buckets/sampler.ts", - "deprecated": false, + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSignificantText", + "text": "AggParamsSignificantText" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSerialDiff", - "type": "Interface", - "tags": [], - "label": "AggParamsSerialDiff", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSerialDiff", - "text": "AggParamsSerialDiff" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSerialDiff.buckets_path", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.GEOTILE_GRID", + "type": "Object", "tags": [], - "label": "buckets_path", + "label": "[BUCKET_TYPES.GEOTILE_GRID]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsGeoTile", + "text": "AggParamsGeoTile" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSerialDiff.customMetric", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.GEOHASH_GRID", "type": "Object", "tags": [], - "label": "customMetric", + "label": "[BUCKET_TYPES.GEOHASH_GRID]", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsGeoHash", + "text": "AggParamsGeoHash" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSerialDiff.metricAgg", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.HISTOGRAM", + "type": "Object", "tags": [], - "label": "metricAgg", + "label": "[BUCKET_TYPES.HISTOGRAM]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsHistogram", + "text": "AggParamsHistogram" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSignificantTerms", - "type": "Interface", - "tags": [], - "label": "AggParamsSignificantTerms", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSignificantTerms", - "text": "AggParamsSignificantTerms" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantTerms.field", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.DATE_HISTOGRAM", + "type": "Object", "tags": [], - "label": "field", + "label": "[BUCKET_TYPES.DATE_HISTOGRAM]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsDateHistogram", + "text": "AggParamsDateHistogram" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantTerms.size", - "type": "number", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.TERMS", + "type": "Object", "tags": [], - "label": "size", + "label": "[BUCKET_TYPES.TERMS]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTerms", + "text": "AggParamsTerms" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantTerms.exclude", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.MULTI_TERMS", + "type": "Object", "tags": [], - "label": "exclude", + "label": "[BUCKET_TYPES.MULTI_TERMS]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMultiTerms", + "text": "AggParamsMultiTerms" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantTerms.include", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.RARE_TERMS", + "type": "Object", "tags": [], - "label": "include", + "label": "[BUCKET_TYPES.RARE_TERMS]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsRareTerms", + "text": "AggParamsRareTerms" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText", - "type": "Interface", - "tags": [], - "label": "AggParamsSignificantText", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSignificantText", - "text": "AggParamsSignificantText" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.field", - "type": "string", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.SAMPLER", + "type": "Object", "tags": [], - "label": "field", + "label": "[BUCKET_TYPES.SAMPLER]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSampler", + "text": "AggParamsSampler" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.size", - "type": "number", + "id": "def-common.AggParamsMapping.BUCKET_TYPES.DIVERSIFIED_SAMPLER", + "type": "Object", "tags": [], - "label": "size", + "label": "[BUCKET_TYPES.DIVERSIFIED_SAMPLER]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsDiversifiedSampler", + "text": "AggParamsDiversifiedSampler" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.min_doc_count", - "type": "number", + "id": "def-common.AggParamsMapping.METRIC_TYPES.AVG", + "type": "Object", "tags": [], - "label": "min_doc_count", + "label": "[METRIC_TYPES.AVG]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsAvg", + "text": "AggParamsAvg" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.filter_duplicate_text", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.CARDINALITY", + "type": "Object", "tags": [], - "label": "filter_duplicate_text", + "label": "[METRIC_TYPES.CARDINALITY]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsCardinality", + "text": "AggParamsCardinality" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.exclude", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.COUNT", + "type": "Object", "tags": [], - "label": "exclude", + "label": "[METRIC_TYPES.COUNT]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsCount", + "text": "AggParamsCount" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSignificantText.include", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.VALUE_COUNT", + "type": "Object", "tags": [], - "label": "include", + "label": "[METRIC_TYPES.VALUE_COUNT]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsValueCount", + "text": "AggParamsValueCount" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentile", - "type": "Interface", - "tags": [], - "label": "AggParamsSinglePercentile", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSinglePercentile", - "text": "AggParamsSinglePercentile" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentile.field", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.GEO_BOUNDS", + "type": "Object", "tags": [], - "label": "field", + "label": "[METRIC_TYPES.GEO_BOUNDS]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsGeoBounds", + "text": "AggParamsGeoBounds" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentile.percentile", - "type": "number", + "id": "def-common.AggParamsMapping.METRIC_TYPES.GEO_CENTROID", + "type": "Object", "tags": [], - "label": "percentile", + "label": "[METRIC_TYPES.GEO_CENTROID]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsGeoCentroid", + "text": "AggParamsGeoCentroid" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentileRank", - "type": "Interface", - "tags": [], - "label": "AggParamsSinglePercentileRank", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSinglePercentileRank", - "text": "AggParamsSinglePercentileRank" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentileRank.field", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MAX", + "type": "Object", "tags": [], - "label": "field", + "label": "[METRIC_TYPES.MAX]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMax", + "text": "AggParamsMax" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSinglePercentileRank.value", - "type": "number", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MEDIAN", + "type": "Object", "tags": [], - "label": "value", + "label": "[METRIC_TYPES.MEDIAN]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMedian", + "text": "AggParamsMedian" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsStdDeviation", - "type": "Interface", - "tags": [], - "label": "AggParamsStdDeviation", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsStdDeviation", - "text": "AggParamsStdDeviation" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsStdDeviation.field", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.SINGLE_PERCENTILE", + "type": "Object", "tags": [], - "label": "field", + "label": "[METRIC_TYPES.SINGLE_PERCENTILE]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSinglePercentile", + "text": "AggParamsSinglePercentile" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsStdDeviation.showBounds", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.SINGLE_PERCENTILE_RANK", + "type": "Object", "tags": [], - "label": "showBounds", + "label": "[METRIC_TYPES.SINGLE_PERCENTILE_RANK]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSinglePercentileRank", + "text": "AggParamsSinglePercentileRank" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsSum", - "type": "Interface", - "tags": [], - "label": "AggParamsSum", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsSum", - "text": "AggParamsSum" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsSum.field", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MIN", + "type": "Object", "tags": [], - "label": "field", + "label": "[METRIC_TYPES.MIN]", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMin", + "text": "AggParamsMin" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsSum.emptyAsNull", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.STD_DEV", + "type": "Object", "tags": [], - "label": "emptyAsNull", + "label": "[METRIC_TYPES.STD_DEV]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsStdDeviation", + "text": "AggParamsStdDeviation" + } ], - "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsTerms", - "type": "Interface", - "tags": [], - "label": "AggParamsTerms", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsTerms", - "text": "AggParamsTerms" }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" - } - ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.field", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.SUM", + "type": "Object", "tags": [], - "label": "field", + "label": "[METRIC_TYPES.SUM]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSum", + "text": "AggParamsSum" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.orderBy", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.AVG_BUCKET", + "type": "Object", "tags": [], - "label": "orderBy", + "label": "[METRIC_TYPES.AVG_BUCKET]", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsBucketAvg", + "text": "AggParamsBucketAvg" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.orderAgg", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MAX_BUCKET", "type": "Object", "tags": [], - "label": "orderAgg", + "label": "[METRIC_TYPES.MAX_BUCKET]", "description": [], "signature": [ - "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", - "SerializableRecord", - " | undefined; schema?: string | undefined; } | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsBucketMax", + "text": "AggParamsBucketMax" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.order", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MIN_BUCKET", + "type": "Object", "tags": [], - "label": "order", + "label": "[METRIC_TYPES.MIN_BUCKET]", "description": [], "signature": [ - "\"asc\" | \"desc\" | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsBucketMin", + "text": "AggParamsBucketMin" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.size", - "type": "number", + "id": "def-common.AggParamsMapping.METRIC_TYPES.SUM_BUCKET", + "type": "Object", "tags": [], - "label": "size", + "label": "[METRIC_TYPES.SUM_BUCKET]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsBucketSum", + "text": "AggParamsBucketSum" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.shardSize", - "type": "number", + "id": "def-common.AggParamsMapping.METRIC_TYPES.FILTERED_METRIC", + "type": "Object", "tags": [], - "label": "shardSize", + "label": "[METRIC_TYPES.FILTERED_METRIC]", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsFilteredMetric", + "text": "AggParamsFilteredMetric" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.missingBucket", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.CUMULATIVE_SUM", + "type": "Object", "tags": [], - "label": "missingBucket", + "label": "[METRIC_TYPES.CUMULATIVE_SUM]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsCumulativeSum", + "text": "AggParamsCumulativeSum" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.missingBucketLabel", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.DERIVATIVE", + "type": "Object", "tags": [], - "label": "missingBucketLabel", + "label": "[METRIC_TYPES.DERIVATIVE]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsDerivative", + "text": "AggParamsDerivative" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.otherBucket", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.MOVING_FN", + "type": "Object", "tags": [], - "label": "otherBucket", + "label": "[METRIC_TYPES.MOVING_FN]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMovingAvg", + "text": "AggParamsMovingAvg" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.otherBucketLabel", - "type": "string", + "id": "def-common.AggParamsMapping.METRIC_TYPES.PERCENTILE_RANKS", + "type": "Object", "tags": [], - "label": "otherBucketLabel", + "label": "[METRIC_TYPES.PERCENTILE_RANKS]", "description": [], "signature": [ - "string | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsPercentileRanks", + "text": "AggParamsPercentileRanks" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.exclude", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.PERCENTILES", + "type": "Object", "tags": [], - "label": "exclude", + "label": "[METRIC_TYPES.PERCENTILES]", "description": [], "signature": [ - "string[] | number[] | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsPercentiles", + "text": "AggParamsPercentiles" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.include", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.SERIAL_DIFF", + "type": "Object", "tags": [], - "label": "include", + "label": "[METRIC_TYPES.SERIAL_DIFF]", "description": [], "signature": [ - "string[] | number[] | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSerialDiff", + "text": "AggParamsSerialDiff" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.includeIsRegex", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.TOP_HITS", + "type": "Object", "tags": [], - "label": "includeIsRegex", + "label": "[METRIC_TYPES.TOP_HITS]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopHit", + "text": "AggParamsTopHit" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggParamsTerms.excludeIsRegex", - "type": "CompoundType", + "id": "def-common.AggParamsMapping.METRIC_TYPES.TOP_METRICS", + "type": "Object", "tags": [], - "label": "excludeIsRegex", + "label": "[METRIC_TYPES.TOP_METRICS]", "description": [], "signature": [ - "boolean | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopMetrics", + "text": "AggParamsTopMetrics" + } ], - "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false } @@ -21640,18 +21526,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsTopHit", + "id": "def-common.AggParamsMax", "type": "Interface", "tags": [], - "label": "AggParamsTopHit", + "label": "AggParamsMax", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsTopHit", - "text": "AggParamsTopHit" + "section": "def-common.AggParamsMax", + "text": "AggParamsMax" }, " extends ", { @@ -21662,74 +21548,18 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "path": "src/plugins/data/common/search/aggs/metrics/max.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsTopHit.field", + "id": "def-common.AggParamsMax.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsTopHit.aggregate", - "type": "CompoundType", - "tags": [], - "label": "aggregate", - "description": [], - "signature": [ - "\"min\" | \"max\" | \"sum\" | \"average\" | \"concat\"" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsTopHit.sortField", - "type": "string", - "tags": [], - "label": "sortField", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsTopHit.size", - "type": "number", - "tags": [], - "label": "size", - "description": [], - "signature": [ - "number | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsTopHit.sortOrder", - "type": "CompoundType", - "tags": [], - "label": "sortOrder", - "description": [], - "signature": [ - "\"asc\" | \"desc\" | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "path": "src/plugins/data/common/search/aggs/metrics/max.ts", "deprecated": false, "trackAdoption": false } @@ -21738,18 +21568,18 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsTopMetrics", + "id": "def-common.AggParamsMedian", "type": "Interface", "tags": [], - "label": "AggParamsTopMetrics", + "label": "AggParamsMedian", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsTopMetrics", - "text": "AggParamsTopMetrics" + "section": "def-common.AggParamsMedian", + "text": "AggParamsMedian" }, " extends ", { @@ -21760,60 +21590,112 @@ "text": "BaseAggParams" } ], - "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "path": "src/plugins/data/common/search/aggs/metrics/median.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsTopMetrics.field", + "id": "def-common.AggParamsMedian.field", "type": "string", "tags": [], "label": "field", "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "path": "src/plugins/data/common/search/aggs/metrics/median.ts", "deprecated": false, "trackAdoption": false - }, + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsMin", + "type": "Interface", + "tags": [], + "label": "AggParamsMin", + "description": [], + "signature": [ { - "parentPluginId": "data", - "id": "def-common.AggParamsTopMetrics.sortField", - "type": "string", - "tags": [], - "label": "sortField", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", - "deprecated": false, - "trackAdoption": false + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMin", + "text": "AggParamsMin" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/min.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsTopMetrics.sortOrder", - "type": "CompoundType", + "id": "def-common.AggParamsMin.field", + "type": "string", "tags": [], - "label": "sortOrder", + "label": "field", "description": [], - "signature": [ - "\"asc\" | \"desc\" | undefined" - ], - "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "path": "src/plugins/data/common/search/aggs/metrics/min.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsMovingAvg", + "type": "Interface", + "tags": [], + "label": "AggParamsMovingAvg", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMovingAvg", + "text": "AggParamsMovingAvg" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsMovingAvg", + "text": "CommonAggParamsMovingAvg" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsTopMetrics.size", - "type": "number", + "id": "def-common.AggParamsMovingAvg.customMetric", + "type": "Object", "tags": [], - "label": "size", + "label": "customMetric", "description": [], "signature": [ - "number | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false } @@ -21822,54 +21704,45 @@ }, { "parentPluginId": "data", - "id": "def-common.AggParamsValueCount", + "id": "def-common.AggParamsMovingAvgSerialized", "type": "Interface", "tags": [], - "label": "AggParamsValueCount", + "label": "AggParamsMovingAvgSerialized", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamsValueCount", - "text": "AggParamsValueCount" + "section": "def-common.AggParamsMovingAvgSerialized", + "text": "AggParamsMovingAvgSerialized" }, " extends ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseAggParams", - "text": "BaseAggParams" + "section": "def-common.CommonAggParamsMovingAvg", + "text": "CommonAggParamsMovingAvg" } ], - "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggParamsValueCount.field", - "type": "string", - "tags": [], - "label": "field", - "description": [], - "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggParamsValueCount.emptyAsNull", - "type": "CompoundType", + "id": "def-common.AggParamsMovingAvgSerialized.customMetric", + "type": "Object", "tags": [], - "label": "emptyAsNull", + "label": "customMetric", "description": [], "signature": [ - "boolean | undefined" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false } @@ -21878,58 +21751,43 @@ }, { "parentPluginId": "data", - "id": "def-common.AggsCommonSetup", + "id": "def-common.AggParamsMultiTerms", "type": "Interface", "tags": [], - "label": "AggsCommonSetup", + "label": "AggParamsMultiTerms", "description": [], - "path": "src/plugins/data/common/search/aggs/types.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMultiTerms", + "text": "AggParamsMultiTerms" + }, + " extends CommonAggParamsMultiTerms" + ], + "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggsCommonSetup.types", + "id": "def-common.AggParamsMultiTerms.orderAgg", "type": "Object", "tags": [], - "label": "types", + "label": "orderAgg", "description": [], "signature": [ - "{ registerBucket: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BucketAggType", - "text": "BucketAggType" - }, - ">(name: N, type: T) => void; registerMetric: ", { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.MetricAggType", - "text": "MetricAggType" + "section": "def-common.AggConfig", + "text": "AggConfig" }, - ">(name: N, type: T) => void; }" + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/types.ts", + "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", "deprecated": false, "trackAdoption": false } @@ -21938,337 +21796,2275 @@ }, { "parentPluginId": "data", - "id": "def-common.AggsCommonSetupDependencies", + "id": "def-common.AggParamsMultiTermsSerialized", "type": "Interface", "tags": [], - "label": "AggsCommonSetupDependencies", + "label": "AggParamsMultiTermsSerialized", "description": [], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMultiTermsSerialized", + "text": "AggParamsMultiTermsSerialized" + }, + " extends CommonAggParamsMultiTerms" + ], + "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggsCommonSetupDependencies.registerFunction", - "type": "Function", + "id": "def-common.AggParamsMultiTermsSerialized.orderAgg", + "type": "Object", "tags": [], - "label": "registerFunction", + "label": "orderAgg", "description": [], "signature": [ - "(functionDefinition: ", - { - "pluginId": "expressions", - "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.AnyExpressionFunctionDefinition", - "text": "AnyExpressionFunctionDefinition" - }, - " | (() => ", - { - "pluginId": "expressions", - "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.AnyExpressionFunctionDefinition", - "text": "AnyExpressionFunctionDefinition" - }, - ")) => void" + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "path": "src/plugins/data/common/search/aggs/buckets/multi_terms.ts", "deprecated": false, - "trackAdoption": false, - "returnComment": [], - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggsCommonSetupDependencies.registerFunction.$1", - "type": "CompoundType", - "tags": [], - "label": "functionDefinition", - "description": [], - "signature": [ - { - "pluginId": "expressions", - "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.AnyExpressionFunctionDefinition", - "text": "AnyExpressionFunctionDefinition" - }, - " | (() => ", - { - "pluginId": "expressions", - "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.AnyExpressionFunctionDefinition", - "text": "AnyExpressionFunctionDefinition" - }, - ")" - ], - "path": "src/plugins/expressions/common/service/expressions_services.ts", - "deprecated": false, - "trackAdoption": false - } - ] + "trackAdoption": false } ], "initialIsOpen": false }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStart", + "id": "def-common.AggParamsPercentileRanks", "type": "Interface", "tags": [], - "label": "AggsCommonStart", + "label": "AggParamsPercentileRanks", "description": [], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ + "signature": [ { - "parentPluginId": "data", - "id": "def-common.AggsCommonStart.calculateAutoTimeExpression", - "type": "Function", - "tags": [], - "label": "calculateAutoTimeExpression", - "description": [], - "signature": [ - "(range: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsPercentileRanks", + "text": "AggParamsPercentileRanks" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsPercentileRanks.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsPercentileRanks.values", + "type": "Array", + "tags": [], + "label": "values", + "description": [], + "signature": [ + "number[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/percentile_ranks.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsPercentiles", + "type": "Interface", + "tags": [], + "label": "AggParamsPercentiles", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsPercentiles", + "text": "AggParamsPercentiles" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsPercentiles.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsPercentiles.percents", + "type": "Array", + "tags": [], + "label": "percents", + "description": [], + "signature": [ + "number[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/percentiles.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsRange", + "type": "Interface", + "tags": [], + "label": "AggParamsRange", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsRange", + "text": "AggParamsRange" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/range.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsRange.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/range.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsRange.ranges", + "type": "Array", + "tags": [], + "label": "ranges", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.NumericalRange", + "text": "NumericalRange" + }, + "[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/range.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsRareTerms", + "type": "Interface", + "tags": [], + "label": "AggParamsRareTerms", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsRareTerms", + "text": "AggParamsRareTerms" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsRareTerms.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsRareTerms.max_doc_count", + "type": "number", + "tags": [], + "label": "max_doc_count", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/rare_terms.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSampler", + "type": "Interface", + "tags": [], + "label": "AggParamsSampler", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSampler", + "text": "AggParamsSampler" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/sampler.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSampler.shard_size", + "type": "number", + "tags": [], + "label": "shard_size", + "description": [ + "\nLimits how many top-scoring documents are collected in the sample processed on each shard." + ], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/sampler.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSerialDiff", + "type": "Interface", + "tags": [], + "label": "AggParamsSerialDiff", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSerialDiff", + "text": "AggParamsSerialDiff" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsSerialDiff", + "text": "CommonAggParamsSerialDiff" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSerialDiff.customMetric", + "type": "Object", + "tags": [], + "label": "customMetric", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSerialDiffSerialized", + "type": "Interface", + "tags": [], + "label": "AggParamsSerialDiffSerialized", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSerialDiffSerialized", + "text": "AggParamsSerialDiffSerialized" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsSerialDiff", + "text": "CommonAggParamsSerialDiff" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSerialDiffSerialized.customMetric", + "type": "Object", + "tags": [], + "label": "customMetric", + "description": [], + "signature": [ + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantTerms", + "type": "Interface", + "tags": [], + "label": "AggParamsSignificantTerms", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSignificantTerms", + "text": "AggParamsSignificantTerms" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantTerms.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantTerms.size", + "type": "number", + "tags": [], + "label": "size", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantTerms.exclude", + "type": "string", + "tags": [], + "label": "exclude", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantTerms.include", + "type": "string", + "tags": [], + "label": "include", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_terms.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText", + "type": "Interface", + "tags": [], + "label": "AggParamsSignificantText", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSignificantText", + "text": "AggParamsSignificantText" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.size", + "type": "number", + "tags": [], + "label": "size", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.min_doc_count", + "type": "number", + "tags": [], + "label": "min_doc_count", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.filter_duplicate_text", + "type": "CompoundType", + "tags": [], + "label": "filter_duplicate_text", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.exclude", + "type": "string", + "tags": [], + "label": "exclude", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSignificantText.include", + "type": "string", + "tags": [], + "label": "include", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/significant_text.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentile", + "type": "Interface", + "tags": [], + "label": "AggParamsSinglePercentile", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSinglePercentile", + "text": "AggParamsSinglePercentile" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentile.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentile.percentile", + "type": "number", + "tags": [], + "label": "percentile", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentileRank", + "type": "Interface", + "tags": [], + "label": "AggParamsSinglePercentileRank", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSinglePercentileRank", + "text": "AggParamsSinglePercentileRank" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentileRank.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSinglePercentileRank.value", + "type": "number", + "tags": [], + "label": "value", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/single_percentile_rank.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsStdDeviation", + "type": "Interface", + "tags": [], + "label": "AggParamsStdDeviation", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsStdDeviation", + "text": "AggParamsStdDeviation" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsStdDeviation.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsStdDeviation.showBounds", + "type": "CompoundType", + "tags": [], + "label": "showBounds", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/std_deviation.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSum", + "type": "Interface", + "tags": [], + "label": "AggParamsSum", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsSum", + "text": "AggParamsSum" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsSum.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsSum.emptyAsNull", + "type": "CompoundType", + "tags": [], + "label": "emptyAsNull", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/sum.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTerms", + "type": "Interface", + "tags": [], + "label": "AggParamsTerms", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTerms", + "text": "AggParamsTerms" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsTerms", + "text": "CommonAggParamsTerms" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTerms.orderAgg", + "type": "Object", + "tags": [], + "label": "orderAgg", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTerms.order", + "type": "Object", + "tags": [], + "label": "order", + "description": [], + "signature": [ + "{ value: \"asc\" | \"desc\"; text: string; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTermsSerialized", + "type": "Interface", + "tags": [], + "label": "AggParamsTermsSerialized", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTermsSerialized", + "text": "AggParamsTermsSerialized" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsTerms", + "text": "CommonAggParamsTerms" + } + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTermsSerialized.orderAgg", + "type": "Object", + "tags": [], + "label": "orderAgg", + "description": [], + "signature": [ + "{ type: string; enabled?: boolean | undefined; id?: string | undefined; params?: {} | ", + "SerializableRecord", + " | undefined; schema?: string | undefined; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTermsSerialized.order", + "type": "CompoundType", + "tags": [], + "label": "order", + "description": [], + "signature": [ + "\"asc\" | \"desc\" | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHit", + "type": "Interface", + "tags": [], + "label": "AggParamsTopHit", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopHit", + "text": "AggParamsTopHit" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopHit", + "text": "BaseAggParamsTopHit" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHit.sortOrder", + "type": "Object", + "tags": [], + "label": "sortOrder", + "description": [], + "signature": [ + "{ value: \"asc\" | \"desc\"; text: string; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHit.sortField", + "type": "Object", + "tags": [], + "label": "sortField", + "description": [], + "signature": [ + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataViewField", + "text": "DataViewField" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHitSerialized", + "type": "Interface", + "tags": [], + "label": "AggParamsTopHitSerialized", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopHitSerialized", + "text": "AggParamsTopHitSerialized" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopHit", + "text": "BaseAggParamsTopHit" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHitSerialized.sortOrder", + "type": "CompoundType", + "tags": [], + "label": "sortOrder", + "description": [], + "signature": [ + "\"asc\" | \"desc\" | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopHitSerialized.sortField", + "type": "string", + "tags": [], + "label": "sortField", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetrics", + "type": "Interface", + "tags": [], + "label": "AggParamsTopMetrics", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopMetrics", + "text": "AggParamsTopMetrics" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopMetrics", + "text": "BaseAggParamsTopMetrics" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetrics.sortOrder", + "type": "Object", + "tags": [], + "label": "sortOrder", + "description": [], + "signature": [ + "{ value: \"asc\" | \"desc\"; text: string; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetrics.sortField", + "type": "Object", + "tags": [], + "label": "sortField", + "description": [], + "signature": [ + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataViewField", + "text": "DataViewField" + }, + " | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetricsSerialized", + "type": "Interface", + "tags": [], + "label": "AggParamsTopMetricsSerialized", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsTopMetricsSerialized", + "text": "AggParamsTopMetricsSerialized" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopMetrics", + "text": "BaseAggParamsTopMetrics" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetricsSerialized.sortOrder", + "type": "CompoundType", + "tags": [], + "label": "sortOrder", + "description": [], + "signature": [ + "\"asc\" | \"desc\" | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsTopMetricsSerialized.sortField", + "type": "string", + "tags": [], + "label": "sortField", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsValueCount", + "type": "Interface", + "tags": [], + "label": "AggParamsValueCount", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsValueCount", + "text": "AggParamsValueCount" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggParamsValueCount.field", + "type": "string", + "tags": [], + "label": "field", + "description": [], + "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggParamsValueCount.emptyAsNull", + "type": "CompoundType", + "tags": [], + "label": "emptyAsNull", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/value_count.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonSetup", + "type": "Interface", + "tags": [], + "label": "AggsCommonSetup", + "description": [], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonSetup.types", + "type": "Object", + "tags": [], + "label": "types", + "description": [], + "signature": [ + "{ registerBucket: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BucketAggType", + "text": "BucketAggType" + }, + ">(name: N, type: T) => void; registerMetric: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.MetricAggType", + "text": "MetricAggType" + }, + ">(name: N, type: T) => void; }" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonSetupDependencies", + "type": "Interface", + "tags": [], + "label": "AggsCommonSetupDependencies", + "description": [], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonSetupDependencies.registerFunction", + "type": "Function", + "tags": [], + "label": "registerFunction", + "description": [], + "signature": [ + "(functionDefinition: ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.AnyExpressionFunctionDefinition", + "text": "AnyExpressionFunctionDefinition" + }, + " | (() => ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.AnyExpressionFunctionDefinition", + "text": "AnyExpressionFunctionDefinition" + }, + ")) => void" + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonSetupDependencies.registerFunction.$1", + "type": "CompoundType", + "tags": [], + "label": "functionDefinition", + "description": [], + "signature": [ + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.AnyExpressionFunctionDefinition", + "text": "AnyExpressionFunctionDefinition" + }, + " | (() => ", + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.AnyExpressionFunctionDefinition", + "text": "AnyExpressionFunctionDefinition" + }, + ")" + ], + "path": "src/plugins/expressions/common/service/expressions_services.ts", + "deprecated": false, + "trackAdoption": false + } + ] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart", + "type": "Interface", + "tags": [], + "label": "AggsCommonStart", + "description": [], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.calculateAutoTimeExpression", + "type": "Function", + "tags": [], + "label": "calculateAutoTimeExpression", + "description": [], + "signature": [ + "(range: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataQueryPluginApi", "section": "def-common.TimeRange", "text": "TimeRange" }, - ") => string | undefined" + ") => string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.calculateAutoTimeExpression.$1", + "type": "Object", + "tags": [], + "label": "range", + "description": [], + "signature": [ + "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" + ], + "path": "src/plugins/data/common/search/aggs/utils/calculate_auto_time_expression.ts", + "deprecated": false, + "trackAdoption": false + } + ] + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.createAggConfigs", + "type": "Function", + "tags": [], + "label": "createAggConfigs", + "description": [], + "signature": [ + "(indexPattern: ", + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataView", + "text": "DataView" + }, + ", configStates?: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CreateAggConfigParams", + "text": "CreateAggConfigParams" + }, + "[] | undefined, options?: Partial<", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfigsOptions", + "text": "AggConfigsOptions" + }, + "> | undefined) => ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfigs", + "text": "AggConfigs" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.createAggConfigs.$1", + "type": "Object", + "tags": [], + "label": "indexPattern", + "description": [], + "signature": [ + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataView", + "text": "DataView" + } + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.createAggConfigs.$2", + "type": "Array", + "tags": [], + "label": "configStates", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CreateAggConfigParams", + "text": "CreateAggConfigParams" + }, + "[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.createAggConfigs.$3", + "type": "Object", + "tags": [], + "label": "options", + "description": [], + "signature": [ + "Partial<", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfigsOptions", + "text": "AggConfigsOptions" + }, + "> | undefined" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + } + ], + "returnComment": [] + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStart.types", + "type": "Object", + "tags": [], + "label": "types", + "description": [], + "signature": [ + "{ get: (name: string) => ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BucketAggType", + "text": "BucketAggType" + }, + " | ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.MetricAggType", + "text": "MetricAggType" + }, + "; getAll: () => { buckets: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BucketAggType", + "text": "BucketAggType" + }, + "[]; metrics: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.MetricAggType", + "text": "MetricAggType" + }, + "[]; }; }" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies", + "type": "Interface", + "tags": [], + "label": "AggsCommonStartDependencies", + "description": [], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.getIndexPattern", + "type": "Function", + "tags": [], + "label": "getIndexPattern", + "description": [], + "signature": [ + "(id: string) => Promise<", + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataView", + "text": "DataView" + }, + ">" + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.getIndexPattern.$1", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "signature": [ + "string" + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.getConfig", + "type": "Function", + "tags": [], + "label": "getConfig", + "description": [], + "signature": [ + "(key: string, defaultOverride?: T | undefined) => T" + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.getConfig.$1", + "type": "string", + "tags": [], + "label": "key", + "description": [], + "path": "src/plugins/data/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.getConfig.$2", + "type": "Uncategorized", + "tags": [], + "label": "defaultOverride", + "description": [], + "signature": [ + "T | undefined" + ], + "path": "src/plugins/data/common/types.ts", + "deprecated": false, + "trackAdoption": false + } + ] + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.fieldFormats", + "type": "Object", + "tags": [], + "label": "fieldFormats", + "description": [], + "signature": [ + "{ deserialize: ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FormatFactory", + "text": "FormatFactory" + }, + "; getDefaultConfig: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined) => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatConfig", + "text": "FieldFormatConfig" + }, + "; getType: (formatId: string) => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatInstanceType", + "text": "FieldFormatInstanceType" + }, + " | undefined; getTypeWithoutMetaParams: (formatId: string) => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatInstanceType", + "text": "FieldFormatInstanceType" + }, + " | undefined; getDefaultType: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined) => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatInstanceType", + "text": "FieldFormatInstanceType" + }, + " | undefined; getTypeNameByEsTypes: (esTypes: ", + "ES_FIELD_TYPES", + "[] | undefined) => ", + "ES_FIELD_TYPES", + " | undefined; getDefaultTypeName: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined) => ", + "ES_FIELD_TYPES", + " | ", + "KBN_FIELD_TYPES", + "; getInstance: (formatId: string, params?: ", + "SerializableRecord", + ") => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormat", + "text": "FieldFormat" + }, + "; getDefaultInstancePlain: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined, params?: ", + "SerializableRecord", + ") => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormat", + "text": "FieldFormat" + }, + "; getDefaultInstanceCacheResolver: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined) => string; getByFieldType: (fieldType: ", + "KBN_FIELD_TYPES", + ") => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatInstanceType", + "text": "FieldFormatInstanceType" + }, + "[]; getDefaultInstance: (fieldType: ", + "KBN_FIELD_TYPES", + ", esTypes?: ", + "ES_FIELD_TYPES", + "[] | undefined, params?: ", + "SerializableRecord", + ") => ", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormat", + "text": "FieldFormat" + }, + "; parseDefaultTypeMap: (value: Record) => void; has: (id: string) => boolean; }" + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.calculateBounds", + "type": "Function", + "tags": [], + "label": "calculateBounds", + "description": [], + "signature": [ + "(timeRange: ", + "TimeRange", + ") => ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataQueryPluginApi", + "section": "def-common.TimeRangeBounds", + "text": "TimeRangeBounds" + } + ], + "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggsCommonStartDependencies.calculateBounds.$1", + "type": "Object", + "tags": [], + "label": "timeRange", + "description": [], + "signature": [ + "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" + ], + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "deprecated": false, + "trackAdoption": false + } + ] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig", + "type": "Interface", + "tags": [], + "label": "AggTypeConfig", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggTypeConfig", + "text": "AggTypeConfig" + }, + "" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.name", + "type": "string", + "tags": [], + "label": "name", + "description": [], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.title", + "type": "string", + "tags": [], + "label": "title", + "description": [], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.createFilter", + "type": "Function", + "tags": [], + "label": "createFilter", + "description": [], + "signature": [ + "((aggConfig: TAggConfig, key: any, params?: any) => any) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.createFilter.$1", + "type": "Uncategorized", + "tags": [], + "label": "aggConfig", + "description": [], + "signature": [ + "TAggConfig" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.createFilter.$2", + "type": "Any", + "tags": [], + "label": "key", + "description": [], + "signature": [ + "any" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.createFilter.$3", + "type": "Any", + "tags": [], + "label": "params", + "description": [], + "signature": [ + "any" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.type", + "type": "string", + "tags": [], + "label": "type", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.dslName", + "type": "string", + "tags": [], + "label": "dslName", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.expressionName", + "type": "string", + "tags": [], + "label": "expressionName", + "description": [], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.makeLabel", + "type": "CompoundType", + "tags": [], + "label": "makeLabel", + "description": [], + "signature": [ + "((aggConfig: TAggConfig) => string) | (() => string) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.ordered", + "type": "Any", + "tags": [], + "label": "ordered", + "description": [], + "signature": [ + "any" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.hasNoDsl", + "type": "CompoundType", + "tags": [], + "label": "hasNoDsl", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.hasNoDslParams", + "type": "CompoundType", + "tags": [], + "label": "hasNoDslParams", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.params", + "type": "Array", + "tags": [], + "label": "params", + "description": [], + "signature": [ + "Partial[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.valueType", + "type": "CompoundType", + "tags": [], + "label": "valueType", + "description": [], + "signature": [ + { + "pluginId": "expressions", + "scope": "common", + "docId": "kibExpressionsPluginApi", + "section": "def-common.DatatableColumnType", + "text": "DatatableColumnType" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/types.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, - "trackAdoption": false, - "returnComment": [], - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggsCommonStart.calculateAutoTimeExpression.$1", - "type": "Object", - "tags": [], - "label": "range", - "description": [], - "signature": [ - "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" - ], - "path": "src/plugins/data/common/search/aggs/utils/calculate_auto_time_expression.ts", - "deprecated": false, - "trackAdoption": false - } - ] + "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStart.createAggConfigs", + "id": "def-common.AggTypeConfig.getRequestAggs", + "type": "CompoundType", + "tags": [], + "label": "getRequestAggs", + "description": [], + "signature": [ + "((aggConfig: TAggConfig) => TAggConfig[]) | (() => void | TAggConfig[]) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getResponseAggs", + "type": "CompoundType", + "tags": [], + "label": "getResponseAggs", + "description": [], + "signature": [ + "((aggConfig: TAggConfig) => TAggConfig[]) | (() => void | TAggConfig[]) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.customLabels", + "type": "CompoundType", + "tags": [], + "label": "customLabels", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.json", + "type": "CompoundType", + "tags": [], + "label": "json", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.decorateAggConfig", "type": "Function", "tags": [], - "label": "createAggConfigs", + "label": "decorateAggConfig", "description": [], "signature": [ - "(indexPattern: ", - { - "pluginId": "dataViews", - "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" - }, - ", configStates?: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.CreateAggConfigParams", - "text": "CreateAggConfigParams" - }, - "[] | undefined, options?: Partial<", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggConfigsOptions", - "text": "AggConfigsOptions" - }, - "> | undefined) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggConfigs", - "text": "AggConfigs" - } + "(() => any) | undefined" ], - "path": "src/plugins/data/common/search/aggs/types.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggsCommonStart.createAggConfigs.$1", - "type": "Object", - "tags": [], - "label": "indexPattern", - "description": [], - "signature": [ - { - "pluginId": "dataViews", - "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" - } - ], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "data", - "id": "def-common.AggsCommonStart.createAggConfigs.$2", - "type": "Array", - "tags": [], - "label": "configStates", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.CreateAggConfigParams", - "text": "CreateAggConfigParams" - }, - "[] | undefined" - ], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggsCommonStart.createAggConfigs.$3", - "type": "Object", - "tags": [], - "label": "options", - "description": [], - "signature": [ - "Partial<", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggConfigsOptions", - "text": "AggConfigsOptions" - }, - "> | undefined" - ], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": false - } - ], + "children": [], "returnComment": [] }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStart.types", - "type": "Object", + "id": "def-common.AggTypeConfig.postFlightRequest", + "type": "Function", "tags": [], - "label": "types", + "label": "postFlightRequest", "description": [], "signature": [ - "{ get: (name: string) => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BucketAggType", - "text": "BucketAggType" - }, - " | ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.MetricAggType", - "text": "MetricAggType" - }, - "; getAll: () => { buckets: ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BucketAggType", - "text": "BucketAggType" - }, - "[]; metrics: ", + "PostFlightRequestFn | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.hasPrecisionError", + "type": "Function", + "tags": [], + "label": "hasPrecisionError", + "description": [], + "signature": [ + "((aggBucket: Record) => boolean) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.MetricAggType", - "text": "MetricAggType" - }, - "[]; }; }" + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.hasPrecisionError.$1", + "type": "Object", + "tags": [], + "label": "aggBucket", + "description": [], + "signature": [ + "Record" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } ], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies", - "type": "Interface", - "tags": [], - "label": "AggsCommonStartDependencies", - "description": [], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ + "returnComment": [] + }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.getIndexPattern", + "id": "def-common.AggTypeConfig.getSerializedFormat", "type": "Function", "tags": [], - "label": "getIndexPattern", + "label": "getSerializedFormat", "description": [], "signature": [ - "(id: string) => Promise<", + "((agg: TAggConfig) => ", { - "pluginId": "dataViews", + "pluginId": "fieldFormats", "scope": "common", - "docId": "kibDataViewsPluginApi", - "section": "def-common.DataView", - "text": "DataView" + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.SerializedFieldFormat", + "text": "SerializedFieldFormat" }, - ">" + "<{}, ", + "SerializableRecord", + ">) | undefined" ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.getIndexPattern.$1", - "type": "string", + "id": "def-common.AggTypeConfig.getSerializedFormat.$1", + "type": "Uncategorized", "tags": [], - "label": "id", + "label": "agg", "description": [], "signature": [ - "string" + "TAggConfig" ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, "trackAdoption": false, "isRequired": true @@ -22278,321 +24074,256 @@ }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.getConfig", + "id": "def-common.AggTypeConfig.getValue", "type": "Function", "tags": [], - "label": "getConfig", + "label": "getValue", "description": [], "signature": [ - "(key: string, defaultOverride?: T | undefined) => T" + "((agg: TAggConfig, bucket: any) => any) | undefined" ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, "trackAdoption": false, - "returnComment": [], "children": [ { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.getConfig.$1", - "type": "string", + "id": "def-common.AggTypeConfig.getValue.$1", + "type": "Uncategorized", "tags": [], - "label": "key", + "label": "agg", "description": [], - "path": "src/plugins/data/common/types.ts", + "signature": [ + "TAggConfig" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.getConfig.$2", - "type": "Uncategorized", + "id": "def-common.AggTypeConfig.getValue.$2", + "type": "Any", "tags": [], - "label": "defaultOverride", + "label": "bucket", "description": [], "signature": [ - "T | undefined" + "any" ], - "path": "src/plugins/data/common/types.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true } - ] + ], + "returnComment": [] }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.fieldFormats", - "type": "Object", + "id": "def-common.AggTypeConfig.getKey", + "type": "Function", "tags": [], - "label": "fieldFormats", + "label": "getKey", "description": [], "signature": [ - "{ deserialize: ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FormatFactory", - "text": "FormatFactory" - }, - "; getDefaultConfig: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined) => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatConfig", - "text": "FieldFormatConfig" - }, - "; getType: (formatId: string) => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatInstanceType", - "text": "FieldFormatInstanceType" - }, - " | undefined; getTypeWithoutMetaParams: (formatId: string) => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatInstanceType", - "text": "FieldFormatInstanceType" - }, - " | undefined; getDefaultType: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined) => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatInstanceType", - "text": "FieldFormatInstanceType" - }, - " | undefined; getTypeNameByEsTypes: (esTypes: ", - "ES_FIELD_TYPES", - "[] | undefined) => ", - "ES_FIELD_TYPES", - " | undefined; getDefaultTypeName: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined) => ", - "ES_FIELD_TYPES", - " | ", - "KBN_FIELD_TYPES", - "; getInstance: (formatId: string, params?: ", - "SerializableRecord", - ") => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormat", - "text": "FieldFormat" - }, - "; getDefaultInstancePlain: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined, params?: ", - "SerializableRecord", - ") => ", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormat", - "text": "FieldFormat" - }, - "; getDefaultInstanceCacheResolver: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined) => string; getByFieldType: (fieldType: ", - "KBN_FIELD_TYPES", - ") => ", + "((bucket: any, key: any, agg: TAggConfig) => any) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatInstanceType", - "text": "FieldFormatInstanceType" + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getKey.$1", + "type": "Any", + "tags": [], + "label": "bucket", + "description": [], + "signature": [ + "any" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true }, - "[]; getDefaultInstance: (fieldType: ", - "KBN_FIELD_TYPES", - ", esTypes?: ", - "ES_FIELD_TYPES", - "[] | undefined, params?: ", - "SerializableRecord", - ") => ", { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormat", - "text": "FieldFormat" + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getKey.$2", + "type": "Any", + "tags": [], + "label": "key", + "description": [], + "signature": [ + "any" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true }, - "; parseDefaultTypeMap: (value: Record) => void; has: (id: string) => boolean; }" + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getKey.$3", + "type": "Uncategorized", + "tags": [], + "label": "agg", + "description": [], + "signature": [ + "TAggConfig" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", - "deprecated": false, - "trackAdoption": false + "returnComment": [] }, { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.calculateBounds", + "id": "def-common.AggTypeConfig.getValueBucketPath", "type": "Function", "tags": [], - "label": "calculateBounds", + "label": "getValueBucketPath", "description": [], "signature": [ - "(timeRange: ", - "TimeRange", - ") => ", + "((agg: TAggConfig) => string) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", - "section": "def-common.TimeRangeBounds", - "text": "TimeRangeBounds" + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getValueBucketPath.$1", + "type": "Uncategorized", + "tags": [], + "label": "agg", + "description": [], + "signature": [ + "TAggConfig" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true } ], - "path": "src/plugins/data/common/search/aggs/aggs_service.ts", + "returnComment": [] + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypeConfig.getResponseId", + "type": "Function", + "tags": [], + "label": "getResponseId", + "description": [], + "signature": [ + "((agg: TAggConfig) => string) | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, "trackAdoption": false, - "returnComment": [], "children": [ { "parentPluginId": "data", - "id": "def-common.AggsCommonStartDependencies.calculateBounds.$1", - "type": "Object", + "id": "def-common.AggTypeConfig.getResponseId.$1", + "type": "Uncategorized", "tags": [], - "label": "timeRange", + "label": "agg", "description": [], "signature": [ - "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" + "TAggConfig" ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", + "path": "src/plugins/data/common/search/aggs/agg_type.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true } - ] + ], + "returnComment": [] } ], "initialIsOpen": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig", + "id": "def-common.AggTypesDependencies", "type": "Interface", "tags": [], - "label": "AggTypeConfig", + "label": "AggTypesDependencies", "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggTypeConfig", - "text": "AggTypeConfig" - }, - "" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/agg_types.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.name", - "type": "string", - "tags": [], - "label": "name", - "description": [], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.title", - "type": "string", - "tags": [], - "label": "title", - "description": [], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.createFilter", + "id": "def-common.AggTypesDependencies.calculateBounds", "type": "Function", "tags": [], - "label": "createFilter", + "label": "calculateBounds", "description": [], "signature": [ - "((aggConfig: TAggConfig, key: any, params?: any) => any) | undefined" + "(timeRange: ", + "TimeRange", + ") => ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataQueryPluginApi", + "section": "def-common.TimeRangeBounds", + "text": "TimeRangeBounds" + } ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/agg_types.ts", "deprecated": false, "trackAdoption": false, + "returnComment": [], "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.createFilter.$1", - "type": "Uncategorized", + "id": "def-common.AggTypesDependencies.calculateBounds.$1", + "type": "Object", "tags": [], - "label": "aggConfig", + "label": "timeRange", "description": [], "signature": [ - "TAggConfig" + "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, + "trackAdoption": false + } + ] + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypesDependencies.getConfig", + "type": "Function", + "tags": [], + "label": "getConfig", + "description": [], + "signature": [ + "(key: string) => T" + ], + "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.createFilter.$2", - "type": "Any", + "id": "def-common.AggTypesDependencies.getConfig.$1", + "type": "string", "tags": [], "label": "key", "description": [], "signature": [ - "any" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.createFilter.$3", - "type": "Any", - "tags": [], - "label": "params", - "description": [], - "signature": [ - "any" + "string" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/agg_types.ts", "deprecated": false, "trackAdoption": false, "isRequired": true @@ -22602,588 +24333,625 @@ }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.type", + "id": "def-common.AggTypesDependencies.getFieldFormatsStart", + "type": "Function", + "tags": [], + "label": "getFieldFormatsStart", + "description": [], + "signature": [ + "() => Pick<", + { + "pluginId": "fieldFormats", + "scope": "common", + "docId": "kibFieldFormatsPluginApi", + "section": "def-common.FieldFormatsStartCommon", + "text": "FieldFormatsStartCommon" + }, + ", \"deserialize\" | \"getDefaultInstance\">" + ], + "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "returnComment": [] + }, + { + "parentPluginId": "data", + "id": "def-common.AggTypesDependencies.aggExecutionContext", + "type": "Object", + "tags": [], + "label": "aggExecutionContext", + "description": [], + "signature": [ + "{ shouldDetectTimeZone?: boolean | undefined; } | undefined" + ], + "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.AutoBounds", + "type": "Interface", + "tags": [], + "label": "AutoBounds", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.AutoBounds.min", + "type": "number", + "tags": [], + "label": "min", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.AutoBounds.max", + "type": "number", + "tags": [], + "label": "max", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.BaseAggParams", + "type": "Interface", + "tags": [], + "label": "BaseAggParams", + "description": [], + "path": "src/plugins/data/common/search/aggs/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "data", + "id": "def-common.BaseAggParams.json", "type": "string", "tags": [], - "label": "type", + "label": "json", "description": [], "signature": [ "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.dslName", + "id": "def-common.BaseAggParams.customLabel", "type": "string", "tags": [], - "label": "dslName", + "label": "customLabel", "description": [], "signature": [ "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.expressionName", + "id": "def-common.BaseAggParams.timeShift", "type": "string", "tags": [], - "label": "expressionName", + "label": "timeShift", "description": [], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/types.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.BaseAggParamsTopHit", + "type": "Interface", + "tags": [], + "label": "BaseAggParamsTopHit", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopHit", + "text": "BaseAggParamsTopHit" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.makeLabel", - "type": "CompoundType", + "id": "def-common.BaseAggParamsTopHit.field", + "type": "string", "tags": [], - "label": "makeLabel", + "label": "field", "description": [], - "signature": [ - "((aggConfig: TAggConfig) => string) | (() => string) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.ordered", - "type": "Any", + "id": "def-common.BaseAggParamsTopHit.aggregate", + "type": "CompoundType", "tags": [], - "label": "ordered", + "label": "aggregate", "description": [], "signature": [ - "any" + "\"min\" | \"max\" | \"sum\" | \"average\" | \"concat\"" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.hasNoDsl", - "type": "CompoundType", + "id": "def-common.BaseAggParamsTopHit.size", + "type": "number", "tags": [], - "label": "hasNoDsl", + "label": "size", "description": [], "signature": [ - "boolean | undefined" + "number | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/metrics/top_hit.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.BaseAggParamsTopMetrics", + "type": "Interface", + "tags": [], + "label": "BaseAggParamsTopMetrics", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParamsTopMetrics", + "text": "BaseAggParamsTopMetrics" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.hasNoDslParams", - "type": "CompoundType", + "id": "def-common.BaseAggParamsTopMetrics.field", + "type": "string", "tags": [], - "label": "hasNoDslParams", + "label": "field", "description": [], - "signature": [ - "boolean | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.params", - "type": "Array", + "id": "def-common.BaseAggParamsTopMetrics.size", + "type": "number", "tags": [], - "label": "params", + "label": "size", "description": [], "signature": [ - "Partial[] | undefined" + "number | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/metrics/top_metrics.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.BaseHit", + "type": "Interface", + "tags": [], + "label": "BaseHit", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseHit", + "text": "BaseHit" }, + "" + ], + "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.valueType", - "type": "CompoundType", + "id": "def-common.BaseHit._index", + "type": "string", "tags": [], - "label": "valueType", + "label": "_index", "description": [], - "signature": [ - { - "pluginId": "expressions", - "scope": "common", - "docId": "kibExpressionsPluginApi", - "section": "def-common.DatatableColumnType", - "text": "DatatableColumnType" - }, - " | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getRequestAggs", - "type": "CompoundType", + "id": "def-common.BaseHit._id", + "type": "string", "tags": [], - "label": "getRequestAggs", + "label": "_id", "description": [], - "signature": [ - "((aggConfig: TAggConfig) => TAggConfig[]) | (() => void | TAggConfig[]) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getResponseAggs", - "type": "CompoundType", + "id": "def-common.BaseHit._source", + "type": "Uncategorized", "tags": [], - "label": "getResponseAggs", + "label": "_source", "description": [], "signature": [ - "((aggConfig: TAggConfig) => TAggConfig[]) | (() => void | TAggConfig[]) | undefined" + "T" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.customLabels", - "type": "CompoundType", + "id": "def-common.BaseHit.fields", + "type": "Object", "tags": [], - "label": "customLabels", + "label": "fields", "description": [], "signature": [ - "boolean | undefined" + "Record | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", "deprecated": false, "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.BucketAggParam", + "type": "Interface", + "tags": [], + "label": "BucketAggParam", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BucketAggParam", + "text": "BucketAggParam" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamType", + "text": "AggParamType" }, + "" + ], + "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.json", + "id": "def-common.BucketAggParam.scriptable", "type": "CompoundType", "tags": [], - "label": "json", + "label": "scriptable", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.decorateAggConfig", - "type": "Function", + "id": "def-common.BucketAggParam.filterFieldTypes", + "type": "CompoundType", "tags": [], - "label": "decorateAggConfig", + "label": "filterFieldTypes", "description": [], "signature": [ - "(() => any) | undefined" + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.FieldTypes", + "text": "FieldTypes" + }, + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.postFlightRequest", - "type": "Function", + "id": "def-common.BucketAggParam.onlyAggregatable", + "type": "CompoundType", "tags": [], - "label": "postFlightRequest", + "label": "onlyAggregatable", "description": [], "signature": [ - "PostFlightRequestFn | undefined" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.hasPrecisionError", + "id": "def-common.BucketAggParam.filterField", "type": "Function", "tags": [], - "label": "hasPrecisionError", - "description": [], - "signature": [ - "((aggBucket: Record) => boolean) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.hasPrecisionError.$1", - "type": "Object", - "tags": [], - "label": "aggBucket", - "description": [], - "signature": [ - "Record" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } + "label": "filterField", + "description": [ + "\nFilter available fields by passing filter fn on a {@link DataViewField}\nIf used, takes precedence over filterFieldTypes and other filter params" ], - "returnComment": [] - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getSerializedFormat", - "type": "Function", - "tags": [], - "label": "getSerializedFormat", - "description": [], "signature": [ - "((agg: TAggConfig) => ", { - "pluginId": "fieldFormats", + "pluginId": "data", "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.SerializedFieldFormat", - "text": "SerializedFieldFormat" + "docId": "kibDataSearchPluginApi", + "section": "def-common.FilterFieldFn", + "text": "FilterFieldFn" }, - "<{}, ", - "SerializableRecord", - ">) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getSerializedFormat.$1", - "type": "Uncategorized", - "tags": [], - "label": "agg", - "description": [], - "signature": [ - "TAggConfig" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getValue", - "type": "Function", - "tags": [], - "label": "getValue", - "description": [], - "signature": [ - "((agg: TAggConfig, bucket: any) => any) | undefined" + " | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getValue.$1", - "type": "Uncategorized", - "tags": [], - "label": "agg", - "description": [], - "signature": [ - "TAggConfig" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getValue.$2", - "type": "Any", - "tags": [], - "label": "bucket", - "description": [], - "signature": [ - "any" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] - }, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.Cidr", + "type": "Interface", + "tags": [], + "label": "Cidr", + "description": [], + "path": "src/plugins/data/common/search/expressions/cidr.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getKey", - "type": "Function", + "id": "def-common.Cidr.mask", + "type": "string", "tags": [], - "label": "getKey", + "label": "mask", "description": [], - "signature": [ - "((bucket: any, key: any, agg: TAggConfig) => any) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/expressions/cidr.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getKey.$1", - "type": "Any", - "tags": [], - "label": "bucket", - "description": [], - "signature": [ - "any" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getKey.$2", - "type": "Any", - "tags": [], - "label": "key", - "description": [], - "signature": [ - "any" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - }, - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getKey.$3", - "type": "Uncategorized", - "tags": [], - "label": "agg", - "description": [], - "signature": [ - "TAggConfig" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] - }, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.CidrMaskIpRangeAggKey", + "type": "Interface", + "tags": [], + "label": "CidrMaskIpRangeAggKey", + "description": [], + "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getValueBucketPath", - "type": "Function", + "id": "def-common.CidrMaskIpRangeAggKey.type", + "type": "string", "tags": [], - "label": "getValueBucketPath", + "label": "type", "description": [], "signature": [ - "((agg: TAggConfig) => string) | undefined" + "\"mask\"" ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getValueBucketPath.$1", - "type": "Uncategorized", - "tags": [], - "label": "agg", - "description": [], - "signature": [ - "TAggConfig" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getResponseId", - "type": "Function", + "id": "def-common.CidrMaskIpRangeAggKey.mask", + "type": "string", "tags": [], - "label": "getResponseId", + "label": "mask", "description": [], - "signature": [ - "((agg: TAggConfig) => string) | undefined" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypeConfig.getResponseId.$1", - "type": "Uncategorized", - "tags": [], - "label": "agg", - "description": [], - "signature": [ - "TAggConfig" - ], - "path": "src/plugins/data/common/search/aggs/agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false } ], "initialIsOpen": false }, { "parentPluginId": "data", - "id": "def-common.AggTypesDependencies", + "id": "def-common.CommonAggParamsCumulativeSum", "type": "Interface", "tags": [], - "label": "AggTypesDependencies", + "label": "CommonAggParamsCumulativeSum", "description": [], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsCumulativeSum", + "text": "CommonAggParamsCumulativeSum" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.calculateBounds", - "type": "Function", + "id": "def-common.CommonAggParamsCumulativeSum.buckets_path", + "type": "string", "tags": [], - "label": "calculateBounds", + "label": "buckets_path", "description": [], "signature": [ - "(timeRange: ", - "TimeRange", - ") => ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataQueryPluginApi", - "section": "def-common.TimeRangeBounds", - "text": "TimeRangeBounds" - } + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, - "trackAdoption": false, - "returnComment": [], - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.calculateBounds.$1", - "type": "Object", - "tags": [], - "label": "timeRange", - "description": [], - "signature": [ - "{ from: string; to: string; mode?: \"absolute\" | \"relative\" | undefined; }" - ], - "path": "src/plugins/data/common/search/aggs/buckets/date_histogram.ts", - "deprecated": false, - "trackAdoption": false - } - ] + "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.getConfig", - "type": "Function", + "id": "def-common.CommonAggParamsCumulativeSum.metricAgg", + "type": "string", "tags": [], - "label": "getConfig", + "label": "metricAgg", "description": [], "signature": [ - "(key: string) => T" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts", "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.getConfig.$1", - "type": "string", - "tags": [], - "label": "key", - "description": [], - "signature": [ - "string" - ], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", - "deprecated": false, - "trackAdoption": false, - "isRequired": true - } - ], - "returnComment": [] + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "data", + "id": "def-common.CommonAggParamsDerivative", + "type": "Interface", + "tags": [], + "label": "CommonAggParamsDerivative", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsDerivative", + "text": "CommonAggParamsDerivative" }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ { "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.getFieldFormatsStart", - "type": "Function", + "id": "def-common.CommonAggParamsDerivative.buckets_path", + "type": "string", "tags": [], - "label": "getFieldFormatsStart", + "label": "buckets_path", "description": [], "signature": [ - "() => Pick<", - { - "pluginId": "fieldFormats", - "scope": "common", - "docId": "kibFieldFormatsPluginApi", - "section": "def-common.FieldFormatsStartCommon", - "text": "FieldFormatsStartCommon" - }, - ", \"deserialize\" | \"getDefaultInstance\">" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, - "trackAdoption": false, - "children": [], - "returnComment": [] + "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AggTypesDependencies.aggExecutionContext", - "type": "Object", + "id": "def-common.CommonAggParamsDerivative.metricAgg", + "type": "string", "tags": [], - "label": "aggExecutionContext", + "label": "metricAgg", "description": [], "signature": [ - "{ shouldDetectTimeZone?: boolean | undefined; } | undefined" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/agg_types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/derivative.ts", "deprecated": false, "trackAdoption": false } @@ -23192,34 +24960,85 @@ }, { "parentPluginId": "data", - "id": "def-common.AutoBounds", + "id": "def-common.CommonAggParamsMovingAvg", "type": "Interface", "tags": [], - "label": "AutoBounds", + "label": "CommonAggParamsMovingAvg", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsMovingAvg", + "text": "CommonAggParamsMovingAvg" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.AutoBounds.min", - "type": "number", + "id": "def-common.CommonAggParamsMovingAvg.buckets_path", + "type": "string", "tags": [], - "label": "min", + "label": "buckets_path", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.AutoBounds.max", + "id": "def-common.CommonAggParamsMovingAvg.window", "type": "number", "tags": [], - "label": "max", + "label": "window", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/histogram.ts", + "signature": [ + "number | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.CommonAggParamsMovingAvg.script", + "type": "string", + "tags": [], + "label": "script", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.CommonAggParamsMovingAvg.metricAgg", + "type": "string", + "tags": [], + "label": "metricAgg", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/data/common/search/aggs/metrics/moving_avg.ts", "deprecated": false, "trackAdoption": false } @@ -23228,54 +25047,57 @@ }, { "parentPluginId": "data", - "id": "def-common.BaseAggParams", + "id": "def-common.CommonAggParamsSerialDiff", "type": "Interface", "tags": [], - "label": "BaseAggParams", + "label": "CommonAggParamsSerialDiff", "description": [], - "path": "src/plugins/data/common/search/aggs/types.ts", + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.CommonAggParamsSerialDiff", + "text": "CommonAggParamsSerialDiff" + }, + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } + ], + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.BaseAggParams.json", - "type": "string", - "tags": [], - "label": "json", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "src/plugins/data/common/search/aggs/types.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "data", - "id": "def-common.BaseAggParams.customLabel", + "id": "def-common.CommonAggParamsSerialDiff.buckets_path", "type": "string", "tags": [], - "label": "customLabel", + "label": "buckets_path", "description": [], "signature": [ "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BaseAggParams.timeShift", + "id": "def-common.CommonAggParamsSerialDiff.metricAgg", "type": "string", "tags": [], - "label": "timeShift", + "label": "metricAgg", "description": [], "signature": [ "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/types.ts", + "path": "src/plugins/data/common/search/aggs/metrics/serial_diff.ts", "deprecated": false, "trackAdoption": false } @@ -23284,248 +25106,191 @@ }, { "parentPluginId": "data", - "id": "def-common.BaseHit", + "id": "def-common.CommonAggParamsTerms", "type": "Interface", "tags": [], - "label": "BaseHit", + "label": "CommonAggParamsTerms", "description": [], "signature": [ { "pluginId": "data", "scope": "common", "docId": "kibDataSearchPluginApi", - "section": "def-common.BaseHit", - "text": "BaseHit" + "section": "def-common.CommonAggParamsTerms", + "text": "CommonAggParamsTerms" }, - "" + " extends ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BaseAggParams", + "text": "BaseAggParams" + } ], - "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "data", - "id": "def-common.BaseHit._index", + "id": "def-common.CommonAggParamsTerms.field", "type": "string", "tags": [], - "label": "_index", + "label": "field", "description": [], - "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BaseHit._id", + "id": "def-common.CommonAggParamsTerms.orderBy", "type": "string", "tags": [], - "label": "_id", + "label": "orderBy", "description": [], - "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BaseHit._source", - "type": "Uncategorized", + "id": "def-common.CommonAggParamsTerms.size", + "type": "number", "tags": [], - "label": "_source", + "label": "size", "description": [], "signature": [ - "T" + "number | undefined" ], - "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BaseHit.fields", - "type": "Object", + "id": "def-common.CommonAggParamsTerms.shardSize", + "type": "number", "tags": [], - "label": "fields", + "label": "shardSize", "description": [], "signature": [ - "Record | undefined" + "number | undefined" ], - "path": "src/plugins/data/common/search/expressions/eql_raw_response.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.BucketAggParam", - "type": "Interface", - "tags": [], - "label": "BucketAggParam", - "description": [], - "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.BucketAggParam", - "text": "BucketAggParam" - }, - " extends ", - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.AggParamType", - "text": "AggParamType" }, - "" - ], - "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ { "parentPluginId": "data", - "id": "def-common.BucketAggParam.scriptable", + "id": "def-common.CommonAggParamsTerms.missingBucket", "type": "CompoundType", "tags": [], - "label": "scriptable", + "label": "missingBucket", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BucketAggParam.filterFieldTypes", - "type": "CompoundType", + "id": "def-common.CommonAggParamsTerms.missingBucketLabel", + "type": "string", "tags": [], - "label": "filterFieldTypes", + "label": "missingBucketLabel", "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.FieldTypes", - "text": "FieldTypes" - }, - " | undefined" + "string | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BucketAggParam.onlyAggregatable", + "id": "def-common.CommonAggParamsTerms.otherBucket", "type": "CompoundType", "tags": [], - "label": "onlyAggregatable", + "label": "otherBucket", "description": [], "signature": [ "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.BucketAggParam.filterField", - "type": "Function", + "id": "def-common.CommonAggParamsTerms.otherBucketLabel", + "type": "string", "tags": [], - "label": "filterField", - "description": [ - "\nFilter available fields by passing filter fn on a {@link DataViewField}\nIf used, takes precedence over filterFieldTypes and other filter params" + "label": "otherBucketLabel", + "description": [], + "signature": [ + "string | undefined" ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "data", + "id": "def-common.CommonAggParamsTerms.exclude", + "type": "CompoundType", + "tags": [], + "label": "exclude", + "description": [], "signature": [ - { - "pluginId": "data", - "scope": "common", - "docId": "kibDataSearchPluginApi", - "section": "def-common.FilterFieldFn", - "text": "FilterFieldFn" - }, - " | undefined" + "string | string[] | number[] | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/bucket_agg_type.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.Cidr", - "type": "Interface", - "tags": [], - "label": "Cidr", - "description": [], - "path": "src/plugins/data/common/search/expressions/cidr.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ + }, { "parentPluginId": "data", - "id": "def-common.Cidr.mask", - "type": "string", + "id": "def-common.CommonAggParamsTerms.include", + "type": "CompoundType", "tags": [], - "label": "mask", + "label": "include", "description": [], - "path": "src/plugins/data/common/search/expressions/cidr.ts", + "signature": [ + "string | string[] | number[] | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "data", - "id": "def-common.CidrMaskIpRangeAggKey", - "type": "Interface", - "tags": [], - "label": "CidrMaskIpRangeAggKey", - "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ + }, { "parentPluginId": "data", - "id": "def-common.CidrMaskIpRangeAggKey.type", - "type": "string", + "id": "def-common.CommonAggParamsTerms.includeIsRegex", + "type": "CompoundType", "tags": [], - "label": "type", + "label": "includeIsRegex", "description": [], "signature": [ - "\"mask\"" + "boolean | undefined" ], - "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "data", - "id": "def-common.CidrMaskIpRangeAggKey.mask", - "type": "string", + "id": "def-common.CommonAggParamsTerms.excludeIsRegex", + "type": "CompoundType", "tags": [], - "label": "mask", + "label": "excludeIsRegex", "description": [], - "path": "src/plugins/data/common/search/aggs/buckets/lib/ip_range.ts", + "signature": [ + "boolean | undefined" + ], + "path": "src/plugins/data/common/search/aggs/buckets/terms.ts", "deprecated": false, "trackAdoption": false } @@ -31653,6 +33418,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "data", + "id": "def-common.SHARD_DELAY_AGG_NAME", + "type": "string", + "tags": [], + "label": "SHARD_DELAY_AGG_NAME", + "description": [], + "signature": [ + "\"shard_delay\"" + ], + "path": "src/plugins/data/common/search/aggs/buckets/shard_delay.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "data", "id": "def-common.siblingPipelineType", diff --git a/api_docs/data_search.mdx b/api_docs/data_search.mdx index 52115cd39ca0c..619cec4220ea7 100644 --- a/api_docs/data_search.mdx +++ b/api_docs/data_search.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/data-search title: "data.search" image: https://source.unsplash.com/400x175/?github description: API docs for the data.search plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'data.search'] --- import dataSearchObj from './data_search.devdocs.json'; @@ -21,7 +21,7 @@ Contact [App Services](https://github.com/orgs/elastic/teams/kibana-app-services | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 3132 | 33 | 2429 | 23 | +| 3213 | 33 | 2509 | 23 | ## Client diff --git a/api_docs/data_view_editor.mdx b/api_docs/data_view_editor.mdx index 511552542ef48..f0d1bf1f9d458 100644 --- a/api_docs/data_view_editor.mdx +++ b/api_docs/data_view_editor.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dataViewEditor title: "dataViewEditor" image: https://source.unsplash.com/400x175/?github description: API docs for the dataViewEditor plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dataViewEditor'] --- import dataViewEditorObj from './data_view_editor.devdocs.json'; diff --git a/api_docs/data_view_field_editor.mdx b/api_docs/data_view_field_editor.mdx index 21cd1c4f73ce1..9800b25ff8baf 100644 --- a/api_docs/data_view_field_editor.mdx +++ b/api_docs/data_view_field_editor.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dataViewFieldEditor title: "dataViewFieldEditor" image: https://source.unsplash.com/400x175/?github description: API docs for the dataViewFieldEditor plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dataViewFieldEditor'] --- import dataViewFieldEditorObj from './data_view_field_editor.devdocs.json'; diff --git a/api_docs/data_view_management.mdx b/api_docs/data_view_management.mdx index d95532f82b1c6..d2f23607c286c 100644 --- a/api_docs/data_view_management.mdx +++ b/api_docs/data_view_management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dataViewManagement title: "dataViewManagement" image: https://source.unsplash.com/400x175/?github description: API docs for the dataViewManagement plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dataViewManagement'] --- import dataViewManagementObj from './data_view_management.devdocs.json'; diff --git a/api_docs/data_views.mdx b/api_docs/data_views.mdx index 7355bdbd438d9..3c9d9dc38bae9 100644 --- a/api_docs/data_views.mdx +++ b/api_docs/data_views.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dataViews title: "dataViews" image: https://source.unsplash.com/400x175/?github description: API docs for the dataViews plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dataViews'] --- import dataViewsObj from './data_views.devdocs.json'; diff --git a/api_docs/data_visualizer.mdx b/api_docs/data_visualizer.mdx index c5b8caa7cb8f8..86bbfd4e83cfa 100644 --- a/api_docs/data_visualizer.mdx +++ b/api_docs/data_visualizer.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/dataVisualizer title: "dataVisualizer" image: https://source.unsplash.com/400x175/?github description: API docs for the dataVisualizer plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'dataVisualizer'] --- import dataVisualizerObj from './data_visualizer.devdocs.json'; diff --git a/api_docs/deprecations_by_api.mdx b/api_docs/deprecations_by_api.mdx index c724b31d268da..547c12c8570c2 100644 --- a/api_docs/deprecations_by_api.mdx +++ b/api_docs/deprecations_by_api.mdx @@ -7,7 +7,7 @@ id: kibDevDocsDeprecationsByApi slug: /kibana-dev-docs/api-meta/deprecated-api-list-by-api title: Deprecated API usage by API description: A list of deprecated APIs, which plugins are still referencing them, and when they need to be removed by. -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana'] --- @@ -24,9 +24,9 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | alerting, discover, securitySolution | - | | | stackAlerts, alerting, securitySolution, inputControlVis | - | | | actions, alerting | - | -| | savedObjects, embeddable, fleet, visualizations, infra, canvas, graph, securitySolution, actions, alerting, enterpriseSearch, taskManager, dashboard, savedSearch, ml, @kbn/core-saved-objects-server-internal | - | -| | savedObjects, embeddable, fleet, visualizations, infra, canvas, graph, securitySolution, actions, alerting, enterpriseSearch, taskManager, dashboard, savedSearch, ml, @kbn/core-saved-objects-server-internal | - | -| | discover, dashboard, maps, monitoring | - | +| | savedObjects, embeddable, fleet, visualizations, dashboard, infra, canvas, graph, securitySolution, actions, alerting, enterpriseSearch, taskManager, savedSearch, ml, @kbn/core-saved-objects-server-internal | - | +| | savedObjects, embeddable, fleet, visualizations, dashboard, infra, canvas, graph, securitySolution, actions, alerting, enterpriseSearch, taskManager, savedSearch, ml, @kbn/core-saved-objects-server-internal | - | +| | discover, maps, monitoring | - | | | unifiedSearch, discover, maps, infra, graph, securitySolution, stackAlerts, inputControlVis, savedObjects | - | | | data, discover, embeddable | - | | | advancedSettings, discover | - | @@ -34,7 +34,6 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | securitySolution | - | | | encryptedSavedObjects, actions, data, cloud, ml, logstash, securitySolution | - | | | dashboard, dataVisualizer, stackAlerts, expressionPartitionVis | - | -| | dashboard | - | | | dataViews, maps | - | | | dataViews, maps | - | | | maps | - | @@ -43,6 +42,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | visTypeTimeseries, graph, dataViewManagement, dataViews | - | | | visTypeTimeseries, graph, dataViewManagement, dataViews | - | | | visTypeTimeseries, graph, dataViewManagement | - | +| | dashboard | - | | | observability, dataVisualizer, fleet, cloudSecurityPosture, discoverEnhanced, osquery, synthetics | - | | | dataViewManagement, dataViews | - | | | dataViews, dataViewManagement | - | @@ -75,10 +75,9 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | apm, security, securitySolution | 8.8.0 | | | visualizations, dashboard, lens, maps, ml, securitySolution, security, @kbn/core-application-browser-internal, @kbn/core-application-browser-mocks | 8.8.0 | | | securitySolution, @kbn/core-application-browser-internal | 8.8.0 | -| | savedObjectsTaggingOss, dashboard | 8.8.0 | -| | dashboard | 8.8.0 | | | maps, dashboard, @kbn/core-saved-objects-migration-server-internal | 8.8.0 | | | monitoring, kibanaUsageCollection, @kbn/core-apps-browser-internal, @kbn/core-metrics-server-internal, @kbn/core-status-server-internal, @kbn/core-usage-data-server-internal | 8.8.0 | +| | savedObjectsTaggingOss, dashboard | 8.8.0 | | | security, fleet | 8.8.0 | | | security, fleet | 8.8.0 | | | security, fleet | 8.8.0 | @@ -131,6 +130,7 @@ Safe to remove. | | expressions | | | expressions | | | kibanaReact | +| | savedObjects | | | savedObjects | | | licensing | | | licensing | diff --git a/api_docs/deprecations_by_plugin.mdx b/api_docs/deprecations_by_plugin.mdx index dbf60f18b4e07..3943c847158f1 100644 --- a/api_docs/deprecations_by_plugin.mdx +++ b/api_docs/deprecations_by_plugin.mdx @@ -7,7 +7,7 @@ id: kibDevDocsDeprecationsByPlugin slug: /kibana-dev-docs/api-meta/deprecated-api-list-by-plugin title: Deprecated API usage by plugin description: A list of deprecated APIs, which plugins are still referencing them, and when they need to be removed by. -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana'] --- @@ -211,16 +211,14 @@ so TS and code-reference navigation might not highlight them. | | Deprecated API | Reference location(s) | Remove By | | ---------------|-----------|-----------| -| | [sync_dashboard_filter_state.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts#:~:text=syncQueryStateWithUrl), [sync_dashboard_filter_state.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts#:~:text=syncQueryStateWithUrl) | - | | | [types.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/data/types.ts#:~:text=fieldFormats), [data_service.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/data/data_service.ts#:~:text=fieldFormats) | - | | | [dashboard_viewport.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx#:~:text=ExitFullScreenButton), [dashboard_viewport.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx#:~:text=ExitFullScreenButton), [dashboard_viewport.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx#:~:text=ExitFullScreenButton) | - | | | [save_modal.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/top_nav/save_modal.tsx#:~:text=SavedObjectSaveModal), [save_modal.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/top_nav/save_modal.tsx#:~:text=SavedObjectSaveModal) | 8.8.0 | -| | [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObject), [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObject), [dashboard_tagging.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts#:~:text=SavedObject), [dashboard_tagging.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts#:~:text=SavedObject) | 8.8.0 | -| | [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObjectClass) | 8.8.0 | +| | [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject) | 8.8.0 | | | [types.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/types.ts#:~:text=onAppLeave), [plugin.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/plugin.tsx#:~:text=onAppLeave) | 8.8.0 | -| | [dashboard_migrations.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts#:~:text=SavedObjectAttributes), [dashboard_migrations.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes), [saved_dashboard_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/common/saved_dashboard_references.ts#:~:text=SavedObjectAttributes), [saved_dashboard_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/common/saved_dashboard_references.ts#:~:text=SavedObjectAttributes)+ 8 more | - | -| | [dashboard_migrations.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts#:~:text=SavedObjectAttributes), [dashboard_migrations.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes), [saved_dashboard_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/common/saved_dashboard_references.ts#:~:text=SavedObjectAttributes), [saved_dashboard_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/common/saved_dashboard_references.ts#:~:text=SavedObjectAttributes)+ 8 more | - | -| | [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations_730.ts#:~:text=warning), [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations_730.ts#:~:text=warning) | 8.8.0 | +| | [load_dashboard_state_from_saved_object.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts#:~:text=SavedObjectAttributes), [load_dashboard_state_from_saved_object.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts#:~:text=SavedObjectAttributes), [migrate_extract_panel_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts#:~:text=SavedObjectAttributes), [migrate_extract_panel_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes)+ 11 more | - | +| | [load_dashboard_state_from_saved_object.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts#:~:text=SavedObjectAttributes), [load_dashboard_state_from_saved_object.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts#:~:text=SavedObjectAttributes), [migrate_extract_panel_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts#:~:text=SavedObjectAttributes), [migrate_extract_panel_references.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry_collection_task.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [dashboard_telemetry.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/dashboard_telemetry.ts#:~:text=SavedObjectAttributes), [find_by_value_embeddables.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts#:~:text=SavedObjectAttributes)+ 11 more | - | +| | [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts#:~:text=warning), [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts#:~:text=warning) | 8.8.0 | @@ -525,7 +523,7 @@ so TS and code-reference navigation might not highlight them. | | Deprecated API | Reference location(s) | Remove By | | ---------------|-----------|-----------| -| | [pack_queries_status_table.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/packs/pack_queries_status_table.tsx#:~:text=indexPatternId), [pack_queries_status_table.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/live_queries/form/pack_queries_status_table.tsx#:~:text=indexPatternId), [use_discover_link.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/common/hooks/use_discover_link.tsx#:~:text=indexPatternId) | - | +| | [pack_queries_status_table.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/packs/pack_queries_status_table.tsx#:~:text=indexPatternId), [view_results_in_discover.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/discover/view_results_in_discover.tsx#:~:text=indexPatternId), [use_discover_link.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/common/hooks/use_discover_link.tsx#:~:text=indexPatternId) | - | | | [empty_state.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/components/empty_state.tsx#:~:text=KibanaPageTemplate), [empty_state.tsx](https://github.com/elastic/kibana/tree/main/x-pack/plugins/osquery/public/components/empty_state.tsx#:~:text=KibanaPageTemplate) | - | diff --git a/api_docs/deprecations_by_team.mdx b/api_docs/deprecations_by_team.mdx index 43aad9198df22..da0e278bffa6c 100644 --- a/api_docs/deprecations_by_team.mdx +++ b/api_docs/deprecations_by_team.mdx @@ -7,7 +7,7 @@ id: kibDevDocsDeprecationsDueByTeam slug: /kibana-dev-docs/api-meta/deprecations-due-by-team title: Deprecated APIs due to be removed, by team description: Lists the teams that are referencing deprecated APIs with a remove by date. -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana'] --- @@ -89,10 +89,9 @@ so TS and code-reference navigation might not highlight them. | | Plugin | Deprecated API | Reference location(s) | Remove By | | --------|-------|-----------|-----------| | dashboard | | [save_modal.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/top_nav/save_modal.tsx#:~:text=SavedObjectSaveModal), [save_modal.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/top_nav/save_modal.tsx#:~:text=SavedObjectSaveModal), [saved_object_save_modal_dashboard.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/presentation_util/public/components/saved_object_save_modal_dashboard.tsx#:~:text=SavedObjectSaveModal), [saved_object_save_modal_dashboard.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/presentation_util/public/components/saved_object_save_modal_dashboard.tsx#:~:text=SavedObjectSaveModal) | 8.8.0 | -| dashboard | | [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [saved_object_loader.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/services/saved_object_loader.ts#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObject), [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObject), [dashboard_tagging.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts#:~:text=SavedObject), [dashboard_tagging.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts#:~:text=SavedObject) | 8.8.0 | -| dashboard | | [saved_dashboard.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts#:~:text=SavedObjectClass) | 8.8.0 | +| dashboard | | [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject), [clone_panel_action.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx#:~:text=SavedObject) | 8.8.0 | | dashboard | | [types.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/types.ts#:~:text=onAppLeave), [plugin.tsx](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/public/plugin.tsx#:~:text=onAppLeave) | 8.8.0 | -| dashboard | | [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations_730.ts#:~:text=warning), [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations_730.ts#:~:text=warning) | 8.8.0 | +| dashboard | | [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts#:~:text=warning), [migrations_730.ts](https://github.com/elastic/kibana/tree/main/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts#:~:text=warning) | 8.8.0 | diff --git a/api_docs/dev_tools.mdx b/api_docs/dev_tools.mdx index ee4b58ad6a39b..b724ab15e695e 100644 --- a/api_docs/dev_tools.mdx +++ b/api_docs/dev_tools.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/devTools title: "devTools" image: https://source.unsplash.com/400x175/?github description: API docs for the devTools plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'devTools'] --- import devToolsObj from './dev_tools.devdocs.json'; diff --git a/api_docs/discover.devdocs.json b/api_docs/discover.devdocs.json index 695319775e984..8c4a6308dd17b 100644 --- a/api_docs/discover.devdocs.json +++ b/api_docs/discover.devdocs.json @@ -346,7 +346,7 @@ }, { "plugin": "osquery", - "path": "x-pack/plugins/osquery/public/live_queries/form/pack_queries_status_table.tsx" + "path": "x-pack/plugins/osquery/public/discover/view_results_in_discover.tsx" }, { "plugin": "osquery", @@ -1101,7 +1101,7 @@ "label": "sharingSavedObjectProps", "description": [], "signature": [ - "{ outcome?: \"exactMatch\" | \"aliasMatch\" | \"conflict\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" + "{ outcome?: \"conflict\" | \"exactMatch\" | \"aliasMatch\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" ], "path": "src/plugins/saved_search/public/services/saved_searches/types.ts", "deprecated": false, diff --git a/api_docs/discover.mdx b/api_docs/discover.mdx index 7cb6b1cef229c..39b2814d4136c 100644 --- a/api_docs/discover.mdx +++ b/api_docs/discover.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/discover title: "discover" image: https://source.unsplash.com/400x175/?github description: API docs for the discover plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'discover'] --- import discoverObj from './discover.devdocs.json'; diff --git a/api_docs/discover_enhanced.mdx b/api_docs/discover_enhanced.mdx index efddbbc3916ec..e9974fbb2bf45 100644 --- a/api_docs/discover_enhanced.mdx +++ b/api_docs/discover_enhanced.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/discoverEnhanced title: "discoverEnhanced" image: https://source.unsplash.com/400x175/?github description: API docs for the discoverEnhanced plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'discoverEnhanced'] --- import discoverEnhancedObj from './discover_enhanced.devdocs.json'; diff --git a/api_docs/embeddable.mdx b/api_docs/embeddable.mdx index eb6a4725d55d1..8bbe0a063796d 100644 --- a/api_docs/embeddable.mdx +++ b/api_docs/embeddable.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/embeddable title: "embeddable" image: https://source.unsplash.com/400x175/?github description: API docs for the embeddable plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'embeddable'] --- import embeddableObj from './embeddable.devdocs.json'; diff --git a/api_docs/embeddable_enhanced.mdx b/api_docs/embeddable_enhanced.mdx index 7318d71853f18..c53b6a4aba7e9 100644 --- a/api_docs/embeddable_enhanced.mdx +++ b/api_docs/embeddable_enhanced.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/embeddableEnhanced title: "embeddableEnhanced" image: https://source.unsplash.com/400x175/?github description: API docs for the embeddableEnhanced plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'embeddableEnhanced'] --- import embeddableEnhancedObj from './embeddable_enhanced.devdocs.json'; diff --git a/api_docs/encrypted_saved_objects.mdx b/api_docs/encrypted_saved_objects.mdx index 3466c99aba602..6cc990a42eba7 100644 --- a/api_docs/encrypted_saved_objects.mdx +++ b/api_docs/encrypted_saved_objects.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/encryptedSavedObjects title: "encryptedSavedObjects" image: https://source.unsplash.com/400x175/?github description: API docs for the encryptedSavedObjects plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'encryptedSavedObjects'] --- import encryptedSavedObjectsObj from './encrypted_saved_objects.devdocs.json'; diff --git a/api_docs/enterprise_search.mdx b/api_docs/enterprise_search.mdx index 8600b14ccd0c7..8f80e15d3886b 100644 --- a/api_docs/enterprise_search.mdx +++ b/api_docs/enterprise_search.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/enterpriseSearch title: "enterpriseSearch" image: https://source.unsplash.com/400x175/?github description: API docs for the enterpriseSearch plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'enterpriseSearch'] --- import enterpriseSearchObj from './enterprise_search.devdocs.json'; diff --git a/api_docs/es_ui_shared.mdx b/api_docs/es_ui_shared.mdx index eaeb120c8aca9..6a4ca6fcb7735 100644 --- a/api_docs/es_ui_shared.mdx +++ b/api_docs/es_ui_shared.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/esUiShared title: "esUiShared" image: https://source.unsplash.com/400x175/?github description: API docs for the esUiShared plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'esUiShared'] --- import esUiSharedObj from './es_ui_shared.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-ma | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 114 | 3 | 110 | 3 | +| 114 | 3 | 110 | 5 | ## Client diff --git a/api_docs/event_annotation.mdx b/api_docs/event_annotation.mdx index d431228998ee4..159a2f7167b0a 100644 --- a/api_docs/event_annotation.mdx +++ b/api_docs/event_annotation.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/eventAnnotation title: "eventAnnotation" image: https://source.unsplash.com/400x175/?github description: API docs for the eventAnnotation plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'eventAnnotation'] --- import eventAnnotationObj from './event_annotation.devdocs.json'; diff --git a/api_docs/event_log.devdocs.json b/api_docs/event_log.devdocs.json index f821ced3a76e0..8361059c91079 100644 --- a/api_docs/event_log.devdocs.json +++ b/api_docs/event_log.devdocs.json @@ -1312,7 +1312,7 @@ "label": "data", "description": [], "signature": [ - "(Readonly<{ error?: Readonly<{ type?: string | undefined; id?: string | undefined; message?: string | undefined; code?: string | undefined; stack_trace?: string | undefined; } & {}> | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; outcome?: string | undefined; created?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}> | undefined)[]" + "(Readonly<{ error?: Readonly<{ type?: string | undefined; id?: string | undefined; message?: string | undefined; code?: string | undefined; stack_trace?: string | undefined; } & {}> | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; total_enrichment_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; created?: string | undefined; outcome?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}> | undefined)[]" ], "path": "x-pack/plugins/event_log/server/es/cluster_client_adapter.ts", "deprecated": false, @@ -1332,7 +1332,7 @@ "label": "IEvent", "description": [], "signature": [ - "DeepPartial | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; outcome?: string | undefined; created?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}>>> | undefined" + "DeepPartial | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; total_enrichment_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; created?: string | undefined; outcome?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}>>> | undefined" ], "path": "x-pack/plugins/event_log/generated/schemas.ts", "deprecated": false, @@ -1347,7 +1347,7 @@ "label": "IValidatedEvent", "description": [], "signature": [ - "Readonly<{ error?: Readonly<{ type?: string | undefined; id?: string | undefined; message?: string | undefined; code?: string | undefined; stack_trace?: string | undefined; } & {}> | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; outcome?: string | undefined; created?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}> | undefined" + "Readonly<{ error?: Readonly<{ type?: string | undefined; id?: string | undefined; message?: string | undefined; code?: string | undefined; stack_trace?: string | undefined; } & {}> | undefined; tags?: string[] | undefined; log?: Readonly<{ logger?: string | undefined; level?: string | undefined; } & {}> | undefined; user?: Readonly<{ name?: string | undefined; } & {}> | undefined; message?: string | undefined; kibana?: Readonly<{ alert?: Readonly<{ rule?: Readonly<{ consumer?: string | undefined; execution?: Readonly<{ status?: string | undefined; metrics?: Readonly<{ number_of_triggered_actions?: string | number | undefined; number_of_generated_actions?: string | number | undefined; alert_counts?: Readonly<{ recovered?: string | number | undefined; active?: string | number | undefined; new?: string | number | undefined; } & {}> | undefined; number_of_searches?: string | number | undefined; total_indexing_duration_ms?: string | number | undefined; es_search_duration_ms?: string | number | undefined; total_search_duration_ms?: string | number | undefined; execution_gap_duration_s?: string | number | undefined; rule_type_run_duration_ms?: string | number | undefined; process_alerts_duration_ms?: string | number | undefined; trigger_actions_duration_ms?: string | number | undefined; process_rule_duration_ms?: string | number | undefined; claim_to_start_duration_ms?: string | number | undefined; prepare_rule_duration_ms?: string | number | undefined; total_run_duration_ms?: string | number | undefined; total_enrichment_duration_ms?: string | number | undefined; } & {}> | undefined; uuid?: string | undefined; status_order?: string | number | undefined; } & {}> | undefined; rule_type_id?: string | undefined; } & {}> | undefined; } & {}> | undefined; version?: string | undefined; alerting?: Readonly<{ status?: string | undefined; instance_id?: string | undefined; action_group_id?: string | undefined; action_subgroup?: string | undefined; } & {}> | undefined; server_uuid?: string | undefined; task?: Readonly<{ id?: string | undefined; schedule_delay?: string | number | undefined; scheduled?: string | undefined; } & {}> | undefined; saved_objects?: Readonly<{ type?: string | undefined; id?: string | undefined; namespace?: string | undefined; rel?: string | undefined; type_id?: string | undefined; } & {}>[] | undefined; space_ids?: string[] | undefined; } & {}> | undefined; ecs?: Readonly<{ version?: string | undefined; } & {}> | undefined; rule?: Readonly<{ name?: string | undefined; description?: string | undefined; category?: string | undefined; id?: string | undefined; version?: string | undefined; license?: string | undefined; reference?: string | undefined; author?: string[] | undefined; ruleset?: string | undefined; uuid?: string | undefined; } & {}> | undefined; event?: Readonly<{ start?: string | undefined; category?: string[] | undefined; type?: string[] | undefined; id?: string | undefined; created?: string | undefined; outcome?: string | undefined; end?: string | undefined; original?: string | undefined; duration?: string | number | undefined; code?: string | undefined; url?: string | undefined; action?: string | undefined; kind?: string | undefined; hash?: string | undefined; severity?: string | number | undefined; dataset?: string | undefined; ingested?: string | undefined; module?: string | undefined; provider?: string | undefined; reason?: string | undefined; reference?: string | undefined; risk_score?: number | undefined; risk_score_norm?: number | undefined; sequence?: string | number | undefined; timezone?: string | undefined; } & {}> | undefined; '@timestamp'?: string | undefined; } & {}> | undefined" ], "path": "x-pack/plugins/event_log/generated/schemas.ts", "deprecated": false, diff --git a/api_docs/event_log.mdx b/api_docs/event_log.mdx index 3b14ac3b38cdf..b9be569d3a3e9 100644 --- a/api_docs/event_log.mdx +++ b/api_docs/event_log.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/eventLog title: "eventLog" image: https://source.unsplash.com/400x175/?github description: API docs for the eventLog plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'eventLog'] --- import eventLogObj from './event_log.devdocs.json'; diff --git a/api_docs/expression_error.mdx b/api_docs/expression_error.mdx index e28ca58c98d8a..6d9a8d244589a 100644 --- a/api_docs/expression_error.mdx +++ b/api_docs/expression_error.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionError title: "expressionError" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionError plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionError'] --- import expressionErrorObj from './expression_error.devdocs.json'; diff --git a/api_docs/expression_gauge.mdx b/api_docs/expression_gauge.mdx index 9ed9d2a67bfd7..b38b786ca55b9 100644 --- a/api_docs/expression_gauge.mdx +++ b/api_docs/expression_gauge.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionGauge title: "expressionGauge" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionGauge plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionGauge'] --- import expressionGaugeObj from './expression_gauge.devdocs.json'; diff --git a/api_docs/expression_heatmap.mdx b/api_docs/expression_heatmap.mdx index 62f645598cc3e..9d856b882a318 100644 --- a/api_docs/expression_heatmap.mdx +++ b/api_docs/expression_heatmap.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionHeatmap title: "expressionHeatmap" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionHeatmap plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionHeatmap'] --- import expressionHeatmapObj from './expression_heatmap.devdocs.json'; diff --git a/api_docs/expression_image.mdx b/api_docs/expression_image.mdx index e14697578e3a5..84225e80ad009 100644 --- a/api_docs/expression_image.mdx +++ b/api_docs/expression_image.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionImage title: "expressionImage" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionImage plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionImage'] --- import expressionImageObj from './expression_image.devdocs.json'; diff --git a/api_docs/expression_legacy_metric_vis.mdx b/api_docs/expression_legacy_metric_vis.mdx index 967f0e15bde38..e6902356f091e 100644 --- a/api_docs/expression_legacy_metric_vis.mdx +++ b/api_docs/expression_legacy_metric_vis.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionLegacyMetricVis title: "expressionLegacyMetricVis" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionLegacyMetricVis plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionLegacyMetricVis'] --- import expressionLegacyMetricVisObj from './expression_legacy_metric_vis.devdocs.json'; diff --git a/api_docs/expression_metric.mdx b/api_docs/expression_metric.mdx index 333cbcb1f5890..60a4d843aad34 100644 --- a/api_docs/expression_metric.mdx +++ b/api_docs/expression_metric.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionMetric title: "expressionMetric" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionMetric plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionMetric'] --- import expressionMetricObj from './expression_metric.devdocs.json'; diff --git a/api_docs/expression_metric_vis.mdx b/api_docs/expression_metric_vis.mdx index f2b118c99a7b4..85c6421d292d1 100644 --- a/api_docs/expression_metric_vis.mdx +++ b/api_docs/expression_metric_vis.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionMetricVis title: "expressionMetricVis" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionMetricVis plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionMetricVis'] --- import expressionMetricVisObj from './expression_metric_vis.devdocs.json'; diff --git a/api_docs/expression_partition_vis.mdx b/api_docs/expression_partition_vis.mdx index 7e900092940cb..4d4a23fe3a6ff 100644 --- a/api_docs/expression_partition_vis.mdx +++ b/api_docs/expression_partition_vis.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionPartitionVis title: "expressionPartitionVis" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionPartitionVis plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionPartitionVis'] --- import expressionPartitionVisObj from './expression_partition_vis.devdocs.json'; diff --git a/api_docs/expression_repeat_image.mdx b/api_docs/expression_repeat_image.mdx index 19427e2c1e8af..ff4af965c963e 100644 --- a/api_docs/expression_repeat_image.mdx +++ b/api_docs/expression_repeat_image.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionRepeatImage title: "expressionRepeatImage" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionRepeatImage plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionRepeatImage'] --- import expressionRepeatImageObj from './expression_repeat_image.devdocs.json'; diff --git a/api_docs/expression_reveal_image.mdx b/api_docs/expression_reveal_image.mdx index 6d7c6e6c85cd5..2d3ede34cf142 100644 --- a/api_docs/expression_reveal_image.mdx +++ b/api_docs/expression_reveal_image.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionRevealImage title: "expressionRevealImage" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionRevealImage plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionRevealImage'] --- import expressionRevealImageObj from './expression_reveal_image.devdocs.json'; diff --git a/api_docs/expression_shape.mdx b/api_docs/expression_shape.mdx index e54835f28d762..114bb08462720 100644 --- a/api_docs/expression_shape.mdx +++ b/api_docs/expression_shape.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionShape title: "expressionShape" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionShape plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionShape'] --- import expressionShapeObj from './expression_shape.devdocs.json'; diff --git a/api_docs/expression_tagcloud.mdx b/api_docs/expression_tagcloud.mdx index 5b5b9430f6023..6a87768ff01e5 100644 --- a/api_docs/expression_tagcloud.mdx +++ b/api_docs/expression_tagcloud.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionTagcloud title: "expressionTagcloud" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionTagcloud plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionTagcloud'] --- import expressionTagcloudObj from './expression_tagcloud.devdocs.json'; diff --git a/api_docs/expression_x_y.mdx b/api_docs/expression_x_y.mdx index bbf844476905b..bf0c8f9c49aea 100644 --- a/api_docs/expression_x_y.mdx +++ b/api_docs/expression_x_y.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressionXY title: "expressionXY" image: https://source.unsplash.com/400x175/?github description: API docs for the expressionXY plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressionXY'] --- import expressionXYObj from './expression_x_y.devdocs.json'; diff --git a/api_docs/expressions.devdocs.json b/api_docs/expressions.devdocs.json index cf0d00e1dd478..bae5e63702f4f 100644 --- a/api_docs/expressions.devdocs.json +++ b/api_docs/expressions.devdocs.json @@ -11507,7 +11507,7 @@ "\nThis type represents the `type` of any `DatatableColumn` in a `Datatable`.\nits duplicated from KBN_FIELD_TYPES" ], "signature": [ - "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"conflict\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"histogram\"" + "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"conflict\" | \"histogram\"" ], "path": "src/plugins/expressions/common/expression_types/specs/datatable.ts", "deprecated": false, @@ -21037,7 +21037,7 @@ "\nThis type represents the `type` of any `DatatableColumn` in a `Datatable`.\nits duplicated from KBN_FIELD_TYPES" ], "signature": [ - "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"conflict\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"histogram\"" + "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"conflict\" | \"histogram\"" ], "path": "src/plugins/expressions/common/expression_types/specs/datatable.ts", "deprecated": false, @@ -29210,7 +29210,7 @@ "label": "type", "description": [], "signature": [ - "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"conflict\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"histogram\"" + "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"conflict\" | \"histogram\"" ], "path": "src/plugins/expressions/common/expression_types/specs/datatable.ts", "deprecated": false, @@ -35226,7 +35226,7 @@ "\nThis type represents the `type` of any `DatatableColumn` in a `Datatable`.\nits duplicated from KBN_FIELD_TYPES" ], "signature": [ - "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"conflict\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"histogram\"" + "\"string\" | \"number\" | \"boolean\" | \"object\" | \"date\" | \"null\" | \"ip\" | \"nested\" | \"_source\" | \"attachment\" | \"geo_point\" | \"geo_shape\" | \"murmur3\" | \"unknown\" | \"conflict\" | \"histogram\"" ], "path": "src/plugins/expressions/common/expression_types/specs/datatable.ts", "deprecated": false, diff --git a/api_docs/expressions.mdx b/api_docs/expressions.mdx index 4fadad12b2dea..cb5617b237f7a 100644 --- a/api_docs/expressions.mdx +++ b/api_docs/expressions.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/expressions title: "expressions" image: https://source.unsplash.com/400x175/?github description: API docs for the expressions plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'expressions'] --- import expressionsObj from './expressions.devdocs.json'; diff --git a/api_docs/features.mdx b/api_docs/features.mdx index 972eaff242d68..1c1d57aa91eb1 100644 --- a/api_docs/features.mdx +++ b/api_docs/features.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/features title: "features" image: https://source.unsplash.com/400x175/?github description: API docs for the features plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'features'] --- import featuresObj from './features.devdocs.json'; diff --git a/api_docs/field_formats.mdx b/api_docs/field_formats.mdx index 0225740e0976c..dc89d286ddfe5 100644 --- a/api_docs/field_formats.mdx +++ b/api_docs/field_formats.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/fieldFormats title: "fieldFormats" image: https://source.unsplash.com/400x175/?github description: API docs for the fieldFormats plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'fieldFormats'] --- import fieldFormatsObj from './field_formats.devdocs.json'; diff --git a/api_docs/file_upload.mdx b/api_docs/file_upload.mdx index 5a7a187da833f..f29f32174d128 100644 --- a/api_docs/file_upload.mdx +++ b/api_docs/file_upload.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/fileUpload title: "fileUpload" image: https://source.unsplash.com/400x175/?github description: API docs for the fileUpload plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'fileUpload'] --- import fileUploadObj from './file_upload.devdocs.json'; diff --git a/api_docs/files.devdocs.json b/api_docs/files.devdocs.json index 358859310c797..7c94fcdac9025 100644 --- a/api_docs/files.devdocs.json +++ b/api_docs/files.devdocs.json @@ -438,10 +438,10 @@ "tags": [], "label": "getDownloadHref", "description": [ - "\nGet a string for downloading a file that can be passed to a button element's\nhref for download." + "\nGet a string for downloading a file that can be passed to a button element's\nhref for download.\n" ], "signature": [ - "(file: ", + "(args: Pick<", { "pluginId": "files", "scope": "common", @@ -449,7 +449,7 @@ "section": "def-common.FileJSON", "text": "FileJSON" }, - ") => string" + ", \"id\" | \"fileKind\">) => string" ], "path": "x-pack/plugins/files/public/types.ts", "deprecated": false, @@ -460,9 +460,12 @@ "id": "def-public.FilesClient.getDownloadHref.$1", "type": "Object", "tags": [], - "label": "file", - "description": [], + "label": "args", + "description": [ + "- get download URL args" + ], "signature": [ + "Pick<", { "pluginId": "files", "scope": "common", @@ -470,7 +473,7 @@ "section": "def-common.FileJSON", "text": "FileJSON" }, - "" + ", \"id\" | \"fileKind\">" ], "path": "x-pack/plugins/files/public/types.ts", "deprecated": false, @@ -1129,7 +1132,7 @@ "section": "def-common.FileJSON", "text": "FileJSON" }, - "; }>; upload: (arg: Omit & Readonly<{ selfDestructOnAbort?: boolean | undefined; } & {}> & { body: unknown; kind: string; abortSignal?: AbortSignal | undefined; contentType?: string | undefined; }, \"kind\">) => Promise<{ ok: true; size: number; }>; download: (arg: Omit & { kind: string; }, \"kind\">) => Promise; getDownloadHref: (arg: Omit<", + "; }>; upload: (arg: Omit & Readonly<{ selfDestructOnAbort?: boolean | undefined; } & {}> & { body: unknown; kind: string; abortSignal?: AbortSignal | undefined; contentType?: string | undefined; }, \"kind\">) => Promise<{ ok: true; size: number; }>; download: (arg: Omit & { kind: string; }, \"kind\">) => Promise; getDownloadHref: (arg: Omit, \"kind\">) => string; share: (arg: Omit & Readonly<{} & { fileId: string; }> & { kind: string; }, \"kind\">) => Promise<", + ", \"id\" | \"fileKind\">, \"kind\">) => string; share: (arg: Omit & Readonly<{} & { fileId: string; }> & { kind: string; }, \"kind\">) => Promise<", { "pluginId": "files", "scope": "common", diff --git a/api_docs/files.mdx b/api_docs/files.mdx index 88478910d3bdb..3cc10c4a1612a 100644 --- a/api_docs/files.mdx +++ b/api_docs/files.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/files title: "files" image: https://source.unsplash.com/400x175/?github description: API docs for the files plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'files'] --- import filesObj from './files.devdocs.json'; @@ -21,7 +21,7 @@ Contact [@elastic/kibana-app-services](https://github.com/orgs/elastic/teams/tea | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 263 | 0 | 15 | 2 | +| 263 | 0 | 14 | 2 | ## Client diff --git a/api_docs/fleet.devdocs.json b/api_docs/fleet.devdocs.json index 66f288b6ca432..3059a8f9c9f84 100644 --- a/api_docs/fleet.devdocs.json +++ b/api_docs/fleet.devdocs.json @@ -1225,6 +1225,146 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtension", + "type": "Interface", + "tags": [], + "label": "PackagePolicyCreateMultiStepExtension", + "description": [ + "Extension point registration contract for Integration Policy Create views in multi-step onboarding" + ], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtension.package", + "type": "string", + "tags": [], + "label": "package", + "description": [], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtension.view", + "type": "string", + "tags": [], + "label": "view", + "description": [], + "signature": [ + "\"package-policy-create-multi-step\"" + ], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtension.Component", + "type": "Function", + "tags": [], + "label": "Component", + "description": [], + "signature": [ + "React.ExoticComponent<(", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtensionComponentProps", + "text": "PackagePolicyCreateMultiStepExtensionComponentProps" + }, + " & React.RefAttributes>) | (", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtensionComponentProps", + "text": "PackagePolicyCreateMultiStepExtensionComponentProps" + }, + " & { children?: React.ReactNode; })> & { readonly _result: ", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtensionComponent", + "text": "PackagePolicyCreateMultiStepExtensionComponent" + }, + "; }" + ], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtension.Component.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtensionComponentProps", + "type": "Interface", + "tags": [], + "label": "PackagePolicyCreateMultiStepExtensionComponentProps", + "description": [], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "fleet", + "id": "def-public.PackagePolicyCreateMultiStepExtensionComponentProps.newPolicy", + "type": "Object", + "tags": [], + "label": "newPolicy", + "description": [ + "The integration policy being created" + ], + "signature": [ + { + "pluginId": "fleet", + "scope": "common", + "docId": "kibFleetPluginApi", + "section": "def-common.NewPackagePolicy", + "text": "NewPackagePolicy" + } + ], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "fleet", "id": "def-public.PackagePolicyEditExtension", @@ -1925,10 +2065,10 @@ "id": "def-public.UIExtensionsStorage.Unnamed", "type": "IndexSignature", "tags": [], - "label": "[key: string]: Partial>", + "label": "[key: string]: Partial>", "description": [], "signature": [ - "[key: string]: Partial | React.FunctionComponent<", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtensionComponentProps", + "text": "PackagePolicyCreateMultiStepExtensionComponentProps" + }, + ">" + ], + "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "fleet", "id": "def-public.PackagePolicyEditExtensionComponent", @@ -2269,6 +2442,14 @@ "docId": "kibFleetPluginApi", "section": "def-public.AgentEnrollmentFlyoutFinalStepExtension", "text": "AgentEnrollmentFlyoutFinalStepExtension" + }, + " | ", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtension", + "text": "PackagePolicyCreateMultiStepExtension" } ], "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", @@ -2365,6 +2546,14 @@ "docId": "kibFleetPluginApi", "section": "def-public.AgentEnrollmentFlyoutFinalStepExtension", "text": "AgentEnrollmentFlyoutFinalStepExtension" + }, + " | ", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtension", + "text": "PackagePolicyCreateMultiStepExtension" } ], "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", @@ -3725,6 +3914,14 @@ "docId": "kibFleetPluginApi", "section": "def-public.AgentEnrollmentFlyoutFinalStepExtension", "text": "AgentEnrollmentFlyoutFinalStepExtension" + }, + " | ", + { + "pluginId": "fleet", + "scope": "public", + "docId": "kibFleetPluginApi", + "section": "def-public.PackagePolicyCreateMultiStepExtension", + "text": "PackagePolicyCreateMultiStepExtension" } ], "path": "x-pack/plugins/fleet/public/types/ui_extensions.ts", @@ -6227,7 +6424,7 @@ "section": "def-common.AuthenticatedUser", "text": "AuthenticatedUser" }, - " | undefined; force?: boolean | undefined; } | undefined, currentVersion?: string | undefined) => Promise<", + " | undefined; force?: boolean | undefined; skipUniqueNameVerification?: boolean | undefined; } | undefined, currentVersion?: string | undefined) => Promise<", { "pluginId": "fleet", "scope": "common", @@ -6352,6 +6549,20 @@ "path": "x-pack/plugins/fleet/server/services/package_policy_service.ts", "deprecated": false, "trackAdoption": false + }, + { + "parentPluginId": "fleet", + "id": "def-server.PackagePolicyClient.update.$5.skipUniqueNameVerification", + "type": "CompoundType", + "tags": [], + "label": "skipUniqueNameVerification", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/fleet/server/services/package_policy_service.ts", + "deprecated": false, + "trackAdoption": false } ] }, @@ -6959,13 +7170,7 @@ "text": "NewPackagePolicy" }, ", context: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ", request: ", "KibanaRequest", ") => Promise) => Promise<", @@ -7400,13 +7593,7 @@ "label": "context", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - } + "RequestHandlerContext" ], "path": "x-pack/plugins/fleet/server/types/extensions.ts", "deprecated": false, @@ -7498,13 +7685,7 @@ "text": "PackagePolicy" }, ", context: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ", request: ", "KibanaRequest", ") => Promise<", @@ -7550,13 +7731,7 @@ "label": "context", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - } + "RequestHandlerContext" ], "path": "x-pack/plugins/fleet/server/types/extensions.ts", "deprecated": false, @@ -7597,13 +7772,7 @@ "text": "UpdatePackagePolicy" }, ", context: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", ", request: ", "KibanaRequest", ") => Promise<", @@ -7649,13 +7818,7 @@ "label": "context", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - } + "RequestHandlerContext" ], "path": "x-pack/plugins/fleet/server/types/extensions.ts", "deprecated": false, @@ -9086,6 +9249,20 @@ "path": "x-pack/plugins/fleet/common/authz.ts", "deprecated": false, "trackAdoption": false + }, + { + "parentPluginId": "fleet", + "id": "def-common.FleetAuthz.packagePrivileges", + "type": "Object", + "tags": [], + "label": "packagePrivileges", + "description": [], + "signature": [ + "{ [packageName: string]: { actions: { [key: string]: { executePackageAction: boolean; }; }; }; } | undefined" + ], + "path": "x-pack/plugins/fleet/common/authz.ts", + "deprecated": false, + "trackAdoption": false } ], "initialIsOpen": false @@ -9262,14 +9439,14 @@ { "parentPluginId": "fleet", "id": "def-common.FleetServerAgent.upgraded_at", - "type": "string", + "type": "CompoundType", "tags": [], "label": "upgraded_at", "description": [ "\nDate/time the Elastic Agent was last upgraded" ], "signature": [ - "string | undefined" + "string | null | undefined" ], "path": "x-pack/plugins/fleet/common/types/models/agent.ts", "deprecated": false, @@ -9291,22 +9468,6 @@ "deprecated": false, "trackAdoption": false }, - { - "parentPluginId": "fleet", - "id": "def-common.FleetServerAgent.upgrade_status", - "type": "CompoundType", - "tags": [], - "label": "upgrade_status", - "description": [ - "\nUpgrade status" - ], - "signature": [ - "\"completed\" | \"started\" | undefined" - ], - "path": "x-pack/plugins/fleet/common/types/models/agent.ts", - "deprecated": false, - "trackAdoption": false - }, { "parentPluginId": "fleet", "id": "def-common.FleetServerAgent.access_api_key_id", @@ -15083,7 +15244,7 @@ "label": "PackageSpecCategory", "description": [], "signature": [ - "\"custom\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\"" + "\"custom\" | \"aws\" | \"azure\" | \"cloud\" | \"config_management\" | \"containers\" | \"crm\" | \"datastore\" | \"elastic_stack\" | \"google_cloud\" | \"infrastructure\" | \"kubernetes\" | \"languages\" | \"message_queue\" | \"monitoring\" | \"network\" | \"notification\" | \"os_system\" | \"productivity\" | \"security\" | \"support\" | \"threat_intel\" | \"ticketing\" | \"version_control\" | \"web\"" ], "path": "x-pack/plugins/fleet/common/types/models/package_spec.ts", "deprecated": false, @@ -16517,6 +16678,21 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "fleet", + "id": "def-common.ENDPOINT_PRIVILEGES", + "type": "Object", + "tags": [], + "label": "ENDPOINT_PRIVILEGES", + "description": [], + "signature": [ + "readonly [\"writeEndpointList\", \"readEndpointList\", \"writeTrustedApplications\", \"readTrustedApplications\", \"writeHostIsolationExceptions\", \"readHostIsolationExceptions\", \"writeBlocklist\", \"readBlocklist\", \"writeEventFilters\", \"readEventFilters\", \"writePolicyManagement\", \"readPolicyManagement\", \"writeActionsLogManagement\", \"readActionsLogManagement\", \"writeHostIsolation\", \"writeProcessOperations\", \"writeFileOperations\"]" + ], + "path": "x-pack/plugins/fleet/common/constants/authz.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "fleet", "id": "def-common.EPM_API_ROUTES", diff --git a/api_docs/fleet.mdx b/api_docs/fleet.mdx index 16f908b5a6559..7c5beab0d5c9d 100644 --- a/api_docs/fleet.mdx +++ b/api_docs/fleet.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/fleet title: "fleet" image: https://source.unsplash.com/400x175/?github description: API docs for the fleet plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'fleet'] --- import fleetObj from './fleet.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Fleet](https://github.com/orgs/elastic/teams/fleet) for questions regar | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 986 | 3 | 886 | 17 | +| 996 | 3 | 893 | 17 | ## Client diff --git a/api_docs/global_search.mdx b/api_docs/global_search.mdx index df42a342ea190..6803fa9d095e6 100644 --- a/api_docs/global_search.mdx +++ b/api_docs/global_search.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/globalSearch title: "globalSearch" image: https://source.unsplash.com/400x175/?github description: API docs for the globalSearch plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'globalSearch'] --- import globalSearchObj from './global_search.devdocs.json'; diff --git a/api_docs/guided_onboarding.mdx b/api_docs/guided_onboarding.mdx index 7036c153af9c9..062ffb1effb3c 100644 --- a/api_docs/guided_onboarding.mdx +++ b/api_docs/guided_onboarding.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/guidedOnboarding title: "guidedOnboarding" image: https://source.unsplash.com/400x175/?github description: API docs for the guidedOnboarding plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'guidedOnboarding'] --- import guidedOnboardingObj from './guided_onboarding.devdocs.json'; diff --git a/api_docs/home.mdx b/api_docs/home.mdx index ea551b71ca3cc..8f772016026cb 100644 --- a/api_docs/home.mdx +++ b/api_docs/home.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/home title: "home" image: https://source.unsplash.com/400x175/?github description: API docs for the home plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'home'] --- import homeObj from './home.devdocs.json'; diff --git a/api_docs/index_lifecycle_management.mdx b/api_docs/index_lifecycle_management.mdx index cb31945f45c53..29de31f6cf689 100644 --- a/api_docs/index_lifecycle_management.mdx +++ b/api_docs/index_lifecycle_management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/indexLifecycleManagement title: "indexLifecycleManagement" image: https://source.unsplash.com/400x175/?github description: API docs for the indexLifecycleManagement plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'indexLifecycleManagement'] --- import indexLifecycleManagementObj from './index_lifecycle_management.devdocs.json'; diff --git a/api_docs/index_management.mdx b/api_docs/index_management.mdx index 500587900e2a9..3dac89fa09d7f 100644 --- a/api_docs/index_management.mdx +++ b/api_docs/index_management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/indexManagement title: "indexManagement" image: https://source.unsplash.com/400x175/?github description: API docs for the indexManagement plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'indexManagement'] --- import indexManagementObj from './index_management.devdocs.json'; diff --git a/api_docs/infra.mdx b/api_docs/infra.mdx index 60945a0fa95fe..315978011a0b4 100644 --- a/api_docs/infra.mdx +++ b/api_docs/infra.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/infra title: "infra" image: https://source.unsplash.com/400x175/?github description: API docs for the infra plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'infra'] --- import infraObj from './infra.devdocs.json'; diff --git a/api_docs/inspector.mdx b/api_docs/inspector.mdx index 0a17336a71a73..1eec7a67db10b 100644 --- a/api_docs/inspector.mdx +++ b/api_docs/inspector.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/inspector title: "inspector" image: https://source.unsplash.com/400x175/?github description: API docs for the inspector plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'inspector'] --- import inspectorObj from './inspector.devdocs.json'; diff --git a/api_docs/interactive_setup.mdx b/api_docs/interactive_setup.mdx index 5de6f23e953e9..ba3797cab67d7 100644 --- a/api_docs/interactive_setup.mdx +++ b/api_docs/interactive_setup.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/interactiveSetup title: "interactiveSetup" image: https://source.unsplash.com/400x175/?github description: API docs for the interactiveSetup plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'interactiveSetup'] --- import interactiveSetupObj from './interactive_setup.devdocs.json'; diff --git a/api_docs/kbn_ace.mdx b/api_docs/kbn_ace.mdx index 6b9ee23b0ad29..c6dcd6bde7831 100644 --- a/api_docs/kbn_ace.mdx +++ b/api_docs/kbn_ace.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ace title: "@kbn/ace" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ace plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ace'] --- import kbnAceObj from './kbn_ace.devdocs.json'; diff --git a/api_docs/kbn_aiops_components.mdx b/api_docs/kbn_aiops_components.mdx index 448c51ad25606..78c88adbe04a1 100644 --- a/api_docs/kbn_aiops_components.mdx +++ b/api_docs/kbn_aiops_components.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-aiops-components title: "@kbn/aiops-components" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/aiops-components plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/aiops-components'] --- import kbnAiopsComponentsObj from './kbn_aiops_components.devdocs.json'; diff --git a/api_docs/kbn_aiops_utils.mdx b/api_docs/kbn_aiops_utils.mdx index 9ef8150e1696a..8e0003a6394ae 100644 --- a/api_docs/kbn_aiops_utils.mdx +++ b/api_docs/kbn_aiops_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-aiops-utils title: "@kbn/aiops-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/aiops-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/aiops-utils'] --- import kbnAiopsUtilsObj from './kbn_aiops_utils.devdocs.json'; diff --git a/api_docs/kbn_alerts.mdx b/api_docs/kbn_alerts.mdx index 7c1ea2975b24e..b936fa218da1b 100644 --- a/api_docs/kbn_alerts.mdx +++ b/api_docs/kbn_alerts.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-alerts title: "@kbn/alerts" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/alerts plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/alerts'] --- import kbnAlertsObj from './kbn_alerts.devdocs.json'; diff --git a/api_docs/kbn_analytics.mdx b/api_docs/kbn_analytics.mdx index f704647f7e7e3..480d1389d1d53 100644 --- a/api_docs/kbn_analytics.mdx +++ b/api_docs/kbn_analytics.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics title: "@kbn/analytics" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics'] --- import kbnAnalyticsObj from './kbn_analytics.devdocs.json'; diff --git a/api_docs/kbn_analytics_client.mdx b/api_docs/kbn_analytics_client.mdx index b088520ed67c6..67d5f65e938ae 100644 --- a/api_docs/kbn_analytics_client.mdx +++ b/api_docs/kbn_analytics_client.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics-client title: "@kbn/analytics-client" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics-client plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics-client'] --- import kbnAnalyticsClientObj from './kbn_analytics_client.devdocs.json'; diff --git a/api_docs/kbn_analytics_shippers_elastic_v3_browser.mdx b/api_docs/kbn_analytics_shippers_elastic_v3_browser.mdx index 6b61b9bf71499..2c75bd5664b65 100644 --- a/api_docs/kbn_analytics_shippers_elastic_v3_browser.mdx +++ b/api_docs/kbn_analytics_shippers_elastic_v3_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics-shippers-elastic-v3-browser title: "@kbn/analytics-shippers-elastic-v3-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics-shippers-elastic-v3-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics-shippers-elastic-v3-browser'] --- import kbnAnalyticsShippersElasticV3BrowserObj from './kbn_analytics_shippers_elastic_v3_browser.devdocs.json'; diff --git a/api_docs/kbn_analytics_shippers_elastic_v3_common.mdx b/api_docs/kbn_analytics_shippers_elastic_v3_common.mdx index 78d07f946255c..af39931531e69 100644 --- a/api_docs/kbn_analytics_shippers_elastic_v3_common.mdx +++ b/api_docs/kbn_analytics_shippers_elastic_v3_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics-shippers-elastic-v3-common title: "@kbn/analytics-shippers-elastic-v3-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics-shippers-elastic-v3-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics-shippers-elastic-v3-common'] --- import kbnAnalyticsShippersElasticV3CommonObj from './kbn_analytics_shippers_elastic_v3_common.devdocs.json'; diff --git a/api_docs/kbn_analytics_shippers_elastic_v3_server.mdx b/api_docs/kbn_analytics_shippers_elastic_v3_server.mdx index e5db75837a62f..5515fe767880f 100644 --- a/api_docs/kbn_analytics_shippers_elastic_v3_server.mdx +++ b/api_docs/kbn_analytics_shippers_elastic_v3_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics-shippers-elastic-v3-server title: "@kbn/analytics-shippers-elastic-v3-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics-shippers-elastic-v3-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics-shippers-elastic-v3-server'] --- import kbnAnalyticsShippersElasticV3ServerObj from './kbn_analytics_shippers_elastic_v3_server.devdocs.json'; diff --git a/api_docs/kbn_analytics_shippers_fullstory.mdx b/api_docs/kbn_analytics_shippers_fullstory.mdx index 90382d27113c7..d857977462103 100644 --- a/api_docs/kbn_analytics_shippers_fullstory.mdx +++ b/api_docs/kbn_analytics_shippers_fullstory.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-analytics-shippers-fullstory title: "@kbn/analytics-shippers-fullstory" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/analytics-shippers-fullstory plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/analytics-shippers-fullstory'] --- import kbnAnalyticsShippersFullstoryObj from './kbn_analytics_shippers_fullstory.devdocs.json'; diff --git a/api_docs/kbn_apm_config_loader.mdx b/api_docs/kbn_apm_config_loader.mdx index 73d11b590be67..ec16bbb3798aa 100644 --- a/api_docs/kbn_apm_config_loader.mdx +++ b/api_docs/kbn_apm_config_loader.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-apm-config-loader title: "@kbn/apm-config-loader" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/apm-config-loader plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/apm-config-loader'] --- import kbnApmConfigLoaderObj from './kbn_apm_config_loader.devdocs.json'; diff --git a/api_docs/kbn_apm_synthtrace.mdx b/api_docs/kbn_apm_synthtrace.mdx index 1c3531004269a..cd86d11a33dc4 100644 --- a/api_docs/kbn_apm_synthtrace.mdx +++ b/api_docs/kbn_apm_synthtrace.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-apm-synthtrace title: "@kbn/apm-synthtrace" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/apm-synthtrace plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/apm-synthtrace'] --- import kbnApmSynthtraceObj from './kbn_apm_synthtrace.devdocs.json'; diff --git a/api_docs/kbn_apm_utils.mdx b/api_docs/kbn_apm_utils.mdx index 3711e212e5708..24e76f781315f 100644 --- a/api_docs/kbn_apm_utils.mdx +++ b/api_docs/kbn_apm_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-apm-utils title: "@kbn/apm-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/apm-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/apm-utils'] --- import kbnApmUtilsObj from './kbn_apm_utils.devdocs.json'; diff --git a/api_docs/kbn_axe_config.mdx b/api_docs/kbn_axe_config.mdx index 48eec0e7ae00b..a38a76d26da3c 100644 --- a/api_docs/kbn_axe_config.mdx +++ b/api_docs/kbn_axe_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-axe-config title: "@kbn/axe-config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/axe-config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/axe-config'] --- import kbnAxeConfigObj from './kbn_axe_config.devdocs.json'; diff --git a/api_docs/kbn_chart_icons.mdx b/api_docs/kbn_chart_icons.mdx index 8da4d01493b55..96f35a5ca85a3 100644 --- a/api_docs/kbn_chart_icons.mdx +++ b/api_docs/kbn_chart_icons.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-chart-icons title: "@kbn/chart-icons" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/chart-icons plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/chart-icons'] --- import kbnChartIconsObj from './kbn_chart_icons.devdocs.json'; diff --git a/api_docs/kbn_ci_stats_core.mdx b/api_docs/kbn_ci_stats_core.mdx index 4d3ed1b971d81..efc5f97cca9fe 100644 --- a/api_docs/kbn_ci_stats_core.mdx +++ b/api_docs/kbn_ci_stats_core.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ci-stats-core title: "@kbn/ci-stats-core" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ci-stats-core plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ci-stats-core'] --- import kbnCiStatsCoreObj from './kbn_ci_stats_core.devdocs.json'; diff --git a/api_docs/kbn_ci_stats_performance_metrics.mdx b/api_docs/kbn_ci_stats_performance_metrics.mdx index 3383ae0297690..7030b63abaa14 100644 --- a/api_docs/kbn_ci_stats_performance_metrics.mdx +++ b/api_docs/kbn_ci_stats_performance_metrics.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ci-stats-performance-metrics title: "@kbn/ci-stats-performance-metrics" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ci-stats-performance-metrics plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ci-stats-performance-metrics'] --- import kbnCiStatsPerformanceMetricsObj from './kbn_ci_stats_performance_metrics.devdocs.json'; diff --git a/api_docs/kbn_ci_stats_reporter.devdocs.json b/api_docs/kbn_ci_stats_reporter.devdocs.json index f831ac502a939..18389c93d07ca 100644 --- a/api_docs/kbn_ci_stats_reporter.devdocs.json +++ b/api_docs/kbn_ci_stats_reporter.devdocs.json @@ -654,7 +654,7 @@ "\nOverall result of this test group" ], "signature": [ - "\"fail\" | \"pass\" | \"skip\"" + "\"skip\" | \"fail\" | \"pass\"" ], "path": "packages/kbn-ci-stats-reporter/src/ci_stats_test_group_types.ts", "deprecated": false, @@ -755,7 +755,7 @@ "\n\"fail\", \"pass\" or \"skip\", the result of the tests" ], "signature": [ - "\"fail\" | \"pass\" | \"skip\"" + "\"skip\" | \"fail\" | \"pass\"" ], "path": "packages/kbn-ci-stats-reporter/src/ci_stats_test_group_types.ts", "deprecated": false, @@ -1041,7 +1041,7 @@ "label": "CiStatsTestResult", "description": [], "signature": [ - "\"fail\" | \"pass\" | \"skip\"" + "\"skip\" | \"fail\" | \"pass\"" ], "path": "packages/kbn-ci-stats-reporter/src/ci_stats_test_group_types.ts", "deprecated": false, diff --git a/api_docs/kbn_ci_stats_reporter.mdx b/api_docs/kbn_ci_stats_reporter.mdx index c36dabc793b02..464ef1f629346 100644 --- a/api_docs/kbn_ci_stats_reporter.mdx +++ b/api_docs/kbn_ci_stats_reporter.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ci-stats-reporter title: "@kbn/ci-stats-reporter" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ci-stats-reporter plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ci-stats-reporter'] --- import kbnCiStatsReporterObj from './kbn_ci_stats_reporter.devdocs.json'; diff --git a/api_docs/kbn_cli_dev_mode.mdx b/api_docs/kbn_cli_dev_mode.mdx index 684ae729f0b53..7aac22dfeead6 100644 --- a/api_docs/kbn_cli_dev_mode.mdx +++ b/api_docs/kbn_cli_dev_mode.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-cli-dev-mode title: "@kbn/cli-dev-mode" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/cli-dev-mode plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/cli-dev-mode'] --- import kbnCliDevModeObj from './kbn_cli_dev_mode.devdocs.json'; diff --git a/api_docs/kbn_coloring.mdx b/api_docs/kbn_coloring.mdx index 56327b337a7c2..edd9cb125e751 100644 --- a/api_docs/kbn_coloring.mdx +++ b/api_docs/kbn_coloring.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-coloring title: "@kbn/coloring" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/coloring plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/coloring'] --- import kbnColoringObj from './kbn_coloring.devdocs.json'; diff --git a/api_docs/kbn_config.mdx b/api_docs/kbn_config.mdx index b999b7fba09cc..b82dc689dba2f 100644 --- a/api_docs/kbn_config.mdx +++ b/api_docs/kbn_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-config title: "@kbn/config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/config'] --- import kbnConfigObj from './kbn_config.devdocs.json'; diff --git a/api_docs/kbn_config_mocks.mdx b/api_docs/kbn_config_mocks.mdx index 89dccaa44cab4..cebca9163e797 100644 --- a/api_docs/kbn_config_mocks.mdx +++ b/api_docs/kbn_config_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-config-mocks title: "@kbn/config-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/config-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/config-mocks'] --- import kbnConfigMocksObj from './kbn_config_mocks.devdocs.json'; diff --git a/api_docs/kbn_config_schema.mdx b/api_docs/kbn_config_schema.mdx index 492cfc1af6639..bd788d6e1868d 100644 --- a/api_docs/kbn_config_schema.mdx +++ b/api_docs/kbn_config_schema.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-config-schema title: "@kbn/config-schema" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/config-schema plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/config-schema'] --- import kbnConfigSchemaObj from './kbn_config_schema.devdocs.json'; diff --git a/api_docs/kbn_content_management_table_list.mdx b/api_docs/kbn_content_management_table_list.mdx index e4d47a7a5e993..ac56135aa2927 100644 --- a/api_docs/kbn_content_management_table_list.mdx +++ b/api_docs/kbn_content_management_table_list.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-content-management-table-list title: "@kbn/content-management-table-list" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/content-management-table-list plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/content-management-table-list'] --- import kbnContentManagementTableListObj from './kbn_content_management_table_list.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_browser.mdx b/api_docs/kbn_core_analytics_browser.mdx index 3963d88ebe0dc..eefeafb88d5d6 100644 --- a/api_docs/kbn_core_analytics_browser.mdx +++ b/api_docs/kbn_core_analytics_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-browser title: "@kbn/core-analytics-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-browser'] --- import kbnCoreAnalyticsBrowserObj from './kbn_core_analytics_browser.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_browser_internal.mdx b/api_docs/kbn_core_analytics_browser_internal.mdx index 23c466871d930..36b99e4215594 100644 --- a/api_docs/kbn_core_analytics_browser_internal.mdx +++ b/api_docs/kbn_core_analytics_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-browser-internal title: "@kbn/core-analytics-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-browser-internal'] --- import kbnCoreAnalyticsBrowserInternalObj from './kbn_core_analytics_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_browser_mocks.mdx b/api_docs/kbn_core_analytics_browser_mocks.mdx index b41585c2f4881..abf361ac547be 100644 --- a/api_docs/kbn_core_analytics_browser_mocks.mdx +++ b/api_docs/kbn_core_analytics_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-browser-mocks title: "@kbn/core-analytics-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-browser-mocks'] --- import kbnCoreAnalyticsBrowserMocksObj from './kbn_core_analytics_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_server.mdx b/api_docs/kbn_core_analytics_server.mdx index 30b966682e32d..ec45043e4726a 100644 --- a/api_docs/kbn_core_analytics_server.mdx +++ b/api_docs/kbn_core_analytics_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-server title: "@kbn/core-analytics-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-server'] --- import kbnCoreAnalyticsServerObj from './kbn_core_analytics_server.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_server_internal.mdx b/api_docs/kbn_core_analytics_server_internal.mdx index 0a67e2a249ecd..04e49781988c4 100644 --- a/api_docs/kbn_core_analytics_server_internal.mdx +++ b/api_docs/kbn_core_analytics_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-server-internal title: "@kbn/core-analytics-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-server-internal'] --- import kbnCoreAnalyticsServerInternalObj from './kbn_core_analytics_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_analytics_server_mocks.mdx b/api_docs/kbn_core_analytics_server_mocks.mdx index d54c96d96a78d..126ab218962cd 100644 --- a/api_docs/kbn_core_analytics_server_mocks.mdx +++ b/api_docs/kbn_core_analytics_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-analytics-server-mocks title: "@kbn/core-analytics-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-analytics-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-analytics-server-mocks'] --- import kbnCoreAnalyticsServerMocksObj from './kbn_core_analytics_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_application_browser.mdx b/api_docs/kbn_core_application_browser.mdx index 15f452f602f3a..71e7fae504f5f 100644 --- a/api_docs/kbn_core_application_browser.mdx +++ b/api_docs/kbn_core_application_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-application-browser title: "@kbn/core-application-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-application-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-application-browser'] --- import kbnCoreApplicationBrowserObj from './kbn_core_application_browser.devdocs.json'; diff --git a/api_docs/kbn_core_application_browser_internal.mdx b/api_docs/kbn_core_application_browser_internal.mdx index d2ca1e1cdf64f..55beb31993bb2 100644 --- a/api_docs/kbn_core_application_browser_internal.mdx +++ b/api_docs/kbn_core_application_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-application-browser-internal title: "@kbn/core-application-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-application-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-application-browser-internal'] --- import kbnCoreApplicationBrowserInternalObj from './kbn_core_application_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_application_browser_mocks.mdx b/api_docs/kbn_core_application_browser_mocks.mdx index 4e5ea9b96abf5..c777505da45db 100644 --- a/api_docs/kbn_core_application_browser_mocks.mdx +++ b/api_docs/kbn_core_application_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-application-browser-mocks title: "@kbn/core-application-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-application-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-application-browser-mocks'] --- import kbnCoreApplicationBrowserMocksObj from './kbn_core_application_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_application_common.mdx b/api_docs/kbn_core_application_common.mdx index 6180696154344..10828fe0de714 100644 --- a/api_docs/kbn_core_application_common.mdx +++ b/api_docs/kbn_core_application_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-application-common title: "@kbn/core-application-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-application-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-application-common'] --- import kbnCoreApplicationCommonObj from './kbn_core_application_common.devdocs.json'; diff --git a/api_docs/kbn_core_apps_browser_internal.mdx b/api_docs/kbn_core_apps_browser_internal.mdx index d2691bfa66636..978ac4faed760 100644 --- a/api_docs/kbn_core_apps_browser_internal.mdx +++ b/api_docs/kbn_core_apps_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-apps-browser-internal title: "@kbn/core-apps-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-apps-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-apps-browser-internal'] --- import kbnCoreAppsBrowserInternalObj from './kbn_core_apps_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_apps_browser_mocks.mdx b/api_docs/kbn_core_apps_browser_mocks.mdx index a97c1b99cebe2..16fd9445d124c 100644 --- a/api_docs/kbn_core_apps_browser_mocks.mdx +++ b/api_docs/kbn_core_apps_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-apps-browser-mocks title: "@kbn/core-apps-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-apps-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-apps-browser-mocks'] --- import kbnCoreAppsBrowserMocksObj from './kbn_core_apps_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_base_browser_mocks.mdx b/api_docs/kbn_core_base_browser_mocks.mdx index d0afb23fc2964..cdaf427d6802b 100644 --- a/api_docs/kbn_core_base_browser_mocks.mdx +++ b/api_docs/kbn_core_base_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-base-browser-mocks title: "@kbn/core-base-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-base-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-base-browser-mocks'] --- import kbnCoreBaseBrowserMocksObj from './kbn_core_base_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_base_common.mdx b/api_docs/kbn_core_base_common.mdx index 51d7ca9f8ab89..5bd2a717b5b84 100644 --- a/api_docs/kbn_core_base_common.mdx +++ b/api_docs/kbn_core_base_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-base-common title: "@kbn/core-base-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-base-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-base-common'] --- import kbnCoreBaseCommonObj from './kbn_core_base_common.devdocs.json'; diff --git a/api_docs/kbn_core_base_server_internal.mdx b/api_docs/kbn_core_base_server_internal.mdx index d7cdf10b971d5..76f931b4d756c 100644 --- a/api_docs/kbn_core_base_server_internal.mdx +++ b/api_docs/kbn_core_base_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-base-server-internal title: "@kbn/core-base-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-base-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-base-server-internal'] --- import kbnCoreBaseServerInternalObj from './kbn_core_base_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_base_server_mocks.mdx b/api_docs/kbn_core_base_server_mocks.mdx index 46d148fd00f47..77aa19a6800c9 100644 --- a/api_docs/kbn_core_base_server_mocks.mdx +++ b/api_docs/kbn_core_base_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-base-server-mocks title: "@kbn/core-base-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-base-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-base-server-mocks'] --- import kbnCoreBaseServerMocksObj from './kbn_core_base_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_capabilities_browser_mocks.mdx b/api_docs/kbn_core_capabilities_browser_mocks.mdx index 8a2759159936f..e6bfe1ecd7db2 100644 --- a/api_docs/kbn_core_capabilities_browser_mocks.mdx +++ b/api_docs/kbn_core_capabilities_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-capabilities-browser-mocks title: "@kbn/core-capabilities-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-capabilities-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-capabilities-browser-mocks'] --- import kbnCoreCapabilitiesBrowserMocksObj from './kbn_core_capabilities_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_capabilities_common.mdx b/api_docs/kbn_core_capabilities_common.mdx index 33ab3d655c3d6..e9475861b697e 100644 --- a/api_docs/kbn_core_capabilities_common.mdx +++ b/api_docs/kbn_core_capabilities_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-capabilities-common title: "@kbn/core-capabilities-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-capabilities-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-capabilities-common'] --- import kbnCoreCapabilitiesCommonObj from './kbn_core_capabilities_common.devdocs.json'; diff --git a/api_docs/kbn_core_capabilities_server.mdx b/api_docs/kbn_core_capabilities_server.mdx index 8c0b095a8af9f..d6dc431b07fdc 100644 --- a/api_docs/kbn_core_capabilities_server.mdx +++ b/api_docs/kbn_core_capabilities_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-capabilities-server title: "@kbn/core-capabilities-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-capabilities-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-capabilities-server'] --- import kbnCoreCapabilitiesServerObj from './kbn_core_capabilities_server.devdocs.json'; diff --git a/api_docs/kbn_core_capabilities_server_mocks.mdx b/api_docs/kbn_core_capabilities_server_mocks.mdx index 5eb8c9868d0e0..fdf7cc31d41f9 100644 --- a/api_docs/kbn_core_capabilities_server_mocks.mdx +++ b/api_docs/kbn_core_capabilities_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-capabilities-server-mocks title: "@kbn/core-capabilities-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-capabilities-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-capabilities-server-mocks'] --- import kbnCoreCapabilitiesServerMocksObj from './kbn_core_capabilities_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_chrome_browser.mdx b/api_docs/kbn_core_chrome_browser.mdx index 1d58a5f7e61aa..73d5385236586 100644 --- a/api_docs/kbn_core_chrome_browser.mdx +++ b/api_docs/kbn_core_chrome_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-chrome-browser title: "@kbn/core-chrome-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-chrome-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-chrome-browser'] --- import kbnCoreChromeBrowserObj from './kbn_core_chrome_browser.devdocs.json'; diff --git a/api_docs/kbn_core_chrome_browser_mocks.mdx b/api_docs/kbn_core_chrome_browser_mocks.mdx index ed179dfdb1276..a1f512749d437 100644 --- a/api_docs/kbn_core_chrome_browser_mocks.mdx +++ b/api_docs/kbn_core_chrome_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-chrome-browser-mocks title: "@kbn/core-chrome-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-chrome-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-chrome-browser-mocks'] --- import kbnCoreChromeBrowserMocksObj from './kbn_core_chrome_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_config_server_internal.mdx b/api_docs/kbn_core_config_server_internal.mdx index 759a640237749..42574e3029ea4 100644 --- a/api_docs/kbn_core_config_server_internal.mdx +++ b/api_docs/kbn_core_config_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-config-server-internal title: "@kbn/core-config-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-config-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-config-server-internal'] --- import kbnCoreConfigServerInternalObj from './kbn_core_config_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_browser.mdx b/api_docs/kbn_core_deprecations_browser.mdx index f8bd9caed5b1c..6bb0bb64c5ba2 100644 --- a/api_docs/kbn_core_deprecations_browser.mdx +++ b/api_docs/kbn_core_deprecations_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-browser title: "@kbn/core-deprecations-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-browser'] --- import kbnCoreDeprecationsBrowserObj from './kbn_core_deprecations_browser.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_browser_internal.mdx b/api_docs/kbn_core_deprecations_browser_internal.mdx index 5ddab954f056f..938d8d6b38aff 100644 --- a/api_docs/kbn_core_deprecations_browser_internal.mdx +++ b/api_docs/kbn_core_deprecations_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-browser-internal title: "@kbn/core-deprecations-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-browser-internal'] --- import kbnCoreDeprecationsBrowserInternalObj from './kbn_core_deprecations_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_browser_mocks.mdx b/api_docs/kbn_core_deprecations_browser_mocks.mdx index f81419be79cb5..9d33c64bd7f4a 100644 --- a/api_docs/kbn_core_deprecations_browser_mocks.mdx +++ b/api_docs/kbn_core_deprecations_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-browser-mocks title: "@kbn/core-deprecations-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-browser-mocks'] --- import kbnCoreDeprecationsBrowserMocksObj from './kbn_core_deprecations_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_common.mdx b/api_docs/kbn_core_deprecations_common.mdx index 615f4b126dc8c..7f254dda6eee2 100644 --- a/api_docs/kbn_core_deprecations_common.mdx +++ b/api_docs/kbn_core_deprecations_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-common title: "@kbn/core-deprecations-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-common'] --- import kbnCoreDeprecationsCommonObj from './kbn_core_deprecations_common.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_server.mdx b/api_docs/kbn_core_deprecations_server.mdx index 6d9794ef57332..527a5f2be91ee 100644 --- a/api_docs/kbn_core_deprecations_server.mdx +++ b/api_docs/kbn_core_deprecations_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-server title: "@kbn/core-deprecations-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-server'] --- import kbnCoreDeprecationsServerObj from './kbn_core_deprecations_server.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_server_internal.mdx b/api_docs/kbn_core_deprecations_server_internal.mdx index e8fb9f138c2ad..7b470aeff3555 100644 --- a/api_docs/kbn_core_deprecations_server_internal.mdx +++ b/api_docs/kbn_core_deprecations_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-server-internal title: "@kbn/core-deprecations-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-server-internal'] --- import kbnCoreDeprecationsServerInternalObj from './kbn_core_deprecations_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_deprecations_server_mocks.mdx b/api_docs/kbn_core_deprecations_server_mocks.mdx index 3a4926f8f7749..34e0e5fb4d1fe 100644 --- a/api_docs/kbn_core_deprecations_server_mocks.mdx +++ b/api_docs/kbn_core_deprecations_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-deprecations-server-mocks title: "@kbn/core-deprecations-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-deprecations-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-deprecations-server-mocks'] --- import kbnCoreDeprecationsServerMocksObj from './kbn_core_deprecations_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_doc_links_browser.mdx b/api_docs/kbn_core_doc_links_browser.mdx index a35bb9c60290f..97c4d2e6d4b44 100644 --- a/api_docs/kbn_core_doc_links_browser.mdx +++ b/api_docs/kbn_core_doc_links_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-doc-links-browser title: "@kbn/core-doc-links-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-doc-links-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-doc-links-browser'] --- import kbnCoreDocLinksBrowserObj from './kbn_core_doc_links_browser.devdocs.json'; diff --git a/api_docs/kbn_core_doc_links_browser_mocks.mdx b/api_docs/kbn_core_doc_links_browser_mocks.mdx index 9afc41514e5e6..0347b3f309a86 100644 --- a/api_docs/kbn_core_doc_links_browser_mocks.mdx +++ b/api_docs/kbn_core_doc_links_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-doc-links-browser-mocks title: "@kbn/core-doc-links-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-doc-links-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-doc-links-browser-mocks'] --- import kbnCoreDocLinksBrowserMocksObj from './kbn_core_doc_links_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_doc_links_server.mdx b/api_docs/kbn_core_doc_links_server.mdx index 3255e485c9b0a..5cccdf33b5038 100644 --- a/api_docs/kbn_core_doc_links_server.mdx +++ b/api_docs/kbn_core_doc_links_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-doc-links-server title: "@kbn/core-doc-links-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-doc-links-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-doc-links-server'] --- import kbnCoreDocLinksServerObj from './kbn_core_doc_links_server.devdocs.json'; diff --git a/api_docs/kbn_core_doc_links_server_mocks.mdx b/api_docs/kbn_core_doc_links_server_mocks.mdx index 1063fef175e9a..e2c4d921a70b3 100644 --- a/api_docs/kbn_core_doc_links_server_mocks.mdx +++ b/api_docs/kbn_core_doc_links_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-doc-links-server-mocks title: "@kbn/core-doc-links-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-doc-links-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-doc-links-server-mocks'] --- import kbnCoreDocLinksServerMocksObj from './kbn_core_doc_links_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_elasticsearch_client_server_internal.mdx b/api_docs/kbn_core_elasticsearch_client_server_internal.mdx index ff9a0baaa5d59..1d786ddcd3496 100644 --- a/api_docs/kbn_core_elasticsearch_client_server_internal.mdx +++ b/api_docs/kbn_core_elasticsearch_client_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-elasticsearch-client-server-internal title: "@kbn/core-elasticsearch-client-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-elasticsearch-client-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-elasticsearch-client-server-internal'] --- import kbnCoreElasticsearchClientServerInternalObj from './kbn_core_elasticsearch_client_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_elasticsearch_client_server_mocks.mdx b/api_docs/kbn_core_elasticsearch_client_server_mocks.mdx index d6435555e96e6..25079df745e3c 100644 --- a/api_docs/kbn_core_elasticsearch_client_server_mocks.mdx +++ b/api_docs/kbn_core_elasticsearch_client_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-elasticsearch-client-server-mocks title: "@kbn/core-elasticsearch-client-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-elasticsearch-client-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-elasticsearch-client-server-mocks'] --- import kbnCoreElasticsearchClientServerMocksObj from './kbn_core_elasticsearch_client_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_elasticsearch_server.mdx b/api_docs/kbn_core_elasticsearch_server.mdx index 4bb98103a64d4..a5712d10acd36 100644 --- a/api_docs/kbn_core_elasticsearch_server.mdx +++ b/api_docs/kbn_core_elasticsearch_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-elasticsearch-server title: "@kbn/core-elasticsearch-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-elasticsearch-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-elasticsearch-server'] --- import kbnCoreElasticsearchServerObj from './kbn_core_elasticsearch_server.devdocs.json'; diff --git a/api_docs/kbn_core_elasticsearch_server_internal.mdx b/api_docs/kbn_core_elasticsearch_server_internal.mdx index 7ad9e23acb721..2b2107d520826 100644 --- a/api_docs/kbn_core_elasticsearch_server_internal.mdx +++ b/api_docs/kbn_core_elasticsearch_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-elasticsearch-server-internal title: "@kbn/core-elasticsearch-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-elasticsearch-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-elasticsearch-server-internal'] --- import kbnCoreElasticsearchServerInternalObj from './kbn_core_elasticsearch_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_elasticsearch_server_mocks.mdx b/api_docs/kbn_core_elasticsearch_server_mocks.mdx index d9f63f24452cb..c9aa728e95fb2 100644 --- a/api_docs/kbn_core_elasticsearch_server_mocks.mdx +++ b/api_docs/kbn_core_elasticsearch_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-elasticsearch-server-mocks title: "@kbn/core-elasticsearch-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-elasticsearch-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-elasticsearch-server-mocks'] --- import kbnCoreElasticsearchServerMocksObj from './kbn_core_elasticsearch_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_environment_server_internal.mdx b/api_docs/kbn_core_environment_server_internal.mdx index d2e0eac9b9816..630ee26b50242 100644 --- a/api_docs/kbn_core_environment_server_internal.mdx +++ b/api_docs/kbn_core_environment_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-environment-server-internal title: "@kbn/core-environment-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-environment-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-environment-server-internal'] --- import kbnCoreEnvironmentServerInternalObj from './kbn_core_environment_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_environment_server_mocks.mdx b/api_docs/kbn_core_environment_server_mocks.mdx index 9a2fe27257295..62ed3d4b8afa0 100644 --- a/api_docs/kbn_core_environment_server_mocks.mdx +++ b/api_docs/kbn_core_environment_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-environment-server-mocks title: "@kbn/core-environment-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-environment-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-environment-server-mocks'] --- import kbnCoreEnvironmentServerMocksObj from './kbn_core_environment_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_browser.mdx b/api_docs/kbn_core_execution_context_browser.mdx index 44333efae72e1..1c33ab738b0ea 100644 --- a/api_docs/kbn_core_execution_context_browser.mdx +++ b/api_docs/kbn_core_execution_context_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-browser title: "@kbn/core-execution-context-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-browser'] --- import kbnCoreExecutionContextBrowserObj from './kbn_core_execution_context_browser.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_browser_internal.mdx b/api_docs/kbn_core_execution_context_browser_internal.mdx index cc8aaa60e702a..8d4402a7a2cda 100644 --- a/api_docs/kbn_core_execution_context_browser_internal.mdx +++ b/api_docs/kbn_core_execution_context_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-browser-internal title: "@kbn/core-execution-context-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-browser-internal'] --- import kbnCoreExecutionContextBrowserInternalObj from './kbn_core_execution_context_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_browser_mocks.mdx b/api_docs/kbn_core_execution_context_browser_mocks.mdx index 5d3c46ebc068a..5e923792bc936 100644 --- a/api_docs/kbn_core_execution_context_browser_mocks.mdx +++ b/api_docs/kbn_core_execution_context_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-browser-mocks title: "@kbn/core-execution-context-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-browser-mocks'] --- import kbnCoreExecutionContextBrowserMocksObj from './kbn_core_execution_context_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_common.mdx b/api_docs/kbn_core_execution_context_common.mdx index a1fb8bd905ca0..f2336d9fdfb05 100644 --- a/api_docs/kbn_core_execution_context_common.mdx +++ b/api_docs/kbn_core_execution_context_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-common title: "@kbn/core-execution-context-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-common'] --- import kbnCoreExecutionContextCommonObj from './kbn_core_execution_context_common.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_server.mdx b/api_docs/kbn_core_execution_context_server.mdx index 67c3abd06ea84..61e72d43c392a 100644 --- a/api_docs/kbn_core_execution_context_server.mdx +++ b/api_docs/kbn_core_execution_context_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-server title: "@kbn/core-execution-context-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-server'] --- import kbnCoreExecutionContextServerObj from './kbn_core_execution_context_server.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_server_internal.mdx b/api_docs/kbn_core_execution_context_server_internal.mdx index db91209848963..1c31d922fc680 100644 --- a/api_docs/kbn_core_execution_context_server_internal.mdx +++ b/api_docs/kbn_core_execution_context_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-server-internal title: "@kbn/core-execution-context-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-server-internal'] --- import kbnCoreExecutionContextServerInternalObj from './kbn_core_execution_context_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_execution_context_server_mocks.mdx b/api_docs/kbn_core_execution_context_server_mocks.mdx index 788b1d01bbec3..00772d47658c5 100644 --- a/api_docs/kbn_core_execution_context_server_mocks.mdx +++ b/api_docs/kbn_core_execution_context_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-execution-context-server-mocks title: "@kbn/core-execution-context-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-execution-context-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-execution-context-server-mocks'] --- import kbnCoreExecutionContextServerMocksObj from './kbn_core_execution_context_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_fatal_errors_browser.mdx b/api_docs/kbn_core_fatal_errors_browser.mdx index ce5add93ded9b..7a8edbe3e3b30 100644 --- a/api_docs/kbn_core_fatal_errors_browser.mdx +++ b/api_docs/kbn_core_fatal_errors_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-fatal-errors-browser title: "@kbn/core-fatal-errors-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-fatal-errors-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-fatal-errors-browser'] --- import kbnCoreFatalErrorsBrowserObj from './kbn_core_fatal_errors_browser.devdocs.json'; diff --git a/api_docs/kbn_core_fatal_errors_browser_mocks.mdx b/api_docs/kbn_core_fatal_errors_browser_mocks.mdx index c4622e5ed407b..6dd6b8aebce65 100644 --- a/api_docs/kbn_core_fatal_errors_browser_mocks.mdx +++ b/api_docs/kbn_core_fatal_errors_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-fatal-errors-browser-mocks title: "@kbn/core-fatal-errors-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-fatal-errors-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-fatal-errors-browser-mocks'] --- import kbnCoreFatalErrorsBrowserMocksObj from './kbn_core_fatal_errors_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_http_browser.mdx b/api_docs/kbn_core_http_browser.mdx index 00ed1200e185d..8014dbb2ceb6b 100644 --- a/api_docs/kbn_core_http_browser.mdx +++ b/api_docs/kbn_core_http_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-browser title: "@kbn/core-http-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-browser'] --- import kbnCoreHttpBrowserObj from './kbn_core_http_browser.devdocs.json'; diff --git a/api_docs/kbn_core_http_browser_internal.mdx b/api_docs/kbn_core_http_browser_internal.mdx index bacf194851ae1..ed565e7b8f3b3 100644 --- a/api_docs/kbn_core_http_browser_internal.mdx +++ b/api_docs/kbn_core_http_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-browser-internal title: "@kbn/core-http-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-browser-internal'] --- import kbnCoreHttpBrowserInternalObj from './kbn_core_http_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_http_browser_mocks.mdx b/api_docs/kbn_core_http_browser_mocks.mdx index 6cc3300153374..632f5546a7210 100644 --- a/api_docs/kbn_core_http_browser_mocks.mdx +++ b/api_docs/kbn_core_http_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-browser-mocks title: "@kbn/core-http-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-browser-mocks'] --- import kbnCoreHttpBrowserMocksObj from './kbn_core_http_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_http_common.mdx b/api_docs/kbn_core_http_common.mdx index 245ed8af6bab0..92184cbab2784 100644 --- a/api_docs/kbn_core_http_common.mdx +++ b/api_docs/kbn_core_http_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-common title: "@kbn/core-http-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-common'] --- import kbnCoreHttpCommonObj from './kbn_core_http_common.devdocs.json'; diff --git a/api_docs/kbn_core_http_context_server_mocks.mdx b/api_docs/kbn_core_http_context_server_mocks.mdx index 4f2adfbc0e897..52f62aad5c930 100644 --- a/api_docs/kbn_core_http_context_server_mocks.mdx +++ b/api_docs/kbn_core_http_context_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-context-server-mocks title: "@kbn/core-http-context-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-context-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-context-server-mocks'] --- import kbnCoreHttpContextServerMocksObj from './kbn_core_http_context_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_http_request_handler_context_server.devdocs.json b/api_docs/kbn_core_http_request_handler_context_server.devdocs.json new file mode 100644 index 0000000000000..ebf6567c0a8b4 --- /dev/null +++ b/api_docs/kbn_core_http_request_handler_context_server.devdocs.json @@ -0,0 +1,283 @@ +{ + "id": "@kbn/core-http-request-handler-context-server", + "client": { + "classes": [], + "functions": [], + "interfaces": [], + "enums": [], + "misc": [], + "objects": [] + }, + "server": { + "classes": [], + "functions": [], + "interfaces": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CoreRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "CoreRequestHandlerContext", + "description": [ + "\nThe `core` context provided to route handler.\n\nProvides the following clients and services:\n - {@link SavedObjectsClient | savedObjects.client} - Saved Objects client\n which uses the credentials of the incoming request\n - {@link ISavedObjectTypeRegistry | savedObjects.typeRegistry} - Type registry containing\n all the registered types.\n - {@link IScopedClusterClient | elasticsearch.client} - Elasticsearch\n data client which uses the credentials of the incoming request\n - {@link IUiSettingsClient | uiSettings.client} - uiSettings client\n which uses the credentials of the incoming request" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CoreRequestHandlerContext.savedObjects", + "type": "Object", + "tags": [], + "label": "savedObjects", + "description": [], + "signature": [ + "SavedObjectsRequestHandlerContext" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CoreRequestHandlerContext.elasticsearch", + "type": "Object", + "tags": [], + "label": "elasticsearch", + "description": [], + "signature": [ + "ElasticsearchRequestHandlerContext" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CoreRequestHandlerContext.uiSettings", + "type": "Object", + "tags": [], + "label": "uiSettings", + "description": [], + "signature": [ + "UiSettingsRequestHandlerContext" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CoreRequestHandlerContext.deprecations", + "type": "Object", + "tags": [], + "label": "deprecations", + "description": [], + "signature": [ + "DeprecationsRequestHandlerContext" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootCoreRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "PrebootCoreRequestHandlerContext", + "description": [], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootCoreRequestHandlerContext.uiSettings", + "type": "Object", + "tags": [], + "label": "uiSettings", + "description": [], + "signature": [ + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.PrebootUiSettingsRequestHandlerContext", + "text": "PrebootUiSettingsRequestHandlerContext" + } + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "PrebootRequestHandlerContext", + "description": [], + "signature": [ + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.PrebootRequestHandlerContext", + "text": "PrebootRequestHandlerContext" + }, + " extends ", + "RequestHandlerContextBase" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootRequestHandlerContext.core", + "type": "Object", + "tags": [], + "label": "core", + "description": [], + "signature": [ + "Promise<", + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.PrebootCoreRequestHandlerContext", + "text": "PrebootCoreRequestHandlerContext" + }, + ">" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootUiSettingsRequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "PrebootUiSettingsRequestHandlerContext", + "description": [], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.PrebootUiSettingsRequestHandlerContext.client", + "type": "Object", + "tags": [], + "label": "client", + "description": [], + "signature": [ + "IUiSettingsClient" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.RequestHandlerContext", + "type": "Interface", + "tags": [], + "label": "RequestHandlerContext", + "description": [ + "\nBase context passed to a route handler, containing the `core` context part.\n" + ], + "signature": [ + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.RequestHandlerContext", + "text": "RequestHandlerContext" + }, + " extends ", + "RequestHandlerContextBase" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.RequestHandlerContext.core", + "type": "Object", + "tags": [], + "label": "core", + "description": [], + "signature": [ + "Promise<", + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.CoreRequestHandlerContext", + "text": "CoreRequestHandlerContext" + }, + ">" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + } + ], + "enums": [], + "misc": [ + { + "parentPluginId": "@kbn/core-http-request-handler-context-server", + "id": "def-server.CustomRequestHandlerContext", + "type": "Type", + "tags": [], + "label": "CustomRequestHandlerContext", + "description": [ + "\nMixin allowing plugins to define their own request handler contexts.\n" + ], + "signature": [ + { + "pluginId": "@kbn/core-http-request-handler-context-server", + "scope": "server", + "docId": "kibKbnCoreHttpRequestHandlerContextServerPluginApi", + "section": "def-server.RequestHandlerContext", + "text": "RequestHandlerContext" + }, + " & { [Key in keyof T]: T[Key] extends Promise ? T[Key] : Promise; }" + ], + "path": "packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + } + ], + "objects": [] + }, + "common": { + "classes": [], + "functions": [], + "interfaces": [], + "enums": [], + "misc": [], + "objects": [] + } +} \ No newline at end of file diff --git a/api_docs/kbn_core_http_request_handler_context_server.mdx b/api_docs/kbn_core_http_request_handler_context_server.mdx new file mode 100644 index 0000000000000..0e41263673dda --- /dev/null +++ b/api_docs/kbn_core_http_request_handler_context_server.mdx @@ -0,0 +1,33 @@ +--- +#### +#### This document is auto-generated and is meant to be viewed inside our experimental, new docs system. +#### Reach out in #docs-engineering for more info. +#### +id: kibKbnCoreHttpRequestHandlerContextServerPluginApi +slug: /kibana-dev-docs/api/kbn-core-http-request-handler-context-server +title: "@kbn/core-http-request-handler-context-server" +image: https://source.unsplash.com/400x175/?github +description: API docs for the @kbn/core-http-request-handler-context-server plugin +date: 2022-09-29 +tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-request-handler-context-server'] +--- +import kbnCoreHttpRequestHandlerContextServerObj from './kbn_core_http_request_handler_context_server.devdocs.json'; + + + +Contact Kibana Core for questions regarding this plugin. + +**Code health stats** + +| Public API count | Any count | Items lacking comments | Missing exports | +|-------------------|-----------|------------------------|-----------------| +| 14 | 0 | 11 | 0 | + +## Server + +### Interfaces + + +### Consts, variables and types + + diff --git a/api_docs/kbn_core_http_router_server_internal.mdx b/api_docs/kbn_core_http_router_server_internal.mdx index e3ec06a3a639d..0fdb1bfe43185 100644 --- a/api_docs/kbn_core_http_router_server_internal.mdx +++ b/api_docs/kbn_core_http_router_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-router-server-internal title: "@kbn/core-http-router-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-router-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-router-server-internal'] --- import kbnCoreHttpRouterServerInternalObj from './kbn_core_http_router_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_http_router_server_mocks.mdx b/api_docs/kbn_core_http_router_server_mocks.mdx index 45107aab5e05d..b758dea2dd269 100644 --- a/api_docs/kbn_core_http_router_server_mocks.mdx +++ b/api_docs/kbn_core_http_router_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-router-server-mocks title: "@kbn/core-http-router-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-router-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-router-server-mocks'] --- import kbnCoreHttpRouterServerMocksObj from './kbn_core_http_router_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_http_server.mdx b/api_docs/kbn_core_http_server.mdx index 5c288a131070c..bb3c7c1bd3505 100644 --- a/api_docs/kbn_core_http_server.mdx +++ b/api_docs/kbn_core_http_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-server title: "@kbn/core-http-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-server'] --- import kbnCoreHttpServerObj from './kbn_core_http_server.devdocs.json'; diff --git a/api_docs/kbn_core_http_server_internal.mdx b/api_docs/kbn_core_http_server_internal.mdx index 0a8cb658945e9..220d5282e1fc4 100644 --- a/api_docs/kbn_core_http_server_internal.mdx +++ b/api_docs/kbn_core_http_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-server-internal title: "@kbn/core-http-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-server-internal'] --- import kbnCoreHttpServerInternalObj from './kbn_core_http_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_http_server_mocks.mdx b/api_docs/kbn_core_http_server_mocks.mdx index a8401fce4884f..ed120c45d977d 100644 --- a/api_docs/kbn_core_http_server_mocks.mdx +++ b/api_docs/kbn_core_http_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-http-server-mocks title: "@kbn/core-http-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-http-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-http-server-mocks'] --- import kbnCoreHttpServerMocksObj from './kbn_core_http_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_i18n_browser.mdx b/api_docs/kbn_core_i18n_browser.mdx index 93cb07e285c54..9cb11bc93a1fe 100644 --- a/api_docs/kbn_core_i18n_browser.mdx +++ b/api_docs/kbn_core_i18n_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-i18n-browser title: "@kbn/core-i18n-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-i18n-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-i18n-browser'] --- import kbnCoreI18nBrowserObj from './kbn_core_i18n_browser.devdocs.json'; diff --git a/api_docs/kbn_core_i18n_browser_mocks.mdx b/api_docs/kbn_core_i18n_browser_mocks.mdx index 0e03b322e5fe7..1bb71320adbcf 100644 --- a/api_docs/kbn_core_i18n_browser_mocks.mdx +++ b/api_docs/kbn_core_i18n_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-i18n-browser-mocks title: "@kbn/core-i18n-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-i18n-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-i18n-browser-mocks'] --- import kbnCoreI18nBrowserMocksObj from './kbn_core_i18n_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_i18n_server.mdx b/api_docs/kbn_core_i18n_server.mdx index d45eca1ec9b95..edbbec7b5aac1 100644 --- a/api_docs/kbn_core_i18n_server.mdx +++ b/api_docs/kbn_core_i18n_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-i18n-server title: "@kbn/core-i18n-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-i18n-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-i18n-server'] --- import kbnCoreI18nServerObj from './kbn_core_i18n_server.devdocs.json'; diff --git a/api_docs/kbn_core_i18n_server_internal.mdx b/api_docs/kbn_core_i18n_server_internal.mdx index 2f38c40e7b1d0..408a8656056a7 100644 --- a/api_docs/kbn_core_i18n_server_internal.mdx +++ b/api_docs/kbn_core_i18n_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-i18n-server-internal title: "@kbn/core-i18n-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-i18n-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-i18n-server-internal'] --- import kbnCoreI18nServerInternalObj from './kbn_core_i18n_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_i18n_server_mocks.mdx b/api_docs/kbn_core_i18n_server_mocks.mdx index 4b103d193e7dc..549c463617a54 100644 --- a/api_docs/kbn_core_i18n_server_mocks.mdx +++ b/api_docs/kbn_core_i18n_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-i18n-server-mocks title: "@kbn/core-i18n-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-i18n-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-i18n-server-mocks'] --- import kbnCoreI18nServerMocksObj from './kbn_core_i18n_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_injected_metadata_browser.mdx b/api_docs/kbn_core_injected_metadata_browser.mdx index f4f5febf27a39..11a4ba2c541e6 100644 --- a/api_docs/kbn_core_injected_metadata_browser.mdx +++ b/api_docs/kbn_core_injected_metadata_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-injected-metadata-browser title: "@kbn/core-injected-metadata-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-injected-metadata-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-injected-metadata-browser'] --- import kbnCoreInjectedMetadataBrowserObj from './kbn_core_injected_metadata_browser.devdocs.json'; diff --git a/api_docs/kbn_core_injected_metadata_browser_mocks.mdx b/api_docs/kbn_core_injected_metadata_browser_mocks.mdx index 138e613d2db1a..579e9087903cf 100644 --- a/api_docs/kbn_core_injected_metadata_browser_mocks.mdx +++ b/api_docs/kbn_core_injected_metadata_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-injected-metadata-browser-mocks title: "@kbn/core-injected-metadata-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-injected-metadata-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-injected-metadata-browser-mocks'] --- import kbnCoreInjectedMetadataBrowserMocksObj from './kbn_core_injected_metadata_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_integrations_browser_internal.mdx b/api_docs/kbn_core_integrations_browser_internal.mdx index ec00287941891..c88718d0e930c 100644 --- a/api_docs/kbn_core_integrations_browser_internal.mdx +++ b/api_docs/kbn_core_integrations_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-integrations-browser-internal title: "@kbn/core-integrations-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-integrations-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-integrations-browser-internal'] --- import kbnCoreIntegrationsBrowserInternalObj from './kbn_core_integrations_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_integrations_browser_mocks.mdx b/api_docs/kbn_core_integrations_browser_mocks.mdx index e4e1d4c03aed4..6be7ee2210094 100644 --- a/api_docs/kbn_core_integrations_browser_mocks.mdx +++ b/api_docs/kbn_core_integrations_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-integrations-browser-mocks title: "@kbn/core-integrations-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-integrations-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-integrations-browser-mocks'] --- import kbnCoreIntegrationsBrowserMocksObj from './kbn_core_integrations_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_lifecycle_browser.mdx b/api_docs/kbn_core_lifecycle_browser.mdx index 228c1de238119..863f69b315180 100644 --- a/api_docs/kbn_core_lifecycle_browser.mdx +++ b/api_docs/kbn_core_lifecycle_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-lifecycle-browser title: "@kbn/core-lifecycle-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-lifecycle-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-lifecycle-browser'] --- import kbnCoreLifecycleBrowserObj from './kbn_core_lifecycle_browser.devdocs.json'; diff --git a/api_docs/kbn_core_lifecycle_browser_mocks.mdx b/api_docs/kbn_core_lifecycle_browser_mocks.mdx index 341910977ce43..add898c16abe6 100644 --- a/api_docs/kbn_core_lifecycle_browser_mocks.mdx +++ b/api_docs/kbn_core_lifecycle_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-lifecycle-browser-mocks title: "@kbn/core-lifecycle-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-lifecycle-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-lifecycle-browser-mocks'] --- import kbnCoreLifecycleBrowserMocksObj from './kbn_core_lifecycle_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_logging_server.mdx b/api_docs/kbn_core_logging_server.mdx index 74084f769426b..a488e40d01dd0 100644 --- a/api_docs/kbn_core_logging_server.mdx +++ b/api_docs/kbn_core_logging_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-logging-server title: "@kbn/core-logging-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-logging-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-logging-server'] --- import kbnCoreLoggingServerObj from './kbn_core_logging_server.devdocs.json'; diff --git a/api_docs/kbn_core_logging_server_internal.mdx b/api_docs/kbn_core_logging_server_internal.mdx index f596b9e2c1cec..87082d1e33197 100644 --- a/api_docs/kbn_core_logging_server_internal.mdx +++ b/api_docs/kbn_core_logging_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-logging-server-internal title: "@kbn/core-logging-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-logging-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-logging-server-internal'] --- import kbnCoreLoggingServerInternalObj from './kbn_core_logging_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_logging_server_mocks.mdx b/api_docs/kbn_core_logging_server_mocks.mdx index b26dafe15f86e..7a746c6278054 100644 --- a/api_docs/kbn_core_logging_server_mocks.mdx +++ b/api_docs/kbn_core_logging_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-logging-server-mocks title: "@kbn/core-logging-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-logging-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-logging-server-mocks'] --- import kbnCoreLoggingServerMocksObj from './kbn_core_logging_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_metrics_collectors_server_internal.mdx b/api_docs/kbn_core_metrics_collectors_server_internal.mdx index 9fc66b3eff5c5..a413d283cb4c8 100644 --- a/api_docs/kbn_core_metrics_collectors_server_internal.mdx +++ b/api_docs/kbn_core_metrics_collectors_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-metrics-collectors-server-internal title: "@kbn/core-metrics-collectors-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-metrics-collectors-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-metrics-collectors-server-internal'] --- import kbnCoreMetricsCollectorsServerInternalObj from './kbn_core_metrics_collectors_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_metrics_collectors_server_mocks.mdx b/api_docs/kbn_core_metrics_collectors_server_mocks.mdx index dd7dc366a7f53..3ad9c040ab8ff 100644 --- a/api_docs/kbn_core_metrics_collectors_server_mocks.mdx +++ b/api_docs/kbn_core_metrics_collectors_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-metrics-collectors-server-mocks title: "@kbn/core-metrics-collectors-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-metrics-collectors-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-metrics-collectors-server-mocks'] --- import kbnCoreMetricsCollectorsServerMocksObj from './kbn_core_metrics_collectors_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_metrics_server.mdx b/api_docs/kbn_core_metrics_server.mdx index c7a4675a50f26..4e9e0445e3f75 100644 --- a/api_docs/kbn_core_metrics_server.mdx +++ b/api_docs/kbn_core_metrics_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-metrics-server title: "@kbn/core-metrics-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-metrics-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-metrics-server'] --- import kbnCoreMetricsServerObj from './kbn_core_metrics_server.devdocs.json'; diff --git a/api_docs/kbn_core_metrics_server_internal.mdx b/api_docs/kbn_core_metrics_server_internal.mdx index f75d6e2e4df86..0cfd64309de97 100644 --- a/api_docs/kbn_core_metrics_server_internal.mdx +++ b/api_docs/kbn_core_metrics_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-metrics-server-internal title: "@kbn/core-metrics-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-metrics-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-metrics-server-internal'] --- import kbnCoreMetricsServerInternalObj from './kbn_core_metrics_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_metrics_server_mocks.mdx b/api_docs/kbn_core_metrics_server_mocks.mdx index 27eb84bcb629d..40f97497e1cff 100644 --- a/api_docs/kbn_core_metrics_server_mocks.mdx +++ b/api_docs/kbn_core_metrics_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-metrics-server-mocks title: "@kbn/core-metrics-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-metrics-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-metrics-server-mocks'] --- import kbnCoreMetricsServerMocksObj from './kbn_core_metrics_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_mount_utils_browser.mdx b/api_docs/kbn_core_mount_utils_browser.mdx index 931250f276d88..3e4d25261b363 100644 --- a/api_docs/kbn_core_mount_utils_browser.mdx +++ b/api_docs/kbn_core_mount_utils_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-mount-utils-browser title: "@kbn/core-mount-utils-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-mount-utils-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-mount-utils-browser'] --- import kbnCoreMountUtilsBrowserObj from './kbn_core_mount_utils_browser.devdocs.json'; diff --git a/api_docs/kbn_core_node_server.mdx b/api_docs/kbn_core_node_server.mdx index 0ea10d0228459..9ec6da0be76fe 100644 --- a/api_docs/kbn_core_node_server.mdx +++ b/api_docs/kbn_core_node_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-node-server title: "@kbn/core-node-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-node-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-node-server'] --- import kbnCoreNodeServerObj from './kbn_core_node_server.devdocs.json'; diff --git a/api_docs/kbn_core_node_server_internal.mdx b/api_docs/kbn_core_node_server_internal.mdx index d6ada13d2b459..e1be058f66949 100644 --- a/api_docs/kbn_core_node_server_internal.mdx +++ b/api_docs/kbn_core_node_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-node-server-internal title: "@kbn/core-node-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-node-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-node-server-internal'] --- import kbnCoreNodeServerInternalObj from './kbn_core_node_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_node_server_mocks.mdx b/api_docs/kbn_core_node_server_mocks.mdx index 055a033501826..2f8dd3d2d3cfc 100644 --- a/api_docs/kbn_core_node_server_mocks.mdx +++ b/api_docs/kbn_core_node_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-node-server-mocks title: "@kbn/core-node-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-node-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-node-server-mocks'] --- import kbnCoreNodeServerMocksObj from './kbn_core_node_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_notifications_browser.mdx b/api_docs/kbn_core_notifications_browser.mdx index e34899253c5c5..99c39b3ae3bff 100644 --- a/api_docs/kbn_core_notifications_browser.mdx +++ b/api_docs/kbn_core_notifications_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-notifications-browser title: "@kbn/core-notifications-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-notifications-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-notifications-browser'] --- import kbnCoreNotificationsBrowserObj from './kbn_core_notifications_browser.devdocs.json'; diff --git a/api_docs/kbn_core_notifications_browser_internal.mdx b/api_docs/kbn_core_notifications_browser_internal.mdx index 7ef10010ee5db..b1abfcae9d1d7 100644 --- a/api_docs/kbn_core_notifications_browser_internal.mdx +++ b/api_docs/kbn_core_notifications_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-notifications-browser-internal title: "@kbn/core-notifications-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-notifications-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-notifications-browser-internal'] --- import kbnCoreNotificationsBrowserInternalObj from './kbn_core_notifications_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_notifications_browser_mocks.mdx b/api_docs/kbn_core_notifications_browser_mocks.mdx index 1b3e5556d6df3..6af7ea7a401a6 100644 --- a/api_docs/kbn_core_notifications_browser_mocks.mdx +++ b/api_docs/kbn_core_notifications_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-notifications-browser-mocks title: "@kbn/core-notifications-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-notifications-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-notifications-browser-mocks'] --- import kbnCoreNotificationsBrowserMocksObj from './kbn_core_notifications_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_overlays_browser.mdx b/api_docs/kbn_core_overlays_browser.mdx index 74050c9f387f7..4e53620f210c2 100644 --- a/api_docs/kbn_core_overlays_browser.mdx +++ b/api_docs/kbn_core_overlays_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-overlays-browser title: "@kbn/core-overlays-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-overlays-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-overlays-browser'] --- import kbnCoreOverlaysBrowserObj from './kbn_core_overlays_browser.devdocs.json'; diff --git a/api_docs/kbn_core_overlays_browser_internal.mdx b/api_docs/kbn_core_overlays_browser_internal.mdx index 955f110fe4809..3cdf63fa196bf 100644 --- a/api_docs/kbn_core_overlays_browser_internal.mdx +++ b/api_docs/kbn_core_overlays_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-overlays-browser-internal title: "@kbn/core-overlays-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-overlays-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-overlays-browser-internal'] --- import kbnCoreOverlaysBrowserInternalObj from './kbn_core_overlays_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_overlays_browser_mocks.mdx b/api_docs/kbn_core_overlays_browser_mocks.mdx index 84ef476c88624..ed9822ce6524b 100644 --- a/api_docs/kbn_core_overlays_browser_mocks.mdx +++ b/api_docs/kbn_core_overlays_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-overlays-browser-mocks title: "@kbn/core-overlays-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-overlays-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-overlays-browser-mocks'] --- import kbnCoreOverlaysBrowserMocksObj from './kbn_core_overlays_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_plugins_browser.mdx b/api_docs/kbn_core_plugins_browser.mdx index 2b5918007517a..0e35863807e95 100644 --- a/api_docs/kbn_core_plugins_browser.mdx +++ b/api_docs/kbn_core_plugins_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-plugins-browser title: "@kbn/core-plugins-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-plugins-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-plugins-browser'] --- import kbnCorePluginsBrowserObj from './kbn_core_plugins_browser.devdocs.json'; diff --git a/api_docs/kbn_core_plugins_browser_mocks.mdx b/api_docs/kbn_core_plugins_browser_mocks.mdx index 1d7f7defbc093..e8513df53c908 100644 --- a/api_docs/kbn_core_plugins_browser_mocks.mdx +++ b/api_docs/kbn_core_plugins_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-plugins-browser-mocks title: "@kbn/core-plugins-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-plugins-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-plugins-browser-mocks'] --- import kbnCorePluginsBrowserMocksObj from './kbn_core_plugins_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_preboot_server.mdx b/api_docs/kbn_core_preboot_server.mdx index a7df07f457116..a33965c6f0245 100644 --- a/api_docs/kbn_core_preboot_server.mdx +++ b/api_docs/kbn_core_preboot_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-preboot-server title: "@kbn/core-preboot-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-preboot-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-preboot-server'] --- import kbnCorePrebootServerObj from './kbn_core_preboot_server.devdocs.json'; diff --git a/api_docs/kbn_core_preboot_server_mocks.mdx b/api_docs/kbn_core_preboot_server_mocks.mdx index f91e8ae1b93d3..499f42fd91b2c 100644 --- a/api_docs/kbn_core_preboot_server_mocks.mdx +++ b/api_docs/kbn_core_preboot_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-preboot-server-mocks title: "@kbn/core-preboot-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-preboot-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-preboot-server-mocks'] --- import kbnCorePrebootServerMocksObj from './kbn_core_preboot_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_rendering_browser_mocks.mdx b/api_docs/kbn_core_rendering_browser_mocks.mdx index 77eb97cc9c81c..cedfc5029275d 100644 --- a/api_docs/kbn_core_rendering_browser_mocks.mdx +++ b/api_docs/kbn_core_rendering_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-rendering-browser-mocks title: "@kbn/core-rendering-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-rendering-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-rendering-browser-mocks'] --- import kbnCoreRenderingBrowserMocksObj from './kbn_core_rendering_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_api_browser.devdocs.json b/api_docs/kbn_core_saved_objects_api_browser.devdocs.json index b12a698b21606..bc6024dea788e 100644 --- a/api_docs/kbn_core_saved_objects_api_browser.devdocs.json +++ b/api_docs/kbn_core_saved_objects_api_browser.devdocs.json @@ -76,7 +76,7 @@ "\nThe outcome for a successful `resolve` call is one of the following values:\n\n * `'exactMatch'` -- One document exactly matched the given ID.\n * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different\n than the given ID.\n * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the\n `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID." ], "signature": [ - "\"exactMatch\" | \"aliasMatch\" | \"conflict\"" + "\"conflict\" | \"exactMatch\" | \"aliasMatch\"" ], "path": "packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts", "deprecated": false, @@ -1974,9 +1974,9 @@ "label": "SavedObjectsFindOptions", "description": [], "signature": [ - "{ type: string | string[]; filter?: any; search?: string | undefined; aggs?: Record | undefined; fields?: string[] | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; searchFields?: string[] | undefined; hasReference?: ", + "> | undefined; page?: number | undefined; perPage?: number | undefined; sortField?: string | undefined; searchFields?: string[] | undefined; hasReference?: ", "SavedObjectsFindOptionsReference", " | ", "SavedObjectsFindOptionsReference", diff --git a/api_docs/kbn_core_saved_objects_api_browser.mdx b/api_docs/kbn_core_saved_objects_api_browser.mdx index 26f71de8a5ce5..de5b9aa205cab 100644 --- a/api_docs/kbn_core_saved_objects_api_browser.mdx +++ b/api_docs/kbn_core_saved_objects_api_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-api-browser title: "@kbn/core-saved-objects-api-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-api-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-api-browser'] --- import kbnCoreSavedObjectsApiBrowserObj from './kbn_core_saved_objects_api_browser.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_api_server.devdocs.json b/api_docs/kbn_core_saved_objects_api_server.devdocs.json index 0e040b72d2d3d..1bff25681bdbf 100644 --- a/api_docs/kbn_core_saved_objects_api_server.devdocs.json +++ b/api_docs/kbn_core_saved_objects_api_server.devdocs.json @@ -5949,7 +5949,7 @@ "\nThe outcome for a successful `resolve` call is one of the following values:\n\n * `'exactMatch'` -- One document exactly matched the given ID.\n * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different\n than the given ID.\n * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the\n `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID." ], "signature": [ - "\"exactMatch\" | \"aliasMatch\" | \"conflict\"" + "\"conflict\" | \"exactMatch\" | \"aliasMatch\"" ], "path": "packages/core/saved-objects/core-saved-objects-api-server/src/apis/resolve.ts", "deprecated": false, @@ -6427,9 +6427,9 @@ "label": "SavedObjectsCreatePointInTimeFinderOptions", "description": [], "signature": [ - "{ type: string | string[]; filter?: any; search?: string | undefined; aggs?: Record | undefined; fields?: string[] | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", + "> | undefined; perPage?: number | undefined; sortField?: string | undefined; sortOrder?: ", "SortOrder", " | undefined; searchFields?: string[] | undefined; rootSearchFields?: string[] | undefined; hasReference?: ", { diff --git a/api_docs/kbn_core_saved_objects_api_server.mdx b/api_docs/kbn_core_saved_objects_api_server.mdx index 16b0b1af9e207..7628f073dc948 100644 --- a/api_docs/kbn_core_saved_objects_api_server.mdx +++ b/api_docs/kbn_core_saved_objects_api_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-api-server title: "@kbn/core-saved-objects-api-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-api-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-api-server'] --- import kbnCoreSavedObjectsApiServerObj from './kbn_core_saved_objects_api_server.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_api_server_internal.mdx b/api_docs/kbn_core_saved_objects_api_server_internal.mdx index a1436d596ee1c..a91351cf9f732 100644 --- a/api_docs/kbn_core_saved_objects_api_server_internal.mdx +++ b/api_docs/kbn_core_saved_objects_api_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-api-server-internal title: "@kbn/core-saved-objects-api-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-api-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-api-server-internal'] --- import kbnCoreSavedObjectsApiServerInternalObj from './kbn_core_saved_objects_api_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_api_server_mocks.mdx b/api_docs/kbn_core_saved_objects_api_server_mocks.mdx index a28f6bdd8a24d..fa562b3b2acf5 100644 --- a/api_docs/kbn_core_saved_objects_api_server_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_api_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-api-server-mocks title: "@kbn/core-saved-objects-api-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-api-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-api-server-mocks'] --- import kbnCoreSavedObjectsApiServerMocksObj from './kbn_core_saved_objects_api_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_base_server_internal.mdx b/api_docs/kbn_core_saved_objects_base_server_internal.mdx index 4961251518500..acc5f724b1bc8 100644 --- a/api_docs/kbn_core_saved_objects_base_server_internal.mdx +++ b/api_docs/kbn_core_saved_objects_base_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-base-server-internal title: "@kbn/core-saved-objects-base-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-base-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-base-server-internal'] --- import kbnCoreSavedObjectsBaseServerInternalObj from './kbn_core_saved_objects_base_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_base_server_mocks.mdx b/api_docs/kbn_core_saved_objects_base_server_mocks.mdx index 447e54cee040b..114ad87c44b3c 100644 --- a/api_docs/kbn_core_saved_objects_base_server_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_base_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-base-server-mocks title: "@kbn/core-saved-objects-base-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-base-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-base-server-mocks'] --- import kbnCoreSavedObjectsBaseServerMocksObj from './kbn_core_saved_objects_base_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_browser.mdx b/api_docs/kbn_core_saved_objects_browser.mdx index 2a3f0b6aa99dc..6731e21119771 100644 --- a/api_docs/kbn_core_saved_objects_browser.mdx +++ b/api_docs/kbn_core_saved_objects_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-browser title: "@kbn/core-saved-objects-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-browser'] --- import kbnCoreSavedObjectsBrowserObj from './kbn_core_saved_objects_browser.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_browser_internal.mdx b/api_docs/kbn_core_saved_objects_browser_internal.mdx index a98c1c6e2be22..276569792284a 100644 --- a/api_docs/kbn_core_saved_objects_browser_internal.mdx +++ b/api_docs/kbn_core_saved_objects_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-browser-internal title: "@kbn/core-saved-objects-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-browser-internal'] --- import kbnCoreSavedObjectsBrowserInternalObj from './kbn_core_saved_objects_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_browser_mocks.mdx b/api_docs/kbn_core_saved_objects_browser_mocks.mdx index efb252b353d8d..9f0c9ea82ba6c 100644 --- a/api_docs/kbn_core_saved_objects_browser_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-browser-mocks title: "@kbn/core-saved-objects-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-browser-mocks'] --- import kbnCoreSavedObjectsBrowserMocksObj from './kbn_core_saved_objects_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_common.mdx b/api_docs/kbn_core_saved_objects_common.mdx index 803208ad83bde..bc3ea822a9424 100644 --- a/api_docs/kbn_core_saved_objects_common.mdx +++ b/api_docs/kbn_core_saved_objects_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-common title: "@kbn/core-saved-objects-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-common'] --- import kbnCoreSavedObjectsCommonObj from './kbn_core_saved_objects_common.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_import_export_server_internal.mdx b/api_docs/kbn_core_saved_objects_import_export_server_internal.mdx index 1593a6563a9f1..b5f3e61df18bf 100644 --- a/api_docs/kbn_core_saved_objects_import_export_server_internal.mdx +++ b/api_docs/kbn_core_saved_objects_import_export_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-import-export-server-internal title: "@kbn/core-saved-objects-import-export-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-import-export-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-import-export-server-internal'] --- import kbnCoreSavedObjectsImportExportServerInternalObj from './kbn_core_saved_objects_import_export_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_import_export_server_mocks.mdx b/api_docs/kbn_core_saved_objects_import_export_server_mocks.mdx index 4e20ad04423fd..99e95bfdab286 100644 --- a/api_docs/kbn_core_saved_objects_import_export_server_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_import_export_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-import-export-server-mocks title: "@kbn/core-saved-objects-import-export-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-import-export-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-import-export-server-mocks'] --- import kbnCoreSavedObjectsImportExportServerMocksObj from './kbn_core_saved_objects_import_export_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_migration_server_internal.mdx b/api_docs/kbn_core_saved_objects_migration_server_internal.mdx index 9c33ea4c0d532..5edf8cbfddef4 100644 --- a/api_docs/kbn_core_saved_objects_migration_server_internal.mdx +++ b/api_docs/kbn_core_saved_objects_migration_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-migration-server-internal title: "@kbn/core-saved-objects-migration-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-migration-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-migration-server-internal'] --- import kbnCoreSavedObjectsMigrationServerInternalObj from './kbn_core_saved_objects_migration_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_migration_server_mocks.mdx b/api_docs/kbn_core_saved_objects_migration_server_mocks.mdx index 3cee9dd92656d..5ed2a4976d1cf 100644 --- a/api_docs/kbn_core_saved_objects_migration_server_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_migration_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-migration-server-mocks title: "@kbn/core-saved-objects-migration-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-migration-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-migration-server-mocks'] --- import kbnCoreSavedObjectsMigrationServerMocksObj from './kbn_core_saved_objects_migration_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_server.mdx b/api_docs/kbn_core_saved_objects_server.mdx index 19f37abb20263..8f12d48e0f7a2 100644 --- a/api_docs/kbn_core_saved_objects_server.mdx +++ b/api_docs/kbn_core_saved_objects_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-server title: "@kbn/core-saved-objects-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-server'] --- import kbnCoreSavedObjectsServerObj from './kbn_core_saved_objects_server.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_server_internal.mdx b/api_docs/kbn_core_saved_objects_server_internal.mdx index 81272d53ba6d1..6de1b336be402 100644 --- a/api_docs/kbn_core_saved_objects_server_internal.mdx +++ b/api_docs/kbn_core_saved_objects_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-server-internal title: "@kbn/core-saved-objects-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-server-internal'] --- import kbnCoreSavedObjectsServerInternalObj from './kbn_core_saved_objects_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_server_mocks.mdx b/api_docs/kbn_core_saved_objects_server_mocks.mdx index be028a3b85168..4fb52fecf8710 100644 --- a/api_docs/kbn_core_saved_objects_server_mocks.mdx +++ b/api_docs/kbn_core_saved_objects_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-server-mocks title: "@kbn/core-saved-objects-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-server-mocks'] --- import kbnCoreSavedObjectsServerMocksObj from './kbn_core_saved_objects_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_saved_objects_utils_server.mdx b/api_docs/kbn_core_saved_objects_utils_server.mdx index afc1a85e2f556..71fdb228446e2 100644 --- a/api_docs/kbn_core_saved_objects_utils_server.mdx +++ b/api_docs/kbn_core_saved_objects_utils_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-saved-objects-utils-server title: "@kbn/core-saved-objects-utils-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-saved-objects-utils-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-saved-objects-utils-server'] --- import kbnCoreSavedObjectsUtilsServerObj from './kbn_core_saved_objects_utils_server.devdocs.json'; diff --git a/api_docs/kbn_core_status_common.mdx b/api_docs/kbn_core_status_common.mdx index 0711b45cc57d1..49314722d46af 100644 --- a/api_docs/kbn_core_status_common.mdx +++ b/api_docs/kbn_core_status_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-status-common title: "@kbn/core-status-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-status-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-status-common'] --- import kbnCoreStatusCommonObj from './kbn_core_status_common.devdocs.json'; diff --git a/api_docs/kbn_core_status_common_internal.mdx b/api_docs/kbn_core_status_common_internal.mdx index 4d73717fa6bbb..266265f2ee05f 100644 --- a/api_docs/kbn_core_status_common_internal.mdx +++ b/api_docs/kbn_core_status_common_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-status-common-internal title: "@kbn/core-status-common-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-status-common-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-status-common-internal'] --- import kbnCoreStatusCommonInternalObj from './kbn_core_status_common_internal.devdocs.json'; diff --git a/api_docs/kbn_core_status_server.mdx b/api_docs/kbn_core_status_server.mdx index acde498787c65..8d222376f5bf9 100644 --- a/api_docs/kbn_core_status_server.mdx +++ b/api_docs/kbn_core_status_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-status-server title: "@kbn/core-status-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-status-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-status-server'] --- import kbnCoreStatusServerObj from './kbn_core_status_server.devdocs.json'; diff --git a/api_docs/kbn_core_status_server_internal.mdx b/api_docs/kbn_core_status_server_internal.mdx index 1c59293c82fe1..f8cae5c4a5506 100644 --- a/api_docs/kbn_core_status_server_internal.mdx +++ b/api_docs/kbn_core_status_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-status-server-internal title: "@kbn/core-status-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-status-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-status-server-internal'] --- import kbnCoreStatusServerInternalObj from './kbn_core_status_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_status_server_mocks.mdx b/api_docs/kbn_core_status_server_mocks.mdx index 4436c0815f04a..0dacdfd5af97c 100644 --- a/api_docs/kbn_core_status_server_mocks.mdx +++ b/api_docs/kbn_core_status_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-status-server-mocks title: "@kbn/core-status-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-status-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-status-server-mocks'] --- import kbnCoreStatusServerMocksObj from './kbn_core_status_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_test_helpers_deprecations_getters.mdx b/api_docs/kbn_core_test_helpers_deprecations_getters.mdx index afd52adf21d20..99b4036abb6bd 100644 --- a/api_docs/kbn_core_test_helpers_deprecations_getters.mdx +++ b/api_docs/kbn_core_test_helpers_deprecations_getters.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-test-helpers-deprecations-getters title: "@kbn/core-test-helpers-deprecations-getters" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-test-helpers-deprecations-getters plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-test-helpers-deprecations-getters'] --- import kbnCoreTestHelpersDeprecationsGettersObj from './kbn_core_test_helpers_deprecations_getters.devdocs.json'; diff --git a/api_docs/kbn_core_test_helpers_http_setup_browser.mdx b/api_docs/kbn_core_test_helpers_http_setup_browser.mdx index d4b695e741006..549cdfe3a58e1 100644 --- a/api_docs/kbn_core_test_helpers_http_setup_browser.mdx +++ b/api_docs/kbn_core_test_helpers_http_setup_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-test-helpers-http-setup-browser title: "@kbn/core-test-helpers-http-setup-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-test-helpers-http-setup-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-test-helpers-http-setup-browser'] --- import kbnCoreTestHelpersHttpSetupBrowserObj from './kbn_core_test_helpers_http_setup_browser.devdocs.json'; diff --git a/api_docs/kbn_core_theme_browser.mdx b/api_docs/kbn_core_theme_browser.mdx index 58f6cbfeab598..c429de87e13d9 100644 --- a/api_docs/kbn_core_theme_browser.mdx +++ b/api_docs/kbn_core_theme_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-theme-browser title: "@kbn/core-theme-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-theme-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-theme-browser'] --- import kbnCoreThemeBrowserObj from './kbn_core_theme_browser.devdocs.json'; diff --git a/api_docs/kbn_core_theme_browser_internal.mdx b/api_docs/kbn_core_theme_browser_internal.mdx index 5f48aa2745570..0888bc8875a22 100644 --- a/api_docs/kbn_core_theme_browser_internal.mdx +++ b/api_docs/kbn_core_theme_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-theme-browser-internal title: "@kbn/core-theme-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-theme-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-theme-browser-internal'] --- import kbnCoreThemeBrowserInternalObj from './kbn_core_theme_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_theme_browser_mocks.mdx b/api_docs/kbn_core_theme_browser_mocks.mdx index 793e79b6aae60..254373b7a14d3 100644 --- a/api_docs/kbn_core_theme_browser_mocks.mdx +++ b/api_docs/kbn_core_theme_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-theme-browser-mocks title: "@kbn/core-theme-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-theme-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-theme-browser-mocks'] --- import kbnCoreThemeBrowserMocksObj from './kbn_core_theme_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_browser.mdx b/api_docs/kbn_core_ui_settings_browser.mdx index 3018311b36ca0..61ceae147d70f 100644 --- a/api_docs/kbn_core_ui_settings_browser.mdx +++ b/api_docs/kbn_core_ui_settings_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-browser title: "@kbn/core-ui-settings-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-browser'] --- import kbnCoreUiSettingsBrowserObj from './kbn_core_ui_settings_browser.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_browser_internal.mdx b/api_docs/kbn_core_ui_settings_browser_internal.mdx index 0c83d35792645..9b9365bc3081a 100644 --- a/api_docs/kbn_core_ui_settings_browser_internal.mdx +++ b/api_docs/kbn_core_ui_settings_browser_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-browser-internal title: "@kbn/core-ui-settings-browser-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-browser-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-browser-internal'] --- import kbnCoreUiSettingsBrowserInternalObj from './kbn_core_ui_settings_browser_internal.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_browser_mocks.mdx b/api_docs/kbn_core_ui_settings_browser_mocks.mdx index 3e5fc158db0e8..baf48b87a0eb3 100644 --- a/api_docs/kbn_core_ui_settings_browser_mocks.mdx +++ b/api_docs/kbn_core_ui_settings_browser_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-browser-mocks title: "@kbn/core-ui-settings-browser-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-browser-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-browser-mocks'] --- import kbnCoreUiSettingsBrowserMocksObj from './kbn_core_ui_settings_browser_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_common.mdx b/api_docs/kbn_core_ui_settings_common.mdx index 7a4d2e6f76c05..1aba4f31960ad 100644 --- a/api_docs/kbn_core_ui_settings_common.mdx +++ b/api_docs/kbn_core_ui_settings_common.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-common title: "@kbn/core-ui-settings-common" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-common plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-common'] --- import kbnCoreUiSettingsCommonObj from './kbn_core_ui_settings_common.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_server.mdx b/api_docs/kbn_core_ui_settings_server.mdx index ceb4e7510df6c..b2fe92199314c 100644 --- a/api_docs/kbn_core_ui_settings_server.mdx +++ b/api_docs/kbn_core_ui_settings_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-server title: "@kbn/core-ui-settings-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-server'] --- import kbnCoreUiSettingsServerObj from './kbn_core_ui_settings_server.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_server_internal.mdx b/api_docs/kbn_core_ui_settings_server_internal.mdx index c3f41e7a93c39..91c104b8b9de3 100644 --- a/api_docs/kbn_core_ui_settings_server_internal.mdx +++ b/api_docs/kbn_core_ui_settings_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-server-internal title: "@kbn/core-ui-settings-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-server-internal'] --- import kbnCoreUiSettingsServerInternalObj from './kbn_core_ui_settings_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_ui_settings_server_mocks.mdx b/api_docs/kbn_core_ui_settings_server_mocks.mdx index 009da9871cacb..31ba42e2554fc 100644 --- a/api_docs/kbn_core_ui_settings_server_mocks.mdx +++ b/api_docs/kbn_core_ui_settings_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-ui-settings-server-mocks title: "@kbn/core-ui-settings-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-ui-settings-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-ui-settings-server-mocks'] --- import kbnCoreUiSettingsServerMocksObj from './kbn_core_ui_settings_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_core_usage_data_server.mdx b/api_docs/kbn_core_usage_data_server.mdx index cee9f5d6574ef..a25b0cfc501c8 100644 --- a/api_docs/kbn_core_usage_data_server.mdx +++ b/api_docs/kbn_core_usage_data_server.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-usage-data-server title: "@kbn/core-usage-data-server" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-usage-data-server plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-usage-data-server'] --- import kbnCoreUsageDataServerObj from './kbn_core_usage_data_server.devdocs.json'; diff --git a/api_docs/kbn_core_usage_data_server_internal.mdx b/api_docs/kbn_core_usage_data_server_internal.mdx index dde6cc13f0d7a..101431a9c73db 100644 --- a/api_docs/kbn_core_usage_data_server_internal.mdx +++ b/api_docs/kbn_core_usage_data_server_internal.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-usage-data-server-internal title: "@kbn/core-usage-data-server-internal" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-usage-data-server-internal plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-usage-data-server-internal'] --- import kbnCoreUsageDataServerInternalObj from './kbn_core_usage_data_server_internal.devdocs.json'; diff --git a/api_docs/kbn_core_usage_data_server_mocks.mdx b/api_docs/kbn_core_usage_data_server_mocks.mdx index 51a7bd54317e2..710a3c62d5446 100644 --- a/api_docs/kbn_core_usage_data_server_mocks.mdx +++ b/api_docs/kbn_core_usage_data_server_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-core-usage-data-server-mocks title: "@kbn/core-usage-data-server-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/core-usage-data-server-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/core-usage-data-server-mocks'] --- import kbnCoreUsageDataServerMocksObj from './kbn_core_usage_data_server_mocks.devdocs.json'; diff --git a/api_docs/kbn_crypto.mdx b/api_docs/kbn_crypto.mdx index b34ce13cff481..a8c5ebefe66c9 100644 --- a/api_docs/kbn_crypto.mdx +++ b/api_docs/kbn_crypto.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-crypto title: "@kbn/crypto" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/crypto plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/crypto'] --- import kbnCryptoObj from './kbn_crypto.devdocs.json'; diff --git a/api_docs/kbn_crypto_browser.mdx b/api_docs/kbn_crypto_browser.mdx index 9f429a934f52e..b7a8b4187db82 100644 --- a/api_docs/kbn_crypto_browser.mdx +++ b/api_docs/kbn_crypto_browser.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-crypto-browser title: "@kbn/crypto-browser" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/crypto-browser plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/crypto-browser'] --- import kbnCryptoBrowserObj from './kbn_crypto_browser.devdocs.json'; diff --git a/api_docs/kbn_datemath.mdx b/api_docs/kbn_datemath.mdx index ac7832eee896e..77c10c205e812 100644 --- a/api_docs/kbn_datemath.mdx +++ b/api_docs/kbn_datemath.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-datemath title: "@kbn/datemath" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/datemath plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/datemath'] --- import kbnDatemathObj from './kbn_datemath.devdocs.json'; diff --git a/api_docs/kbn_dev_cli_errors.mdx b/api_docs/kbn_dev_cli_errors.mdx index 0f86f2ff4b9f4..f79bd78824a01 100644 --- a/api_docs/kbn_dev_cli_errors.mdx +++ b/api_docs/kbn_dev_cli_errors.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-dev-cli-errors title: "@kbn/dev-cli-errors" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/dev-cli-errors plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/dev-cli-errors'] --- import kbnDevCliErrorsObj from './kbn_dev_cli_errors.devdocs.json'; diff --git a/api_docs/kbn_dev_cli_runner.mdx b/api_docs/kbn_dev_cli_runner.mdx index 45dd5563f16e7..156f2ad1e34d0 100644 --- a/api_docs/kbn_dev_cli_runner.mdx +++ b/api_docs/kbn_dev_cli_runner.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-dev-cli-runner title: "@kbn/dev-cli-runner" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/dev-cli-runner plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/dev-cli-runner'] --- import kbnDevCliRunnerObj from './kbn_dev_cli_runner.devdocs.json'; diff --git a/api_docs/kbn_dev_proc_runner.mdx b/api_docs/kbn_dev_proc_runner.mdx index b04c85e281cf0..c40a114fb200d 100644 --- a/api_docs/kbn_dev_proc_runner.mdx +++ b/api_docs/kbn_dev_proc_runner.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-dev-proc-runner title: "@kbn/dev-proc-runner" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/dev-proc-runner plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/dev-proc-runner'] --- import kbnDevProcRunnerObj from './kbn_dev_proc_runner.devdocs.json'; diff --git a/api_docs/kbn_dev_utils.mdx b/api_docs/kbn_dev_utils.mdx index 88cb75e8f3f22..6c817ebf71e78 100644 --- a/api_docs/kbn_dev_utils.mdx +++ b/api_docs/kbn_dev_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-dev-utils title: "@kbn/dev-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/dev-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/dev-utils'] --- import kbnDevUtilsObj from './kbn_dev_utils.devdocs.json'; diff --git a/api_docs/kbn_doc_links.mdx b/api_docs/kbn_doc_links.mdx index 616f1cca3ea9d..055b95affc247 100644 --- a/api_docs/kbn_doc_links.mdx +++ b/api_docs/kbn_doc_links.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-doc-links title: "@kbn/doc-links" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/doc-links plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/doc-links'] --- import kbnDocLinksObj from './kbn_doc_links.devdocs.json'; diff --git a/api_docs/kbn_docs_utils.mdx b/api_docs/kbn_docs_utils.mdx index 53bb660a8e7b1..f6a0a8c29e495 100644 --- a/api_docs/kbn_docs_utils.mdx +++ b/api_docs/kbn_docs_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-docs-utils title: "@kbn/docs-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/docs-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/docs-utils'] --- import kbnDocsUtilsObj from './kbn_docs_utils.devdocs.json'; diff --git a/api_docs/kbn_ebt_tools.mdx b/api_docs/kbn_ebt_tools.mdx index a0e9a2c8017ef..fa63acb9d852c 100644 --- a/api_docs/kbn_ebt_tools.mdx +++ b/api_docs/kbn_ebt_tools.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ebt-tools title: "@kbn/ebt-tools" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ebt-tools plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ebt-tools'] --- import kbnEbtToolsObj from './kbn_ebt_tools.devdocs.json'; diff --git a/api_docs/kbn_es_archiver.mdx b/api_docs/kbn_es_archiver.mdx index 9411c11c7447d..9f608a801f2c0 100644 --- a/api_docs/kbn_es_archiver.mdx +++ b/api_docs/kbn_es_archiver.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-es-archiver title: "@kbn/es-archiver" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/es-archiver plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/es-archiver'] --- import kbnEsArchiverObj from './kbn_es_archiver.devdocs.json'; diff --git a/api_docs/kbn_es_errors.mdx b/api_docs/kbn_es_errors.mdx index 88df541d3f845..1498ddb5d2636 100644 --- a/api_docs/kbn_es_errors.mdx +++ b/api_docs/kbn_es_errors.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-es-errors title: "@kbn/es-errors" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/es-errors plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/es-errors'] --- import kbnEsErrorsObj from './kbn_es_errors.devdocs.json'; diff --git a/api_docs/kbn_es_query.mdx b/api_docs/kbn_es_query.mdx index 1a5e2446af816..537db266a40f5 100644 --- a/api_docs/kbn_es_query.mdx +++ b/api_docs/kbn_es_query.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-es-query title: "@kbn/es-query" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/es-query plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/es-query'] --- import kbnEsQueryObj from './kbn_es_query.devdocs.json'; diff --git a/api_docs/kbn_es_types.mdx b/api_docs/kbn_es_types.mdx index 4894e6741a7cc..923c644404d7b 100644 --- a/api_docs/kbn_es_types.mdx +++ b/api_docs/kbn_es_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-es-types title: "@kbn/es-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/es-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/es-types'] --- import kbnEsTypesObj from './kbn_es_types.devdocs.json'; diff --git a/api_docs/kbn_eslint_plugin_imports.mdx b/api_docs/kbn_eslint_plugin_imports.mdx index bfe263038499e..23893848967a1 100644 --- a/api_docs/kbn_eslint_plugin_imports.mdx +++ b/api_docs/kbn_eslint_plugin_imports.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-eslint-plugin-imports title: "@kbn/eslint-plugin-imports" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/eslint-plugin-imports plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/eslint-plugin-imports'] --- import kbnEslintPluginImportsObj from './kbn_eslint_plugin_imports.devdocs.json'; diff --git a/api_docs/kbn_field_types.mdx b/api_docs/kbn_field_types.mdx index 6cc96f29596cb..a29e11c7f3f5c 100644 --- a/api_docs/kbn_field_types.mdx +++ b/api_docs/kbn_field_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-field-types title: "@kbn/field-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/field-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/field-types'] --- import kbnFieldTypesObj from './kbn_field_types.devdocs.json'; diff --git a/api_docs/kbn_find_used_node_modules.mdx b/api_docs/kbn_find_used_node_modules.mdx index 61e4b8c3d726d..c3673495d2d9a 100644 --- a/api_docs/kbn_find_used_node_modules.mdx +++ b/api_docs/kbn_find_used_node_modules.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-find-used-node-modules title: "@kbn/find-used-node-modules" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/find-used-node-modules plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/find-used-node-modules'] --- import kbnFindUsedNodeModulesObj from './kbn_find_used_node_modules.devdocs.json'; diff --git a/api_docs/kbn_ftr_common_functional_services.mdx b/api_docs/kbn_ftr_common_functional_services.mdx index 84efde87a1fde..29968a934531a 100644 --- a/api_docs/kbn_ftr_common_functional_services.mdx +++ b/api_docs/kbn_ftr_common_functional_services.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ftr-common-functional-services title: "@kbn/ftr-common-functional-services" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ftr-common-functional-services plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ftr-common-functional-services'] --- import kbnFtrCommonFunctionalServicesObj from './kbn_ftr_common_functional_services.devdocs.json'; diff --git a/api_docs/kbn_generate.mdx b/api_docs/kbn_generate.mdx index 104726e50bc58..535192fd22884 100644 --- a/api_docs/kbn_generate.mdx +++ b/api_docs/kbn_generate.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-generate title: "@kbn/generate" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/generate plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/generate'] --- import kbnGenerateObj from './kbn_generate.devdocs.json'; diff --git a/api_docs/kbn_get_repo_files.mdx b/api_docs/kbn_get_repo_files.mdx index d37093b825fe6..270341543e978 100644 --- a/api_docs/kbn_get_repo_files.mdx +++ b/api_docs/kbn_get_repo_files.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-get-repo-files title: "@kbn/get-repo-files" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/get-repo-files plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/get-repo-files'] --- import kbnGetRepoFilesObj from './kbn_get_repo_files.devdocs.json'; diff --git a/api_docs/kbn_handlebars.mdx b/api_docs/kbn_handlebars.mdx index ee29767cd0d97..75d249e64bf71 100644 --- a/api_docs/kbn_handlebars.mdx +++ b/api_docs/kbn_handlebars.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-handlebars title: "@kbn/handlebars" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/handlebars plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/handlebars'] --- import kbnHandlebarsObj from './kbn_handlebars.devdocs.json'; diff --git a/api_docs/kbn_hapi_mocks.mdx b/api_docs/kbn_hapi_mocks.mdx index 700389481b7c7..d7346ce1b677d 100644 --- a/api_docs/kbn_hapi_mocks.mdx +++ b/api_docs/kbn_hapi_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-hapi-mocks title: "@kbn/hapi-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/hapi-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/hapi-mocks'] --- import kbnHapiMocksObj from './kbn_hapi_mocks.devdocs.json'; diff --git a/api_docs/kbn_home_sample_data_card.mdx b/api_docs/kbn_home_sample_data_card.mdx index 0ad6ecfa1134f..b1ce2043e27f1 100644 --- a/api_docs/kbn_home_sample_data_card.mdx +++ b/api_docs/kbn_home_sample_data_card.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-home-sample-data-card title: "@kbn/home-sample-data-card" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/home-sample-data-card plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/home-sample-data-card'] --- import kbnHomeSampleDataCardObj from './kbn_home_sample_data_card.devdocs.json'; diff --git a/api_docs/kbn_home_sample_data_tab.mdx b/api_docs/kbn_home_sample_data_tab.mdx index 859c50588c5d6..63510d74b009a 100644 --- a/api_docs/kbn_home_sample_data_tab.mdx +++ b/api_docs/kbn_home_sample_data_tab.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-home-sample-data-tab title: "@kbn/home-sample-data-tab" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/home-sample-data-tab plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/home-sample-data-tab'] --- import kbnHomeSampleDataTabObj from './kbn_home_sample_data_tab.devdocs.json'; diff --git a/api_docs/kbn_i18n.mdx b/api_docs/kbn_i18n.mdx index 8ee94c2d71b0e..ce7de735a1105 100644 --- a/api_docs/kbn_i18n.mdx +++ b/api_docs/kbn_i18n.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-i18n title: "@kbn/i18n" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/i18n plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/i18n'] --- import kbnI18nObj from './kbn_i18n.devdocs.json'; diff --git a/api_docs/kbn_import_resolver.mdx b/api_docs/kbn_import_resolver.mdx index c847655641fb9..a96adba4a09b2 100644 --- a/api_docs/kbn_import_resolver.mdx +++ b/api_docs/kbn_import_resolver.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-import-resolver title: "@kbn/import-resolver" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/import-resolver plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/import-resolver'] --- import kbnImportResolverObj from './kbn_import_resolver.devdocs.json'; diff --git a/api_docs/kbn_interpreter.mdx b/api_docs/kbn_interpreter.mdx index d9c5b743c7992..d35da6c7ae880 100644 --- a/api_docs/kbn_interpreter.mdx +++ b/api_docs/kbn_interpreter.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-interpreter title: "@kbn/interpreter" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/interpreter plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/interpreter'] --- import kbnInterpreterObj from './kbn_interpreter.devdocs.json'; diff --git a/api_docs/kbn_io_ts_utils.mdx b/api_docs/kbn_io_ts_utils.mdx index 35c6c024c30aa..623552a19ab96 100644 --- a/api_docs/kbn_io_ts_utils.mdx +++ b/api_docs/kbn_io_ts_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-io-ts-utils title: "@kbn/io-ts-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/io-ts-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/io-ts-utils'] --- import kbnIoTsUtilsObj from './kbn_io_ts_utils.devdocs.json'; diff --git a/api_docs/kbn_jest_serializers.mdx b/api_docs/kbn_jest_serializers.mdx index 4227de2378990..46b40beb8bf35 100644 --- a/api_docs/kbn_jest_serializers.mdx +++ b/api_docs/kbn_jest_serializers.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-jest-serializers title: "@kbn/jest-serializers" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/jest-serializers plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/jest-serializers'] --- import kbnJestSerializersObj from './kbn_jest_serializers.devdocs.json'; diff --git a/api_docs/kbn_journeys.devdocs.json b/api_docs/kbn_journeys.devdocs.json index d34c75a453efb..601334a03f8e8 100644 --- a/api_docs/kbn_journeys.devdocs.json +++ b/api_docs/kbn_journeys.devdocs.json @@ -792,7 +792,7 @@ "signature": [ "(step: ", "AnyStep", - ", screenshot: Buffer) => Promise" + ", screenshot: Buffer, fullscreenScreenshot: Buffer) => Promise" ], "path": "packages/kbn-journeys/journey/journey_screenshots.ts", "deprecated": false, @@ -827,6 +827,21 @@ "deprecated": false, "trackAdoption": false, "isRequired": true + }, + { + "parentPluginId": "@kbn/journeys", + "id": "def-server.JourneyScreenshots.addError.$3", + "type": "Object", + "tags": [], + "label": "fullscreenScreenshot", + "description": [], + "signature": [ + "Buffer" + ], + "path": "packages/kbn-journeys/journey/journey_screenshots.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true } ], "returnComment": [] @@ -841,7 +856,7 @@ "signature": [ "(step: ", "AnyStep", - ", screenshot: Buffer) => Promise" + ", screenshot: Buffer, fullscreenScreenshot: Buffer) => Promise" ], "path": "packages/kbn-journeys/journey/journey_screenshots.ts", "deprecated": false, @@ -876,6 +891,21 @@ "deprecated": false, "trackAdoption": false, "isRequired": true + }, + { + "parentPluginId": "@kbn/journeys", + "id": "def-server.JourneyScreenshots.addSuccess.$3", + "type": "Object", + "tags": [], + "label": "fullscreenScreenshot", + "description": [], + "signature": [ + "Buffer" + ], + "path": "packages/kbn-journeys/journey/journey_screenshots.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true } ], "returnComment": [] @@ -888,7 +918,7 @@ "label": "get", "description": [], "signature": [ - "() => { path: string; type: \"success\" | \"failure\"; title: string; filename: string; }[]" + "() => { path: string; fullscreenPath: string; type: \"success\" | \"failure\"; title: string; filename: string; fullscreenFilename: string; }[]" ], "path": "packages/kbn-journeys/journey/journey_screenshots.ts", "deprecated": false, diff --git a/api_docs/kbn_journeys.mdx b/api_docs/kbn_journeys.mdx index 39f179d7f006b..e9b4b290f7d14 100644 --- a/api_docs/kbn_journeys.mdx +++ b/api_docs/kbn_journeys.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-journeys title: "@kbn/journeys" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/journeys plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/journeys'] --- import kbnJourneysObj from './kbn_journeys.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Owner missing] for questions regarding this plugin. | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 62 | 0 | 57 | 5 | +| 64 | 0 | 59 | 5 | ## Server diff --git a/api_docs/kbn_kibana_manifest_schema.mdx b/api_docs/kbn_kibana_manifest_schema.mdx index aefca257ec51d..3f19d6bc0c359 100644 --- a/api_docs/kbn_kibana_manifest_schema.mdx +++ b/api_docs/kbn_kibana_manifest_schema.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-kibana-manifest-schema title: "@kbn/kibana-manifest-schema" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/kibana-manifest-schema plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/kibana-manifest-schema'] --- import kbnKibanaManifestSchemaObj from './kbn_kibana_manifest_schema.devdocs.json'; diff --git a/api_docs/kbn_logging.mdx b/api_docs/kbn_logging.mdx index e842c1eb7e347..da43bfec51c4d 100644 --- a/api_docs/kbn_logging.mdx +++ b/api_docs/kbn_logging.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-logging title: "@kbn/logging" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/logging plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/logging'] --- import kbnLoggingObj from './kbn_logging.devdocs.json'; diff --git a/api_docs/kbn_logging_mocks.mdx b/api_docs/kbn_logging_mocks.mdx index 3b27866609cf4..2770d7ccb6ac7 100644 --- a/api_docs/kbn_logging_mocks.mdx +++ b/api_docs/kbn_logging_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-logging-mocks title: "@kbn/logging-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/logging-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/logging-mocks'] --- import kbnLoggingMocksObj from './kbn_logging_mocks.devdocs.json'; diff --git a/api_docs/kbn_managed_vscode_config.mdx b/api_docs/kbn_managed_vscode_config.mdx index 3f639cd9df6de..83b9321c6a3f9 100644 --- a/api_docs/kbn_managed_vscode_config.mdx +++ b/api_docs/kbn_managed_vscode_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-managed-vscode-config title: "@kbn/managed-vscode-config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/managed-vscode-config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/managed-vscode-config'] --- import kbnManagedVscodeConfigObj from './kbn_managed_vscode_config.devdocs.json'; diff --git a/api_docs/kbn_mapbox_gl.mdx b/api_docs/kbn_mapbox_gl.mdx index 57ce7a27a5c6c..ae4854e96ac2a 100644 --- a/api_docs/kbn_mapbox_gl.mdx +++ b/api_docs/kbn_mapbox_gl.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-mapbox-gl title: "@kbn/mapbox-gl" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/mapbox-gl plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/mapbox-gl'] --- import kbnMapboxGlObj from './kbn_mapbox_gl.devdocs.json'; diff --git a/api_docs/kbn_ml_agg_utils.mdx b/api_docs/kbn_ml_agg_utils.mdx index 699d038a62b36..dd5f5c5ace183 100644 --- a/api_docs/kbn_ml_agg_utils.mdx +++ b/api_docs/kbn_ml_agg_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ml-agg-utils title: "@kbn/ml-agg-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ml-agg-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ml-agg-utils'] --- import kbnMlAggUtilsObj from './kbn_ml_agg_utils.devdocs.json'; diff --git a/api_docs/kbn_ml_is_populated_object.mdx b/api_docs/kbn_ml_is_populated_object.mdx index 2e93d4df6a7c0..4a750b0b7dfad 100644 --- a/api_docs/kbn_ml_is_populated_object.mdx +++ b/api_docs/kbn_ml_is_populated_object.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ml-is-populated-object title: "@kbn/ml-is-populated-object" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ml-is-populated-object plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ml-is-populated-object'] --- import kbnMlIsPopulatedObjectObj from './kbn_ml_is_populated_object.devdocs.json'; diff --git a/api_docs/kbn_ml_string_hash.mdx b/api_docs/kbn_ml_string_hash.mdx index e54522717c361..1702698262627 100644 --- a/api_docs/kbn_ml_string_hash.mdx +++ b/api_docs/kbn_ml_string_hash.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ml-string-hash title: "@kbn/ml-string-hash" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ml-string-hash plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ml-string-hash'] --- import kbnMlStringHashObj from './kbn_ml_string_hash.devdocs.json'; diff --git a/api_docs/kbn_monaco.mdx b/api_docs/kbn_monaco.mdx index 4cf3e42607ebc..987ec45f387a2 100644 --- a/api_docs/kbn_monaco.mdx +++ b/api_docs/kbn_monaco.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-monaco title: "@kbn/monaco" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/monaco plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/monaco'] --- import kbnMonacoObj from './kbn_monaco.devdocs.json'; diff --git a/api_docs/kbn_optimizer.mdx b/api_docs/kbn_optimizer.mdx index aa06f117f4ad3..ed7566b575b58 100644 --- a/api_docs/kbn_optimizer.mdx +++ b/api_docs/kbn_optimizer.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-optimizer title: "@kbn/optimizer" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/optimizer plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/optimizer'] --- import kbnOptimizerObj from './kbn_optimizer.devdocs.json'; diff --git a/api_docs/kbn_optimizer_webpack_helpers.mdx b/api_docs/kbn_optimizer_webpack_helpers.mdx index 07c0bcadb88c2..7c45eeef92b57 100644 --- a/api_docs/kbn_optimizer_webpack_helpers.mdx +++ b/api_docs/kbn_optimizer_webpack_helpers.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-optimizer-webpack-helpers title: "@kbn/optimizer-webpack-helpers" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/optimizer-webpack-helpers plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/optimizer-webpack-helpers'] --- import kbnOptimizerWebpackHelpersObj from './kbn_optimizer_webpack_helpers.devdocs.json'; diff --git a/api_docs/kbn_osquery_io_ts_types.mdx b/api_docs/kbn_osquery_io_ts_types.mdx index c7a1e479d8338..859b6a067644d 100644 --- a/api_docs/kbn_osquery_io_ts_types.mdx +++ b/api_docs/kbn_osquery_io_ts_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-osquery-io-ts-types title: "@kbn/osquery-io-ts-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/osquery-io-ts-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/osquery-io-ts-types'] --- import kbnOsqueryIoTsTypesObj from './kbn_osquery_io_ts_types.devdocs.json'; diff --git a/api_docs/kbn_performance_testing_dataset_extractor.mdx b/api_docs/kbn_performance_testing_dataset_extractor.mdx index 849a9f36eb3b5..aedd0101a45aa 100644 --- a/api_docs/kbn_performance_testing_dataset_extractor.mdx +++ b/api_docs/kbn_performance_testing_dataset_extractor.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-performance-testing-dataset-extractor title: "@kbn/performance-testing-dataset-extractor" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/performance-testing-dataset-extractor plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/performance-testing-dataset-extractor'] --- import kbnPerformanceTestingDatasetExtractorObj from './kbn_performance_testing_dataset_extractor.devdocs.json'; diff --git a/api_docs/kbn_plugin_generator.mdx b/api_docs/kbn_plugin_generator.mdx index a9ee3347d4153..bfd4b4e6b5afb 100644 --- a/api_docs/kbn_plugin_generator.mdx +++ b/api_docs/kbn_plugin_generator.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-plugin-generator title: "@kbn/plugin-generator" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/plugin-generator plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/plugin-generator'] --- import kbnPluginGeneratorObj from './kbn_plugin_generator.devdocs.json'; diff --git a/api_docs/kbn_plugin_helpers.mdx b/api_docs/kbn_plugin_helpers.mdx index be22071f32f0f..3ca9f9e155f16 100644 --- a/api_docs/kbn_plugin_helpers.mdx +++ b/api_docs/kbn_plugin_helpers.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-plugin-helpers title: "@kbn/plugin-helpers" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/plugin-helpers plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/plugin-helpers'] --- import kbnPluginHelpersObj from './kbn_plugin_helpers.devdocs.json'; diff --git a/api_docs/kbn_react_field.mdx b/api_docs/kbn_react_field.mdx index aaac08a4676bb..293fa51905454 100644 --- a/api_docs/kbn_react_field.mdx +++ b/api_docs/kbn_react_field.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-react-field title: "@kbn/react-field" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/react-field plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/react-field'] --- import kbnReactFieldObj from './kbn_react_field.devdocs.json'; diff --git a/api_docs/kbn_repo_source_classifier.mdx b/api_docs/kbn_repo_source_classifier.mdx index 5f065f4241db9..aaf5d45ea057c 100644 --- a/api_docs/kbn_repo_source_classifier.mdx +++ b/api_docs/kbn_repo_source_classifier.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-repo-source-classifier title: "@kbn/repo-source-classifier" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/repo-source-classifier plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/repo-source-classifier'] --- import kbnRepoSourceClassifierObj from './kbn_repo_source_classifier.devdocs.json'; diff --git a/api_docs/kbn_rule_data_utils.devdocs.json b/api_docs/kbn_rule_data_utils.devdocs.json index c30477647a1ce..2d6403bd41dfe 100644 --- a/api_docs/kbn_rule_data_utils.devdocs.json +++ b/api_docs/kbn_rule_data_utils.devdocs.json @@ -912,7 +912,7 @@ "label": "AlertConsumers", "description": [], "signature": [ - "\"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\" | \"infrastructure\"" + "\"infrastructure\" | \"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\"" ], "path": "packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts", "deprecated": false, @@ -1077,7 +1077,7 @@ "label": "TechnicalRuleDataFieldName", "description": [], "signature": [ - "\"tags\" | \"kibana\" | \"@timestamp\" | \"event.action\" | \"kibana.alert.rule.parameters\" | \"kibana.alert.rule.rule_type_id\" | \"kibana.alert.rule.consumer\" | \"kibana.alert.rule.producer\" | \"kibana.space_ids\" | \"kibana.alert.uuid\" | \"kibana.alert.instance.id\" | \"kibana.alert.start\" | \"kibana.alert.end\" | \"kibana.alert.duration.us\" | \"kibana.alert.severity\" | \"kibana.alert.status\" | \"kibana.version\" | \"ecs.version\" | \"kibana.alert.risk_score\" | \"kibana.alert.workflow_status\" | \"kibana.alert.workflow_user\" | \"kibana.alert.workflow_reason\" | \"kibana.alert.system_status\" | \"kibana.alert.action_group\" | \"kibana.alert.reason\" | \"kibana.alert.rule.author\" | \"kibana.alert.rule.category\" | \"kibana.alert.rule.uuid\" | \"kibana.alert.rule.created_at\" | \"kibana.alert.rule.created_by\" | \"kibana.alert.rule.description\" | \"kibana.alert.rule.enabled\" | \"kibana.alert.rule.execution.uuid\" | \"kibana.alert.rule.from\" | \"kibana.alert.rule.interval\" | \"kibana.alert.rule.license\" | \"kibana.alert.rule.name\" | \"kibana.alert.rule.note\" | \"kibana.alert.rule.references\" | \"kibana.alert.rule.rule_id\" | \"kibana.alert.rule.rule_name_override\" | \"kibana.alert.rule.tags\" | \"kibana.alert.rule.to\" | \"kibana.alert.rule.type\" | \"kibana.alert.rule.updated_at\" | \"kibana.alert.rule.updated_by\" | \"kibana.alert.rule.version\" | \"event.kind\" | \"event.module\" | \"kibana.alert.evaluation.threshold\" | \"kibana.alert.evaluation.value\" | \"kibana.alert.building_block_type\" | \"kibana.alert.rule.exceptions_list\" | \"kibana.alert.rule.namespace\" | \"kibana.alert\" | \"kibana.alert.rule\"" + "\"tags\" | \"kibana\" | \"@timestamp\" | \"kibana.alert.rule.rule_type_id\" | \"kibana.alert.rule.consumer\" | \"event.action\" | \"kibana.alert.rule.execution.uuid\" | \"kibana.alert.rule.parameters\" | \"kibana.alert.rule.producer\" | \"kibana.space_ids\" | \"kibana.alert.uuid\" | \"kibana.alert.instance.id\" | \"kibana.alert.start\" | \"kibana.alert.end\" | \"kibana.alert.duration.us\" | \"kibana.alert.severity\" | \"kibana.alert.status\" | \"kibana.version\" | \"ecs.version\" | \"kibana.alert.risk_score\" | \"kibana.alert.workflow_status\" | \"kibana.alert.workflow_user\" | \"kibana.alert.workflow_reason\" | \"kibana.alert.system_status\" | \"kibana.alert.action_group\" | \"kibana.alert.reason\" | \"kibana.alert.rule.author\" | \"kibana.alert.rule.category\" | \"kibana.alert.rule.uuid\" | \"kibana.alert.rule.created_at\" | \"kibana.alert.rule.created_by\" | \"kibana.alert.rule.description\" | \"kibana.alert.rule.enabled\" | \"kibana.alert.rule.from\" | \"kibana.alert.rule.interval\" | \"kibana.alert.rule.license\" | \"kibana.alert.rule.name\" | \"kibana.alert.rule.note\" | \"kibana.alert.rule.references\" | \"kibana.alert.rule.rule_id\" | \"kibana.alert.rule.rule_name_override\" | \"kibana.alert.rule.tags\" | \"kibana.alert.rule.to\" | \"kibana.alert.rule.type\" | \"kibana.alert.rule.updated_at\" | \"kibana.alert.rule.updated_by\" | \"kibana.alert.rule.version\" | \"event.kind\" | \"event.module\" | \"kibana.alert.evaluation.threshold\" | \"kibana.alert.evaluation.value\" | \"kibana.alert.building_block_type\" | \"kibana.alert.rule.exceptions_list\" | \"kibana.alert.rule.namespace\" | \"kibana.alert\" | \"kibana.alert.rule\"" ], "path": "packages/kbn-rule-data-utils/src/technical_field_names.ts", "deprecated": false, @@ -1107,7 +1107,7 @@ "label": "ValidFeatureId", "description": [], "signature": [ - "\"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\" | \"infrastructure\"" + "\"infrastructure\" | \"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\"" ], "path": "packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts", "deprecated": false, diff --git a/api_docs/kbn_rule_data_utils.mdx b/api_docs/kbn_rule_data_utils.mdx index 20d2b0fa67d73..4f65db7503fc7 100644 --- a/api_docs/kbn_rule_data_utils.mdx +++ b/api_docs/kbn_rule_data_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-rule-data-utils title: "@kbn/rule-data-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/rule-data-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/rule-data-utils'] --- import kbnRuleDataUtilsObj from './kbn_rule_data_utils.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_autocomplete.mdx b/api_docs/kbn_securitysolution_autocomplete.mdx index 231bccc342205..5a9078575773a 100644 --- a/api_docs/kbn_securitysolution_autocomplete.mdx +++ b/api_docs/kbn_securitysolution_autocomplete.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-autocomplete title: "@kbn/securitysolution-autocomplete" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-autocomplete plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-autocomplete'] --- import kbnSecuritysolutionAutocompleteObj from './kbn_securitysolution_autocomplete.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_es_utils.mdx b/api_docs/kbn_securitysolution_es_utils.mdx index b6eabe236bc52..dc5fcdbd1d0f1 100644 --- a/api_docs/kbn_securitysolution_es_utils.mdx +++ b/api_docs/kbn_securitysolution_es_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-es-utils title: "@kbn/securitysolution-es-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-es-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-es-utils'] --- import kbnSecuritysolutionEsUtilsObj from './kbn_securitysolution_es_utils.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_exception_list_components.devdocs.json b/api_docs/kbn_securitysolution_exception_list_components.devdocs.json new file mode 100644 index 0000000000000..97b711804af12 --- /dev/null +++ b/api_docs/kbn_securitysolution_exception_list_components.devdocs.json @@ -0,0 +1,1209 @@ +{ + "id": "@kbn/securitysolution-exception-list-components", + "client": { + "classes": [], + "functions": [], + "interfaces": [], + "enums": [], + "misc": [], + "objects": [] + }, + "server": { + "classes": [], + "functions": [], + "interfaces": [], + "enums": [], + "misc": [], + "objects": [] + }, + "common": { + "classes": [], + "functions": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.EmptyViewerState", + "type": "Function", + "tags": [], + "label": "EmptyViewerState", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.EmptyViewerState.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCard", + "type": "Function", + "tags": [], + "label": "ExceptionItemCard", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionItemProps", + "text": "ExceptionItemProps" + }, + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCard.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardComments", + "type": "Function", + "tags": [], + "label": "ExceptionItemCardComments", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionItemCardCommentsProps", + "text": "ExceptionItemCardCommentsProps" + }, + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardComments.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardConditions", + "type": "Function", + "tags": [], + "label": "ExceptionItemCardConditions", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + "CriteriaConditionsProps", + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardConditions.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeader", + "type": "Function", + "tags": [], + "label": "ExceptionItemCardHeader", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionItemCardHeaderProps", + "text": "ExceptionItemCardHeaderProps" + }, + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeader.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfo", + "type": "Function", + "tags": [], + "label": "ExceptionItemCardMetaInfo", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionItemCardMetaInfoProps", + "text": "ExceptionItemCardMetaInfoProps" + }, + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfo.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItems", + "type": "Function", + "tags": [], + "label": "ExceptionItems", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItems.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.Pagination", + "type": "Function", + "tags": [], + "label": "Pagination", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.PaginationProps", + "text": "PaginationProps" + }, + ">" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.Pagination.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.SearchBar", + "type": "Function", + "tags": [], + "label": "SearchBar", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.SearchBar.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ValueWithSpaceWarning", + "type": "Function", + "tags": [], + "label": "ValueWithSpaceWarning", + "description": [], + "signature": [ + "({ value, tooltipIconType, tooltipIconText, }: React.PropsWithChildren) => JSX.Element | null" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ValueWithSpaceWarning.$1", + "type": "CompoundType", + "tags": [], + "label": "{\n value,\n tooltipIconType = 'iInCircle',\n tooltipIconText,\n}", + "description": [], + "signature": [ + "React.PropsWithChildren" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + } + ], + "interfaces": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardCommentsProps", + "type": "Interface", + "tags": [], + "label": "ExceptionItemCardCommentsProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardCommentsProps.comments", + "type": "Array", + "tags": [], + "label": "comments", + "description": [], + "signature": [ + "EuiCommentProps", + "[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeaderProps", + "type": "Interface", + "tags": [], + "label": "ExceptionItemCardHeaderProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeaderProps.item", + "type": "Object", + "tags": [], + "label": "item", + "description": [], + "signature": [ + "{ _version: string | undefined; comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]; created_at: string; created_by: string; description: string; entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; } | { field: string; list: { id: string; type: \"boolean\" | \"date\" | \"keyword\" | \"ip\" | \"text\" | \"geo_point\" | \"geo_shape\" | \"date_nanos\" | \"long\" | \"double\" | \"date_range\" | \"ip_range\" | \"shape\" | \"short\" | \"binary\" | \"float\" | \"half_float\" | \"integer\" | \"byte\" | \"long_range\" | \"integer_range\" | \"float_range\" | \"double_range\"; }; operator: \"excluded\" | \"included\"; type: \"list\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; })[]; field: string; type: \"nested\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"wildcard\"; value: string; })[]; id: string; item_id: string; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"simple\"; updated_at: string; updated_by: string; }" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeaderProps.actions", + "type": "Array", + "tags": [], + "label": "actions", + "description": [], + "signature": [ + "{ key: string; icon: string; label: string | boolean; onClick: () => void; }[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeaderProps.disableActions", + "type": "CompoundType", + "tags": [], + "label": "disableActions", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardHeaderProps.dataTestSubj", + "type": "string", + "tags": [], + "label": "dataTestSubj", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps", + "type": "Interface", + "tags": [], + "label": "ExceptionItemCardMetaInfoProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps.item", + "type": "Object", + "tags": [], + "label": "item", + "description": [], + "signature": [ + "{ _version: string | undefined; comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]; created_at: string; created_by: string; description: string; entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; } | { field: string; list: { id: string; type: \"boolean\" | \"date\" | \"keyword\" | \"ip\" | \"text\" | \"geo_point\" | \"geo_shape\" | \"date_nanos\" | \"long\" | \"double\" | \"date_range\" | \"ip_range\" | \"shape\" | \"short\" | \"binary\" | \"float\" | \"half_float\" | \"integer\" | \"byte\" | \"long_range\" | \"integer_range\" | \"float_range\" | \"double_range\"; }; operator: \"excluded\" | \"included\"; type: \"list\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; })[]; field: string; type: \"nested\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"wildcard\"; value: string; })[]; id: string; item_id: string; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"simple\"; updated_at: string; updated_by: string; }" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps.references", + "type": "Array", + "tags": [], + "label": "references", + "description": [], + "signature": [ + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.RuleReference", + "text": "RuleReference" + }, + "[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps.dataTestSubj", + "type": "string", + "tags": [], + "label": "dataTestSubj", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps.formattedDateComponent", + "type": "CompoundType", + "tags": [], + "label": "formattedDateComponent", + "description": [], + "signature": [ + "\"symbol\" | \"object\" | React.ComponentType | \"body\" | \"path\" | \"circle\" | \"filter\" | \"data\" | \"line\" | \"area\" | \"time\" | \"label\" | \"legend\" | \"image\" | \"link\" | \"menu\" | \"stop\" | \"base\" | \"text\" | \"title\" | \"s\" | \"small\" | \"svg\" | \"meta\" | \"script\" | \"summary\" | \"source\" | \"desc\" | \"q\" | \"pattern\" | \"mask\" | \"input\" | \"slot\" | \"style\" | \"head\" | \"section\" | \"big\" | \"sub\" | \"sup\" | \"animate\" | \"progress\" | \"view\" | \"output\" | \"var\" | \"map\" | \"html\" | \"a\" | \"img\" | \"audio\" | \"form\" | \"main\" | \"abbr\" | \"address\" | \"article\" | \"aside\" | \"b\" | \"bdi\" | \"bdo\" | \"blockquote\" | \"br\" | \"button\" | \"canvas\" | \"caption\" | \"cite\" | \"code\" | \"col\" | \"colgroup\" | \"datalist\" | \"dd\" | \"del\" | \"details\" | \"dfn\" | \"dialog\" | \"div\" | \"dl\" | \"dt\" | \"em\" | \"embed\" | \"fieldset\" | \"figcaption\" | \"figure\" | \"footer\" | \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"header\" | \"hgroup\" | \"hr\" | \"i\" | \"iframe\" | \"ins\" | \"kbd\" | \"keygen\" | \"li\" | \"mark\" | \"menuitem\" | \"meter\" | \"nav\" | \"noindex\" | \"noscript\" | \"ol\" | \"optgroup\" | \"option\" | \"p\" | \"param\" | \"picture\" | \"pre\" | \"rp\" | \"rt\" | \"ruby\" | \"samp\" | \"select\" | \"span\" | \"strong\" | \"table\" | \"template\" | \"tbody\" | \"td\" | \"textarea\" | \"tfoot\" | \"th\" | \"thead\" | \"tr\" | \"track\" | \"u\" | \"ul\" | \"video\" | \"wbr\" | \"webview\" | \"animateMotion\" | \"animateTransform\" | \"clipPath\" | \"defs\" | \"ellipse\" | \"feBlend\" | \"feColorMatrix\" | \"feComponentTransfer\" | \"feComposite\" | \"feConvolveMatrix\" | \"feDiffuseLighting\" | \"feDisplacementMap\" | \"feDistantLight\" | \"feDropShadow\" | \"feFlood\" | \"feFuncA\" | \"feFuncB\" | \"feFuncG\" | \"feFuncR\" | \"feGaussianBlur\" | \"feImage\" | \"feMerge\" | \"feMergeNode\" | \"feMorphology\" | \"feOffset\" | \"fePointLight\" | \"feSpecularLighting\" | \"feSpotLight\" | \"feTile\" | \"feTurbulence\" | \"foreignObject\" | \"g\" | \"linearGradient\" | \"marker\" | \"metadata\" | \"mpath\" | \"polygon\" | \"polyline\" | \"radialGradient\" | \"rect\" | \"switch\" | \"textPath\" | \"tspan\" | \"use\"" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemCardMetaInfoProps.securityLinkAnchorComponent", + "type": "CompoundType", + "tags": [], + "label": "securityLinkAnchorComponent", + "description": [], + "signature": [ + "\"symbol\" | \"object\" | React.ComponentType | \"body\" | \"path\" | \"circle\" | \"filter\" | \"data\" | \"line\" | \"area\" | \"time\" | \"label\" | \"legend\" | \"image\" | \"link\" | \"menu\" | \"stop\" | \"base\" | \"text\" | \"title\" | \"s\" | \"small\" | \"svg\" | \"meta\" | \"script\" | \"summary\" | \"source\" | \"desc\" | \"q\" | \"pattern\" | \"mask\" | \"input\" | \"slot\" | \"style\" | \"head\" | \"section\" | \"big\" | \"sub\" | \"sup\" | \"animate\" | \"progress\" | \"view\" | \"output\" | \"var\" | \"map\" | \"html\" | \"a\" | \"img\" | \"audio\" | \"form\" | \"main\" | \"abbr\" | \"address\" | \"article\" | \"aside\" | \"b\" | \"bdi\" | \"bdo\" | \"blockquote\" | \"br\" | \"button\" | \"canvas\" | \"caption\" | \"cite\" | \"code\" | \"col\" | \"colgroup\" | \"datalist\" | \"dd\" | \"del\" | \"details\" | \"dfn\" | \"dialog\" | \"div\" | \"dl\" | \"dt\" | \"em\" | \"embed\" | \"fieldset\" | \"figcaption\" | \"figure\" | \"footer\" | \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"header\" | \"hgroup\" | \"hr\" | \"i\" | \"iframe\" | \"ins\" | \"kbd\" | \"keygen\" | \"li\" | \"mark\" | \"menuitem\" | \"meter\" | \"nav\" | \"noindex\" | \"noscript\" | \"ol\" | \"optgroup\" | \"option\" | \"p\" | \"param\" | \"picture\" | \"pre\" | \"rp\" | \"rt\" | \"ruby\" | \"samp\" | \"select\" | \"span\" | \"strong\" | \"table\" | \"template\" | \"tbody\" | \"td\" | \"textarea\" | \"tfoot\" | \"th\" | \"thead\" | \"tr\" | \"track\" | \"u\" | \"ul\" | \"video\" | \"wbr\" | \"webview\" | \"animateMotion\" | \"animateTransform\" | \"clipPath\" | \"defs\" | \"ellipse\" | \"feBlend\" | \"feColorMatrix\" | \"feComponentTransfer\" | \"feComposite\" | \"feConvolveMatrix\" | \"feDiffuseLighting\" | \"feDisplacementMap\" | \"feDistantLight\" | \"feDropShadow\" | \"feFlood\" | \"feFuncA\" | \"feFuncB\" | \"feFuncG\" | \"feFuncR\" | \"feGaussianBlur\" | \"feImage\" | \"feMerge\" | \"feMergeNode\" | \"feMorphology\" | \"feOffset\" | \"fePointLight\" | \"feSpecularLighting\" | \"feSpotLight\" | \"feTile\" | \"feTurbulence\" | \"foreignObject\" | \"g\" | \"linearGradient\" | \"marker\" | \"metadata\" | \"mpath\" | \"polygon\" | \"polyline\" | \"radialGradient\" | \"rect\" | \"switch\" | \"textPath\" | \"tspan\" | \"use\"" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps", + "type": "Interface", + "tags": [], + "label": "ExceptionItemProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.dataTestSubj", + "type": "string", + "tags": [], + "label": "dataTestSubj", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.disableActions", + "type": "CompoundType", + "tags": [], + "label": "disableActions", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.exceptionItem", + "type": "Object", + "tags": [], + "label": "exceptionItem", + "description": [], + "signature": [ + "{ _version: string | undefined; comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]; created_at: string; created_by: string; description: string; entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; } | { field: string; list: { id: string; type: \"boolean\" | \"date\" | \"keyword\" | \"ip\" | \"text\" | \"geo_point\" | \"geo_shape\" | \"date_nanos\" | \"long\" | \"double\" | \"date_range\" | \"ip_range\" | \"shape\" | \"short\" | \"binary\" | \"float\" | \"half_float\" | \"integer\" | \"byte\" | \"long_range\" | \"integer_range\" | \"float_range\" | \"double_range\"; }; operator: \"excluded\" | \"included\"; type: \"list\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; })[]; field: string; type: \"nested\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"wildcard\"; value: string; })[]; id: string; item_id: string; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"simple\"; updated_at: string; updated_by: string; }" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.listType", + "type": "Enum", + "tags": [], + "label": "listType", + "description": [], + "signature": [ + "ExceptionListTypeEnum" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.ruleReferences", + "type": "Array", + "tags": [], + "label": "ruleReferences", + "description": [], + "signature": [ + "any[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.editActionLabel", + "type": "string", + "tags": [], + "label": "editActionLabel", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.deleteActionLabel", + "type": "string", + "tags": [], + "label": "deleteActionLabel", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.securityLinkAnchorComponent", + "type": "CompoundType", + "tags": [], + "label": "securityLinkAnchorComponent", + "description": [], + "signature": [ + "\"symbol\" | \"object\" | React.ComponentType | \"body\" | \"path\" | \"circle\" | \"filter\" | \"data\" | \"line\" | \"area\" | \"time\" | \"label\" | \"legend\" | \"image\" | \"link\" | \"menu\" | \"stop\" | \"base\" | \"text\" | \"title\" | \"s\" | \"small\" | \"svg\" | \"meta\" | \"script\" | \"summary\" | \"source\" | \"desc\" | \"q\" | \"pattern\" | \"mask\" | \"input\" | \"slot\" | \"style\" | \"head\" | \"section\" | \"big\" | \"sub\" | \"sup\" | \"animate\" | \"progress\" | \"view\" | \"output\" | \"var\" | \"map\" | \"html\" | \"a\" | \"img\" | \"audio\" | \"form\" | \"main\" | \"abbr\" | \"address\" | \"article\" | \"aside\" | \"b\" | \"bdi\" | \"bdo\" | \"blockquote\" | \"br\" | \"button\" | \"canvas\" | \"caption\" | \"cite\" | \"code\" | \"col\" | \"colgroup\" | \"datalist\" | \"dd\" | \"del\" | \"details\" | \"dfn\" | \"dialog\" | \"div\" | \"dl\" | \"dt\" | \"em\" | \"embed\" | \"fieldset\" | \"figcaption\" | \"figure\" | \"footer\" | \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"header\" | \"hgroup\" | \"hr\" | \"i\" | \"iframe\" | \"ins\" | \"kbd\" | \"keygen\" | \"li\" | \"mark\" | \"menuitem\" | \"meter\" | \"nav\" | \"noindex\" | \"noscript\" | \"ol\" | \"optgroup\" | \"option\" | \"p\" | \"param\" | \"picture\" | \"pre\" | \"rp\" | \"rt\" | \"ruby\" | \"samp\" | \"select\" | \"span\" | \"strong\" | \"table\" | \"template\" | \"tbody\" | \"td\" | \"textarea\" | \"tfoot\" | \"th\" | \"thead\" | \"tr\" | \"track\" | \"u\" | \"ul\" | \"video\" | \"wbr\" | \"webview\" | \"animateMotion\" | \"animateTransform\" | \"clipPath\" | \"defs\" | \"ellipse\" | \"feBlend\" | \"feColorMatrix\" | \"feComponentTransfer\" | \"feComposite\" | \"feConvolveMatrix\" | \"feDiffuseLighting\" | \"feDisplacementMap\" | \"feDistantLight\" | \"feDropShadow\" | \"feFlood\" | \"feFuncA\" | \"feFuncB\" | \"feFuncG\" | \"feFuncR\" | \"feGaussianBlur\" | \"feImage\" | \"feMerge\" | \"feMergeNode\" | \"feMorphology\" | \"feOffset\" | \"fePointLight\" | \"feSpecularLighting\" | \"feSpotLight\" | \"feTile\" | \"feTurbulence\" | \"foreignObject\" | \"g\" | \"linearGradient\" | \"marker\" | \"metadata\" | \"mpath\" | \"polygon\" | \"polyline\" | \"radialGradient\" | \"rect\" | \"switch\" | \"textPath\" | \"tspan\" | \"use\"" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.formattedDateComponent", + "type": "CompoundType", + "tags": [], + "label": "formattedDateComponent", + "description": [], + "signature": [ + "\"symbol\" | \"object\" | React.ComponentType | \"body\" | \"path\" | \"circle\" | \"filter\" | \"data\" | \"line\" | \"area\" | \"time\" | \"label\" | \"legend\" | \"image\" | \"link\" | \"menu\" | \"stop\" | \"base\" | \"text\" | \"title\" | \"s\" | \"small\" | \"svg\" | \"meta\" | \"script\" | \"summary\" | \"source\" | \"desc\" | \"q\" | \"pattern\" | \"mask\" | \"input\" | \"slot\" | \"style\" | \"head\" | \"section\" | \"big\" | \"sub\" | \"sup\" | \"animate\" | \"progress\" | \"view\" | \"output\" | \"var\" | \"map\" | \"html\" | \"a\" | \"img\" | \"audio\" | \"form\" | \"main\" | \"abbr\" | \"address\" | \"article\" | \"aside\" | \"b\" | \"bdi\" | \"bdo\" | \"blockquote\" | \"br\" | \"button\" | \"canvas\" | \"caption\" | \"cite\" | \"code\" | \"col\" | \"colgroup\" | \"datalist\" | \"dd\" | \"del\" | \"details\" | \"dfn\" | \"dialog\" | \"div\" | \"dl\" | \"dt\" | \"em\" | \"embed\" | \"fieldset\" | \"figcaption\" | \"figure\" | \"footer\" | \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"header\" | \"hgroup\" | \"hr\" | \"i\" | \"iframe\" | \"ins\" | \"kbd\" | \"keygen\" | \"li\" | \"mark\" | \"menuitem\" | \"meter\" | \"nav\" | \"noindex\" | \"noscript\" | \"ol\" | \"optgroup\" | \"option\" | \"p\" | \"param\" | \"picture\" | \"pre\" | \"rp\" | \"rt\" | \"ruby\" | \"samp\" | \"select\" | \"span\" | \"strong\" | \"table\" | \"template\" | \"tbody\" | \"td\" | \"textarea\" | \"tfoot\" | \"th\" | \"thead\" | \"tr\" | \"track\" | \"u\" | \"ul\" | \"video\" | \"wbr\" | \"webview\" | \"animateMotion\" | \"animateTransform\" | \"clipPath\" | \"defs\" | \"ellipse\" | \"feBlend\" | \"feColorMatrix\" | \"feComponentTransfer\" | \"feComposite\" | \"feConvolveMatrix\" | \"feDiffuseLighting\" | \"feDisplacementMap\" | \"feDistantLight\" | \"feDropShadow\" | \"feFlood\" | \"feFuncA\" | \"feFuncB\" | \"feFuncG\" | \"feFuncR\" | \"feGaussianBlur\" | \"feImage\" | \"feMerge\" | \"feMergeNode\" | \"feMorphology\" | \"feOffset\" | \"fePointLight\" | \"feSpecularLighting\" | \"feSpotLight\" | \"feTile\" | \"feTurbulence\" | \"foreignObject\" | \"g\" | \"linearGradient\" | \"marker\" | \"metadata\" | \"mpath\" | \"polygon\" | \"polyline\" | \"radialGradient\" | \"rect\" | \"switch\" | \"textPath\" | \"tspan\" | \"use\"" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.getFormattedComments", + "type": "Function", + "tags": [], + "label": "getFormattedComments", + "description": [], + "signature": [ + "(comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]) => ", + "EuiCommentProps", + "[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.getFormattedComments.$1", + "type": "Array", + "tags": [], + "label": "comments", + "description": [], + "signature": [ + "({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.onDeleteException", + "type": "Function", + "tags": [], + "label": "onDeleteException", + "description": [], + "signature": [ + "(arg: ", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionListItemIdentifiers", + "text": "ExceptionListItemIdentifiers" + }, + ") => void" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.onDeleteException.$1", + "type": "Object", + "tags": [], + "label": "arg", + "description": [], + "signature": [ + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.ExceptionListItemIdentifiers", + "text": "ExceptionListItemIdentifiers" + } + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.onEditException", + "type": "Function", + "tags": [], + "label": "onEditException", + "description": [], + "signature": [ + "(item: { _version: string | undefined; comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]; created_at: string; created_by: string; description: string; entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; } | { field: string; list: { id: string; type: \"boolean\" | \"date\" | \"keyword\" | \"ip\" | \"text\" | \"geo_point\" | \"geo_shape\" | \"date_nanos\" | \"long\" | \"double\" | \"date_range\" | \"ip_range\" | \"shape\" | \"short\" | \"binary\" | \"float\" | \"half_float\" | \"integer\" | \"byte\" | \"long_range\" | \"integer_range\" | \"float_range\" | \"double_range\"; }; operator: \"excluded\" | \"included\"; type: \"list\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; })[]; field: string; type: \"nested\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"wildcard\"; value: string; })[]; id: string; item_id: string; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"simple\"; updated_at: string; updated_by: string; }) => void" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionItemProps.onEditException.$1", + "type": "Object", + "tags": [], + "label": "item", + "description": [], + "signature": [ + "{ _version: string | undefined; comments: ({ comment: string; created_at: string; created_by: string; id: string; } & { updated_at?: string | undefined; updated_by?: string | undefined; })[]; created_at: string; created_by: string; description: string; entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; } | { field: string; list: { id: string; type: \"boolean\" | \"date\" | \"keyword\" | \"ip\" | \"text\" | \"geo_point\" | \"geo_shape\" | \"date_nanos\" | \"long\" | \"double\" | \"date_range\" | \"ip_range\" | \"shape\" | \"short\" | \"binary\" | \"float\" | \"half_float\" | \"integer\" | \"byte\" | \"long_range\" | \"integer_range\" | \"float_range\" | \"double_range\"; }; operator: \"excluded\" | \"included\"; type: \"list\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { entries: ({ field: string; operator: \"excluded\" | \"included\"; type: \"exists\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match\"; value: string; } | { field: string; operator: \"excluded\" | \"included\"; type: \"match_any\"; value: string[]; })[]; field: string; type: \"nested\"; } | { field: string; operator: \"excluded\" | \"included\"; type: \"wildcard\"; value: string; })[]; id: string; item_id: string; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"simple\"; updated_at: string; updated_by: string; }" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListItemIdentifiers", + "type": "Interface", + "tags": [], + "label": "ExceptionListItemIdentifiers", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListItemIdentifiers.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListItemIdentifiers.name", + "type": "string", + "tags": [], + "label": "name", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListItemIdentifiers.namespaceType", + "type": "CompoundType", + "tags": [], + "label": "namespaceType", + "description": [], + "signature": [ + "\"single\" | \"agnostic\"" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListSummaryProps", + "type": "Interface", + "tags": [], + "label": "ExceptionListSummaryProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListSummaryProps.pagination", + "type": "Object", + "tags": [], + "label": "pagination", + "description": [], + "signature": [ + "Pagination" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ExceptionListSummaryProps.lastUpdated", + "type": "CompoundType", + "tags": [], + "label": "lastUpdated", + "description": [], + "signature": [ + "string | number | null" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.GetExceptionItemProps", + "type": "Interface", + "tags": [], + "label": "GetExceptionItemProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.GetExceptionItemProps.pagination", + "type": "Object", + "tags": [], + "label": "pagination", + "description": [], + "signature": [ + "Pagination", + " | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.GetExceptionItemProps.search", + "type": "string", + "tags": [], + "label": "search", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.GetExceptionItemProps.filters", + "type": "string", + "tags": [], + "label": "filters", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps", + "type": "Interface", + "tags": [], + "label": "PaginationProps", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps.dataTestSubj", + "type": "string", + "tags": [], + "label": "dataTestSubj", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps.ariaLabel", + "type": "string", + "tags": [], + "label": "ariaLabel", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps.pagination", + "type": "Object", + "tags": [], + "label": "pagination", + "description": [], + "signature": [ + "Pagination" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps.onPaginationChange", + "type": "Function", + "tags": [], + "label": "onPaginationChange", + "description": [], + "signature": [ + "(arg: ", + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.GetExceptionItemProps", + "text": "GetExceptionItemProps" + }, + ") => void" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.PaginationProps.onPaginationChange.$1", + "type": "Object", + "tags": [], + "label": "arg", + "description": [], + "signature": [ + { + "pluginId": "@kbn/securitysolution-exception-list-components", + "scope": "common", + "docId": "kibKbnSecuritysolutionExceptionListComponentsPluginApi", + "section": "def-common.GetExceptionItemProps", + "text": "GetExceptionItemProps" + } + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReference", + "type": "Interface", + "tags": [], + "label": "RuleReference", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReference.name", + "type": "string", + "tags": [], + "label": "name", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReference.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReference.ruleId", + "type": "string", + "tags": [], + "label": "ruleId", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReference.exceptionLists", + "type": "Array", + "tags": [], + "label": "exceptionLists", + "description": [], + "signature": [ + "{ _version: string | undefined; created_at: string; created_by: string; description: string; id: string; immutable: boolean; list_id: string; meta: object | undefined; name: string; namespace_type: \"single\" | \"agnostic\"; os_types: (\"windows\" | \"linux\" | \"macos\")[]; tags: string[]; tie_breaker_id: string; type: \"endpoint\" | \"detection\" | \"rule_default\" | \"endpoint_trusted_apps\" | \"endpoint_events\" | \"endpoint_host_isolation_exceptions\" | \"endpoint_blocklists\"; updated_at: string; updated_by: string; version: number; }[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReferences", + "type": "Interface", + "tags": [], + "label": "RuleReferences", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.RuleReferences.Unnamed", + "type": "IndexSignature", + "tags": [], + "label": "[key: string]: any[]", + "description": [], + "signature": [ + "[key: string]: any[]" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + } + ], + "enums": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ListTypeText", + "type": "Enum", + "tags": [], + "label": "ListTypeText", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ViewerStatus", + "type": "Enum", + "tags": [], + "label": "ViewerStatus", + "description": [], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + } + ], + "misc": [ + { + "parentPluginId": "@kbn/securitysolution-exception-list-components", + "id": "def-common.ViewerFlyoutName", + "type": "Type", + "tags": [], + "label": "ViewerFlyoutName", + "description": [], + "signature": [ + "\"addException\" | \"editException\" | null" + ], + "path": "packages/kbn-securitysolution-exception-list-components/src/types/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + } + ], + "objects": [] + } +} \ No newline at end of file diff --git a/api_docs/kbn_securitysolution_exception_list_components.mdx b/api_docs/kbn_securitysolution_exception_list_components.mdx new file mode 100644 index 0000000000000..1bcc5017dfc5e --- /dev/null +++ b/api_docs/kbn_securitysolution_exception_list_components.mdx @@ -0,0 +1,39 @@ +--- +#### +#### This document is auto-generated and is meant to be viewed inside our experimental, new docs system. +#### Reach out in #docs-engineering for more info. +#### +id: kibKbnSecuritysolutionExceptionListComponentsPluginApi +slug: /kibana-dev-docs/api/kbn-securitysolution-exception-list-components +title: "@kbn/securitysolution-exception-list-components" +image: https://source.unsplash.com/400x175/?github +description: API docs for the @kbn/securitysolution-exception-list-components plugin +date: 2022-09-29 +tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-exception-list-components'] +--- +import kbnSecuritysolutionExceptionListComponentsObj from './kbn_securitysolution_exception_list_components.devdocs.json'; + + + +Contact [Owner missing] for questions regarding this plugin. + +**Code health stats** + +| Public API count | Any count | Items lacking comments | Missing exports | +|-------------------|-----------|------------------------|-----------------| +| 76 | 0 | 67 | 1 | + +## Common + +### Functions + + +### Interfaces + + +### Enums + + +### Consts, variables and types + + diff --git a/api_docs/kbn_securitysolution_hook_utils.mdx b/api_docs/kbn_securitysolution_hook_utils.mdx index 497c2c3d7d8bd..a22707f2957be 100644 --- a/api_docs/kbn_securitysolution_hook_utils.mdx +++ b/api_docs/kbn_securitysolution_hook_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-hook-utils title: "@kbn/securitysolution-hook-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-hook-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-hook-utils'] --- import kbnSecuritysolutionHookUtilsObj from './kbn_securitysolution_hook_utils.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_io_ts_alerting_types.devdocs.json b/api_docs/kbn_securitysolution_io_ts_alerting_types.devdocs.json index e313879791dd2..f9869d88c91cd 100644 --- a/api_docs/kbn_securitysolution_io_ts_alerting_types.devdocs.json +++ b/api_docs/kbn_securitysolution_io_ts_alerting_types.devdocs.json @@ -227,7 +227,7 @@ "label": "Language", "description": [], "signature": [ - "\"eql\" | \"kuery\" | \"lucene\"" + "\"eql\" | \"lucene\" | \"kuery\"" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts", "deprecated": false, @@ -242,7 +242,7 @@ "label": "LanguageOrUndefined", "description": [], "signature": [ - "\"eql\" | \"kuery\" | \"lucene\" | undefined" + "\"eql\" | \"lucene\" | \"kuery\" | undefined" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts", "deprecated": false, @@ -660,7 +660,7 @@ "label": "ThreatLanguage", "description": [], "signature": [ - "\"eql\" | \"kuery\" | \"lucene\" | undefined" + "\"eql\" | \"lucene\" | \"kuery\" | undefined" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts", "deprecated": false, @@ -675,7 +675,7 @@ "label": "ThreatLanguageOrUndefined", "description": [], "signature": [ - "\"eql\" | \"kuery\" | \"lucene\" | undefined" + "\"eql\" | \"lucene\" | \"kuery\" | undefined" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts", "deprecated": false, @@ -877,21 +877,6 @@ "trackAdoption": false, "initialIsOpen": false }, - { - "parentPluginId": "@kbn/securitysolution-io-ts-alerting-types", - "id": "def-common.ThrottleOrUndefinedOrNull", - "type": "Type", - "tags": [], - "label": "ThrottleOrUndefinedOrNull", - "description": [], - "signature": [ - "string | null | undefined" - ], - "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, { "parentPluginId": "@kbn/securitysolution-io-ts-alerting-types", "id": "def-common.Type", @@ -1383,24 +1368,6 @@ "trackAdoption": false, "initialIsOpen": false }, - { - "parentPluginId": "@kbn/securitysolution-io-ts-alerting-types", - "id": "def-common.DefaultThrottleNull", - "type": "Object", - "tags": [], - "label": "DefaultThrottleNull", - "description": [ - "\nTypes the DefaultThrottleNull as:\n - If null or undefined, then a null will be set" - ], - "signature": [ - "Type", - "" - ], - "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, { "parentPluginId": "@kbn/securitysolution-io-ts-alerting-types", "id": "def-common.DefaultToString", @@ -2921,7 +2888,14 @@ "label": "throttle", "description": [], "signature": [ - "StringC" + "UnionC", + "<[", + "LiteralC", + "<\"no_actions\">, ", + "LiteralC", + "<\"rule\">, ", + "Type", + "]>" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts", "deprecated": false, @@ -2938,31 +2912,15 @@ "signature": [ "UnionC", "<[", - "StringC", - ", ", - "NullC", - "]>" - ], - "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, - { - "parentPluginId": "@kbn/securitysolution-io-ts-alerting-types", - "id": "def-common.throttleOrNullOrUndefined", - "type": "Object", - "tags": [], - "label": "throttleOrNullOrUndefined", - "description": [], - "signature": [ "UnionC", "<[", - "StringC", - ", ", + "LiteralC", + "<\"no_actions\">, ", + "LiteralC", + "<\"rule\">, ", + "Type", + "]>, ", "NullC", - ", ", - "UndefinedC", "]>" ], "path": "packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts", diff --git a/api_docs/kbn_securitysolution_io_ts_alerting_types.mdx b/api_docs/kbn_securitysolution_io_ts_alerting_types.mdx index fbf50097d69a4..cdc1b3ea54ed7 100644 --- a/api_docs/kbn_securitysolution_io_ts_alerting_types.mdx +++ b/api_docs/kbn_securitysolution_io_ts_alerting_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-io-ts-alerting-types title: "@kbn/securitysolution-io-ts-alerting-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-io-ts-alerting-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-io-ts-alerting-types'] --- import kbnSecuritysolutionIoTsAlertingTypesObj from './kbn_securitysolution_io_ts_alerting_types.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Owner missing] for questions regarding this plugin. | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 148 | 0 | 129 | 0 | +| 145 | 0 | 127 | 0 | ## Common diff --git a/api_docs/kbn_securitysolution_io_ts_list_types.mdx b/api_docs/kbn_securitysolution_io_ts_list_types.mdx index 45ef5aade835f..185f8a6c2a54b 100644 --- a/api_docs/kbn_securitysolution_io_ts_list_types.mdx +++ b/api_docs/kbn_securitysolution_io_ts_list_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-io-ts-list-types title: "@kbn/securitysolution-io-ts-list-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-io-ts-list-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-io-ts-list-types'] --- import kbnSecuritysolutionIoTsListTypesObj from './kbn_securitysolution_io_ts_list_types.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_io_ts_types.devdocs.json b/api_docs/kbn_securitysolution_io_ts_types.devdocs.json index 2ec94e9e8c1c0..ef934492d28ef 100644 --- a/api_docs/kbn_securitysolution_io_ts_types.devdocs.json +++ b/api_docs/kbn_securitysolution_io_ts_types.devdocs.json @@ -405,6 +405,41 @@ ], "returnComment": [], "initialIsOpen": false + }, + { + "parentPluginId": "@kbn/securitysolution-io-ts-types", + "id": "def-common.TimeDuration", + "type": "Function", + "tags": [], + "label": "TimeDuration", + "description": [], + "signature": [ + "({ allowedUnits, allowedDurations }: TimeDurationType) => ", + "Type", + "" + ], + "path": "packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "@kbn/securitysolution-io-ts-types", + "id": "def-common.TimeDuration.$1", + "type": "CompoundType", + "tags": [], + "label": "{ allowedUnits, allowedDurations }", + "description": [], + "signature": [ + "TimeDurationType" + ], + "path": "packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false } ], "interfaces": [], @@ -644,12 +679,30 @@ "label": "TimeDurationC", "description": [], "signature": [ + "({ allowedUnits, allowedDurations }: TimeDurationType) => ", "Type", "" ], "path": "packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts", "deprecated": false, "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "@kbn/securitysolution-io-ts-types", + "id": "def-common.TimeDurationC.$1", + "type": "CompoundType", + "tags": [], + "label": "__0", + "description": [], + "signature": [ + "TimeDurationWithAllowedDurations | TimeDurationWithAllowedUnits" + ], + "path": "packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts", + "deprecated": false, + "trackAdoption": false + } + ], "initialIsOpen": false }, { @@ -1042,24 +1095,6 @@ "trackAdoption": false, "initialIsOpen": false }, - { - "parentPluginId": "@kbn/securitysolution-io-ts-types", - "id": "def-common.TimeDuration", - "type": "Object", - "tags": [], - "label": "TimeDuration", - "description": [ - "\nTypes the TimeDuration as:\n - A string that is not empty, and composed of a positive integer greater than 0 followed by a unit of time\n - in the format {safe_integer}{timeUnit}, e.g. \"30s\", \"1m\", \"2h\"" - ], - "signature": [ - "Type", - "" - ], - "path": "packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts", - "deprecated": false, - "trackAdoption": false, - "initialIsOpen": false - }, { "parentPluginId": "@kbn/securitysolution-io-ts-types", "id": "def-common.UUID", diff --git a/api_docs/kbn_securitysolution_io_ts_types.mdx b/api_docs/kbn_securitysolution_io_ts_types.mdx index c3bb2e7e2ee49..ee826f79d080f 100644 --- a/api_docs/kbn_securitysolution_io_ts_types.mdx +++ b/api_docs/kbn_securitysolution_io_ts_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-io-ts-types title: "@kbn/securitysolution-io-ts-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-io-ts-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-io-ts-types'] --- import kbnSecuritysolutionIoTsTypesObj from './kbn_securitysolution_io_ts_types.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Owner missing] for questions regarding this plugin. | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 63 | 0 | 33 | 0 | +| 65 | 0 | 36 | 0 | ## Common diff --git a/api_docs/kbn_securitysolution_io_ts_utils.mdx b/api_docs/kbn_securitysolution_io_ts_utils.mdx index f41af821ce9b8..79363d1648a7d 100644 --- a/api_docs/kbn_securitysolution_io_ts_utils.mdx +++ b/api_docs/kbn_securitysolution_io_ts_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-io-ts-utils title: "@kbn/securitysolution-io-ts-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-io-ts-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-io-ts-utils'] --- import kbnSecuritysolutionIoTsUtilsObj from './kbn_securitysolution_io_ts_utils.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_list_api.mdx b/api_docs/kbn_securitysolution_list_api.mdx index 00d3453ea1564..bad03cd4ead92 100644 --- a/api_docs/kbn_securitysolution_list_api.mdx +++ b/api_docs/kbn_securitysolution_list_api.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-list-api title: "@kbn/securitysolution-list-api" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-list-api plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-list-api'] --- import kbnSecuritysolutionListApiObj from './kbn_securitysolution_list_api.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_list_constants.mdx b/api_docs/kbn_securitysolution_list_constants.mdx index 7f950925e143c..d2e797f19a3e8 100644 --- a/api_docs/kbn_securitysolution_list_constants.mdx +++ b/api_docs/kbn_securitysolution_list_constants.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-list-constants title: "@kbn/securitysolution-list-constants" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-list-constants plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-list-constants'] --- import kbnSecuritysolutionListConstantsObj from './kbn_securitysolution_list_constants.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_list_hooks.mdx b/api_docs/kbn_securitysolution_list_hooks.mdx index a87c153759c2e..aadd62030a1b8 100644 --- a/api_docs/kbn_securitysolution_list_hooks.mdx +++ b/api_docs/kbn_securitysolution_list_hooks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-list-hooks title: "@kbn/securitysolution-list-hooks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-list-hooks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-list-hooks'] --- import kbnSecuritysolutionListHooksObj from './kbn_securitysolution_list_hooks.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_list_utils.mdx b/api_docs/kbn_securitysolution_list_utils.mdx index a8a0a5be5ed8f..37f5836577b4f 100644 --- a/api_docs/kbn_securitysolution_list_utils.mdx +++ b/api_docs/kbn_securitysolution_list_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-list-utils title: "@kbn/securitysolution-list-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-list-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-list-utils'] --- import kbnSecuritysolutionListUtilsObj from './kbn_securitysolution_list_utils.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_rules.mdx b/api_docs/kbn_securitysolution_rules.mdx index ceb9e4a1a4c4b..7aa2954ee0c08 100644 --- a/api_docs/kbn_securitysolution_rules.mdx +++ b/api_docs/kbn_securitysolution_rules.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-rules title: "@kbn/securitysolution-rules" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-rules plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-rules'] --- import kbnSecuritysolutionRulesObj from './kbn_securitysolution_rules.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_t_grid.mdx b/api_docs/kbn_securitysolution_t_grid.mdx index 62afc60aba44b..99fe2b585b0b2 100644 --- a/api_docs/kbn_securitysolution_t_grid.mdx +++ b/api_docs/kbn_securitysolution_t_grid.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-t-grid title: "@kbn/securitysolution-t-grid" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-t-grid plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-t-grid'] --- import kbnSecuritysolutionTGridObj from './kbn_securitysolution_t_grid.devdocs.json'; diff --git a/api_docs/kbn_securitysolution_utils.mdx b/api_docs/kbn_securitysolution_utils.mdx index 24d192fa7cbfa..e132797fea852 100644 --- a/api_docs/kbn_securitysolution_utils.mdx +++ b/api_docs/kbn_securitysolution_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-securitysolution-utils title: "@kbn/securitysolution-utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/securitysolution-utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/securitysolution-utils'] --- import kbnSecuritysolutionUtilsObj from './kbn_securitysolution_utils.devdocs.json'; diff --git a/api_docs/kbn_server_http_tools.mdx b/api_docs/kbn_server_http_tools.mdx index a46263ee9f1c1..48d0d4756ef6c 100644 --- a/api_docs/kbn_server_http_tools.mdx +++ b/api_docs/kbn_server_http_tools.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-server-http-tools title: "@kbn/server-http-tools" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/server-http-tools plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/server-http-tools'] --- import kbnServerHttpToolsObj from './kbn_server_http_tools.devdocs.json'; diff --git a/api_docs/kbn_server_route_repository.mdx b/api_docs/kbn_server_route_repository.mdx index cf89e44a80e04..5c184c9a583cc 100644 --- a/api_docs/kbn_server_route_repository.mdx +++ b/api_docs/kbn_server_route_repository.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-server-route-repository title: "@kbn/server-route-repository" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/server-route-repository plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/server-route-repository'] --- import kbnServerRouteRepositoryObj from './kbn_server_route_repository.devdocs.json'; diff --git a/api_docs/kbn_shared_svg.mdx b/api_docs/kbn_shared_svg.mdx index 564e869ba0739..249f6a00cf7e6 100644 --- a/api_docs/kbn_shared_svg.mdx +++ b/api_docs/kbn_shared_svg.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-svg title: "@kbn/shared-svg" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-svg plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-svg'] --- import kbnSharedSvgObj from './kbn_shared_svg.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_avatar_user_profile_components.mdx b/api_docs/kbn_shared_ux_avatar_user_profile_components.mdx index 4af4131d0d5cf..e5e0f236974fb 100644 --- a/api_docs/kbn_shared_ux_avatar_user_profile_components.mdx +++ b/api_docs/kbn_shared_ux_avatar_user_profile_components.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-avatar-user-profile-components title: "@kbn/shared-ux-avatar-user-profile-components" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-avatar-user-profile-components plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-avatar-user-profile-components'] --- import kbnSharedUxAvatarUserProfileComponentsObj from './kbn_shared_ux_avatar_user_profile_components.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_button_exit_full_screen_mocks.mdx b/api_docs/kbn_shared_ux_button_exit_full_screen_mocks.mdx index 8faaf694df8d7..b78abda31ac59 100644 --- a/api_docs/kbn_shared_ux_button_exit_full_screen_mocks.mdx +++ b/api_docs/kbn_shared_ux_button_exit_full_screen_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-button-exit-full-screen-mocks title: "@kbn/shared-ux-button-exit-full-screen-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-button-exit-full-screen-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-button-exit-full-screen-mocks'] --- import kbnSharedUxButtonExitFullScreenMocksObj from './kbn_shared_ux_button_exit_full_screen_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_button_toolbar.mdx b/api_docs/kbn_shared_ux_button_toolbar.mdx index ac580aab9a27b..dda07aa08205d 100644 --- a/api_docs/kbn_shared_ux_button_toolbar.mdx +++ b/api_docs/kbn_shared_ux_button_toolbar.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-button-toolbar title: "@kbn/shared-ux-button-toolbar" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-button-toolbar plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-button-toolbar'] --- import kbnSharedUxButtonToolbarObj from './kbn_shared_ux_button_toolbar.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_card_no_data.mdx b/api_docs/kbn_shared_ux_card_no_data.mdx index 773e3c7234c27..92fa45970a95f 100644 --- a/api_docs/kbn_shared_ux_card_no_data.mdx +++ b/api_docs/kbn_shared_ux_card_no_data.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-card-no-data title: "@kbn/shared-ux-card-no-data" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-card-no-data plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-card-no-data'] --- import kbnSharedUxCardNoDataObj from './kbn_shared_ux_card_no_data.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_card_no_data_mocks.mdx b/api_docs/kbn_shared_ux_card_no_data_mocks.mdx index 0f940aadb3daa..67fd1537b9531 100644 --- a/api_docs/kbn_shared_ux_card_no_data_mocks.mdx +++ b/api_docs/kbn_shared_ux_card_no_data_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-card-no-data-mocks title: "@kbn/shared-ux-card-no-data-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-card-no-data-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-card-no-data-mocks'] --- import kbnSharedUxCardNoDataMocksObj from './kbn_shared_ux_card_no_data_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_link_redirect_app_mocks.mdx b/api_docs/kbn_shared_ux_link_redirect_app_mocks.mdx index 1ffc0e131ca1d..dba90c297e1be 100644 --- a/api_docs/kbn_shared_ux_link_redirect_app_mocks.mdx +++ b/api_docs/kbn_shared_ux_link_redirect_app_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-link-redirect-app-mocks title: "@kbn/shared-ux-link-redirect-app-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-link-redirect-app-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-link-redirect-app-mocks'] --- import kbnSharedUxLinkRedirectAppMocksObj from './kbn_shared_ux_link_redirect_app_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_analytics_no_data.mdx b/api_docs/kbn_shared_ux_page_analytics_no_data.mdx index 6aa2d0a90d57c..eb63fe71719da 100644 --- a/api_docs/kbn_shared_ux_page_analytics_no_data.mdx +++ b/api_docs/kbn_shared_ux_page_analytics_no_data.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-analytics-no-data title: "@kbn/shared-ux-page-analytics-no-data" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-analytics-no-data plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-analytics-no-data'] --- import kbnSharedUxPageAnalyticsNoDataObj from './kbn_shared_ux_page_analytics_no_data.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_analytics_no_data_mocks.mdx b/api_docs/kbn_shared_ux_page_analytics_no_data_mocks.mdx index cf773f26fba40..312cc6dc442de 100644 --- a/api_docs/kbn_shared_ux_page_analytics_no_data_mocks.mdx +++ b/api_docs/kbn_shared_ux_page_analytics_no_data_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-analytics-no-data-mocks title: "@kbn/shared-ux-page-analytics-no-data-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-analytics-no-data-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-analytics-no-data-mocks'] --- import kbnSharedUxPageAnalyticsNoDataMocksObj from './kbn_shared_ux_page_analytics_no_data_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_kibana_no_data.mdx b/api_docs/kbn_shared_ux_page_kibana_no_data.mdx index 232f4f31d8750..fc5ddb138a558 100644 --- a/api_docs/kbn_shared_ux_page_kibana_no_data.mdx +++ b/api_docs/kbn_shared_ux_page_kibana_no_data.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-kibana-no-data title: "@kbn/shared-ux-page-kibana-no-data" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-kibana-no-data plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-kibana-no-data'] --- import kbnSharedUxPageKibanaNoDataObj from './kbn_shared_ux_page_kibana_no_data.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_kibana_no_data_mocks.mdx b/api_docs/kbn_shared_ux_page_kibana_no_data_mocks.mdx index 59d78c3af89d0..00f4e0b05251d 100644 --- a/api_docs/kbn_shared_ux_page_kibana_no_data_mocks.mdx +++ b/api_docs/kbn_shared_ux_page_kibana_no_data_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-kibana-no-data-mocks title: "@kbn/shared-ux-page-kibana-no-data-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-kibana-no-data-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-kibana-no-data-mocks'] --- import kbnSharedUxPageKibanaNoDataMocksObj from './kbn_shared_ux_page_kibana_no_data_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_kibana_template.mdx b/api_docs/kbn_shared_ux_page_kibana_template.mdx index 65d2654e0e4c0..22e5de7cb344c 100644 --- a/api_docs/kbn_shared_ux_page_kibana_template.mdx +++ b/api_docs/kbn_shared_ux_page_kibana_template.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-kibana-template title: "@kbn/shared-ux-page-kibana-template" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-kibana-template plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-kibana-template'] --- import kbnSharedUxPageKibanaTemplateObj from './kbn_shared_ux_page_kibana_template.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_kibana_template_mocks.mdx b/api_docs/kbn_shared_ux_page_kibana_template_mocks.mdx index 3099d81b2efb1..de0d8b5ff101e 100644 --- a/api_docs/kbn_shared_ux_page_kibana_template_mocks.mdx +++ b/api_docs/kbn_shared_ux_page_kibana_template_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-kibana-template-mocks title: "@kbn/shared-ux-page-kibana-template-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-kibana-template-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-kibana-template-mocks'] --- import kbnSharedUxPageKibanaTemplateMocksObj from './kbn_shared_ux_page_kibana_template_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_no_data.mdx b/api_docs/kbn_shared_ux_page_no_data.mdx index 91ebc86264d87..b1597719e26ac 100644 --- a/api_docs/kbn_shared_ux_page_no_data.mdx +++ b/api_docs/kbn_shared_ux_page_no_data.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-no-data title: "@kbn/shared-ux-page-no-data" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-no-data plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-no-data'] --- import kbnSharedUxPageNoDataObj from './kbn_shared_ux_page_no_data.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_no_data_config.mdx b/api_docs/kbn_shared_ux_page_no_data_config.mdx index 4d580254bc41d..254ce88f6ed03 100644 --- a/api_docs/kbn_shared_ux_page_no_data_config.mdx +++ b/api_docs/kbn_shared_ux_page_no_data_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-no-data-config title: "@kbn/shared-ux-page-no-data-config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-no-data-config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-no-data-config'] --- import kbnSharedUxPageNoDataConfigObj from './kbn_shared_ux_page_no_data_config.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_no_data_config_mocks.mdx b/api_docs/kbn_shared_ux_page_no_data_config_mocks.mdx index 3b09d9851a4ad..4b7ce948af067 100644 --- a/api_docs/kbn_shared_ux_page_no_data_config_mocks.mdx +++ b/api_docs/kbn_shared_ux_page_no_data_config_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-no-data-config-mocks title: "@kbn/shared-ux-page-no-data-config-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-no-data-config-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-no-data-config-mocks'] --- import kbnSharedUxPageNoDataConfigMocksObj from './kbn_shared_ux_page_no_data_config_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_no_data_mocks.mdx b/api_docs/kbn_shared_ux_page_no_data_mocks.mdx index cc8e890cebed1..4bebd9fa27f9e 100644 --- a/api_docs/kbn_shared_ux_page_no_data_mocks.mdx +++ b/api_docs/kbn_shared_ux_page_no_data_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-no-data-mocks title: "@kbn/shared-ux-page-no-data-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-no-data-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-no-data-mocks'] --- import kbnSharedUxPageNoDataMocksObj from './kbn_shared_ux_page_no_data_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_page_solution_nav.mdx b/api_docs/kbn_shared_ux_page_solution_nav.mdx index 85615d64e6b93..a3b2ddd97a17e 100644 --- a/api_docs/kbn_shared_ux_page_solution_nav.mdx +++ b/api_docs/kbn_shared_ux_page_solution_nav.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-page-solution-nav title: "@kbn/shared-ux-page-solution-nav" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-page-solution-nav plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-page-solution-nav'] --- import kbnSharedUxPageSolutionNavObj from './kbn_shared_ux_page_solution_nav.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_prompt_no_data_views.mdx b/api_docs/kbn_shared_ux_prompt_no_data_views.mdx index 23769d6634d61..0a1d772cc031c 100644 --- a/api_docs/kbn_shared_ux_prompt_no_data_views.mdx +++ b/api_docs/kbn_shared_ux_prompt_no_data_views.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-prompt-no-data-views title: "@kbn/shared-ux-prompt-no-data-views" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-prompt-no-data-views plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-prompt-no-data-views'] --- import kbnSharedUxPromptNoDataViewsObj from './kbn_shared_ux_prompt_no_data_views.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_prompt_no_data_views_mocks.mdx b/api_docs/kbn_shared_ux_prompt_no_data_views_mocks.mdx index b0cae6ebc2b47..70d3cf84c5ef6 100644 --- a/api_docs/kbn_shared_ux_prompt_no_data_views_mocks.mdx +++ b/api_docs/kbn_shared_ux_prompt_no_data_views_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-prompt-no-data-views-mocks title: "@kbn/shared-ux-prompt-no-data-views-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-prompt-no-data-views-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-prompt-no-data-views-mocks'] --- import kbnSharedUxPromptNoDataViewsMocksObj from './kbn_shared_ux_prompt_no_data_views_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_router.mdx b/api_docs/kbn_shared_ux_router.mdx index fdeb9e70af30f..61fe760de5035 100644 --- a/api_docs/kbn_shared_ux_router.mdx +++ b/api_docs/kbn_shared_ux_router.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-router title: "@kbn/shared-ux-router" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-router plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-router'] --- import kbnSharedUxRouterObj from './kbn_shared_ux_router.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_router_mocks.mdx b/api_docs/kbn_shared_ux_router_mocks.mdx index 4e4d6fc4c43d4..02064c4eacc66 100644 --- a/api_docs/kbn_shared_ux_router_mocks.mdx +++ b/api_docs/kbn_shared_ux_router_mocks.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-router-mocks title: "@kbn/shared-ux-router-mocks" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-router-mocks plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-router-mocks'] --- import kbnSharedUxRouterMocksObj from './kbn_shared_ux_router_mocks.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_storybook_config.mdx b/api_docs/kbn_shared_ux_storybook_config.mdx index fcfeea3f91e2b..86606778f8dfd 100644 --- a/api_docs/kbn_shared_ux_storybook_config.mdx +++ b/api_docs/kbn_shared_ux_storybook_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-storybook-config title: "@kbn/shared-ux-storybook-config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-storybook-config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-storybook-config'] --- import kbnSharedUxStorybookConfigObj from './kbn_shared_ux_storybook_config.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_storybook_mock.mdx b/api_docs/kbn_shared_ux_storybook_mock.mdx index 9341074e595cf..180ae33f7885a 100644 --- a/api_docs/kbn_shared_ux_storybook_mock.mdx +++ b/api_docs/kbn_shared_ux_storybook_mock.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-storybook-mock title: "@kbn/shared-ux-storybook-mock" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-storybook-mock plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-storybook-mock'] --- import kbnSharedUxStorybookMockObj from './kbn_shared_ux_storybook_mock.devdocs.json'; diff --git a/api_docs/kbn_shared_ux_utility.mdx b/api_docs/kbn_shared_ux_utility.mdx index 9f9fb98016df2..7c2f7cc09c77b 100644 --- a/api_docs/kbn_shared_ux_utility.mdx +++ b/api_docs/kbn_shared_ux_utility.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-shared-ux-utility title: "@kbn/shared-ux-utility" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/shared-ux-utility plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/shared-ux-utility'] --- import kbnSharedUxUtilityObj from './kbn_shared_ux_utility.devdocs.json'; diff --git a/api_docs/kbn_some_dev_log.mdx b/api_docs/kbn_some_dev_log.mdx index 085818f1a51e5..ef8d669ed27aa 100644 --- a/api_docs/kbn_some_dev_log.mdx +++ b/api_docs/kbn_some_dev_log.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-some-dev-log title: "@kbn/some-dev-log" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/some-dev-log plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/some-dev-log'] --- import kbnSomeDevLogObj from './kbn_some_dev_log.devdocs.json'; diff --git a/api_docs/kbn_sort_package_json.mdx b/api_docs/kbn_sort_package_json.mdx index e16b35454f5d6..0e8f9505b35f7 100644 --- a/api_docs/kbn_sort_package_json.mdx +++ b/api_docs/kbn_sort_package_json.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-sort-package-json title: "@kbn/sort-package-json" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/sort-package-json plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/sort-package-json'] --- import kbnSortPackageJsonObj from './kbn_sort_package_json.devdocs.json'; diff --git a/api_docs/kbn_std.mdx b/api_docs/kbn_std.mdx index a8f40a8a4eb4a..c2a9a20196954 100644 --- a/api_docs/kbn_std.mdx +++ b/api_docs/kbn_std.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-std title: "@kbn/std" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/std plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/std'] --- import kbnStdObj from './kbn_std.devdocs.json'; diff --git a/api_docs/kbn_stdio_dev_helpers.mdx b/api_docs/kbn_stdio_dev_helpers.mdx index 1a56b36b7ecf7..9662e0b7958fe 100644 --- a/api_docs/kbn_stdio_dev_helpers.mdx +++ b/api_docs/kbn_stdio_dev_helpers.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-stdio-dev-helpers title: "@kbn/stdio-dev-helpers" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/stdio-dev-helpers plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/stdio-dev-helpers'] --- import kbnStdioDevHelpersObj from './kbn_stdio_dev_helpers.devdocs.json'; diff --git a/api_docs/kbn_storybook.mdx b/api_docs/kbn_storybook.mdx index cef4816dbfcb2..f279425a11288 100644 --- a/api_docs/kbn_storybook.mdx +++ b/api_docs/kbn_storybook.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-storybook title: "@kbn/storybook" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/storybook plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/storybook'] --- import kbnStorybookObj from './kbn_storybook.devdocs.json'; diff --git a/api_docs/kbn_telemetry_tools.mdx b/api_docs/kbn_telemetry_tools.mdx index 3ce0d27a31aa2..70dd586f3b9f7 100644 --- a/api_docs/kbn_telemetry_tools.mdx +++ b/api_docs/kbn_telemetry_tools.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-telemetry-tools title: "@kbn/telemetry-tools" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/telemetry-tools plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/telemetry-tools'] --- import kbnTelemetryToolsObj from './kbn_telemetry_tools.devdocs.json'; diff --git a/api_docs/kbn_test.mdx b/api_docs/kbn_test.mdx index 8c68a064c4eea..2d4b1f7a3e301 100644 --- a/api_docs/kbn_test.mdx +++ b/api_docs/kbn_test.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-test title: "@kbn/test" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/test plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/test'] --- import kbnTestObj from './kbn_test.devdocs.json'; diff --git a/api_docs/kbn_test_jest_helpers.mdx b/api_docs/kbn_test_jest_helpers.mdx index 80810336bb2e1..f0c472ec736d5 100644 --- a/api_docs/kbn_test_jest_helpers.mdx +++ b/api_docs/kbn_test_jest_helpers.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-test-jest-helpers title: "@kbn/test-jest-helpers" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/test-jest-helpers plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/test-jest-helpers'] --- import kbnTestJestHelpersObj from './kbn_test_jest_helpers.devdocs.json'; diff --git a/api_docs/kbn_test_subj_selector.mdx b/api_docs/kbn_test_subj_selector.mdx index dcfdbe0b9b3d9..421399623af64 100644 --- a/api_docs/kbn_test_subj_selector.mdx +++ b/api_docs/kbn_test_subj_selector.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-test-subj-selector title: "@kbn/test-subj-selector" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/test-subj-selector plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/test-subj-selector'] --- import kbnTestSubjSelectorObj from './kbn_test_subj_selector.devdocs.json'; diff --git a/api_docs/kbn_tooling_log.mdx b/api_docs/kbn_tooling_log.mdx index e42d04d4b96da..8c06707332c23 100644 --- a/api_docs/kbn_tooling_log.mdx +++ b/api_docs/kbn_tooling_log.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-tooling-log title: "@kbn/tooling-log" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/tooling-log plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/tooling-log'] --- import kbnToolingLogObj from './kbn_tooling_log.devdocs.json'; diff --git a/api_docs/kbn_type_summarizer.mdx b/api_docs/kbn_type_summarizer.mdx index 7ff0d31edaa88..a03912522beaa 100644 --- a/api_docs/kbn_type_summarizer.mdx +++ b/api_docs/kbn_type_summarizer.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-type-summarizer title: "@kbn/type-summarizer" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/type-summarizer plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/type-summarizer'] --- import kbnTypeSummarizerObj from './kbn_type_summarizer.devdocs.json'; diff --git a/api_docs/kbn_type_summarizer_core.mdx b/api_docs/kbn_type_summarizer_core.mdx index bee4f19aa6a1b..7d6e18575e25c 100644 --- a/api_docs/kbn_type_summarizer_core.mdx +++ b/api_docs/kbn_type_summarizer_core.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-type-summarizer-core title: "@kbn/type-summarizer-core" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/type-summarizer-core plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/type-summarizer-core'] --- import kbnTypeSummarizerCoreObj from './kbn_type_summarizer_core.devdocs.json'; diff --git a/api_docs/kbn_typed_react_router_config.mdx b/api_docs/kbn_typed_react_router_config.mdx index 89d19b610938a..3d387dbca9d59 100644 --- a/api_docs/kbn_typed_react_router_config.mdx +++ b/api_docs/kbn_typed_react_router_config.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-typed-react-router-config title: "@kbn/typed-react-router-config" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/typed-react-router-config plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/typed-react-router-config'] --- import kbnTypedReactRouterConfigObj from './kbn_typed_react_router_config.devdocs.json'; diff --git a/api_docs/kbn_ui_theme.mdx b/api_docs/kbn_ui_theme.mdx index 42b1e58ea7503..80555e578ee94 100644 --- a/api_docs/kbn_ui_theme.mdx +++ b/api_docs/kbn_ui_theme.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-ui-theme title: "@kbn/ui-theme" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/ui-theme plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/ui-theme'] --- import kbnUiThemeObj from './kbn_ui_theme.devdocs.json'; diff --git a/api_docs/kbn_user_profile_components.mdx b/api_docs/kbn_user_profile_components.mdx index b7d198915a35e..0396c24bc40eb 100644 --- a/api_docs/kbn_user_profile_components.mdx +++ b/api_docs/kbn_user_profile_components.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-user-profile-components title: "@kbn/user-profile-components" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/user-profile-components plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/user-profile-components'] --- import kbnUserProfileComponentsObj from './kbn_user_profile_components.devdocs.json'; diff --git a/api_docs/kbn_utility_types.mdx b/api_docs/kbn_utility_types.mdx index 52b2243fe3b35..de93a8fe050a9 100644 --- a/api_docs/kbn_utility_types.mdx +++ b/api_docs/kbn_utility_types.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-utility-types title: "@kbn/utility-types" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/utility-types plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/utility-types'] --- import kbnUtilityTypesObj from './kbn_utility_types.devdocs.json'; diff --git a/api_docs/kbn_utility_types_jest.mdx b/api_docs/kbn_utility_types_jest.mdx index 9687cfb2270f9..fe8d933d19a34 100644 --- a/api_docs/kbn_utility_types_jest.mdx +++ b/api_docs/kbn_utility_types_jest.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-utility-types-jest title: "@kbn/utility-types-jest" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/utility-types-jest plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/utility-types-jest'] --- import kbnUtilityTypesJestObj from './kbn_utility_types_jest.devdocs.json'; diff --git a/api_docs/kbn_utils.mdx b/api_docs/kbn_utils.mdx index 02a4c9d1adf55..e9e1e8d327dfd 100644 --- a/api_docs/kbn_utils.mdx +++ b/api_docs/kbn_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-utils title: "@kbn/utils" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/utils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/utils'] --- import kbnUtilsObj from './kbn_utils.devdocs.json'; diff --git a/api_docs/kbn_yarn_lock_validator.mdx b/api_docs/kbn_yarn_lock_validator.mdx index 2b7ea1ef4ae65..96ce8b5f78b19 100644 --- a/api_docs/kbn_yarn_lock_validator.mdx +++ b/api_docs/kbn_yarn_lock_validator.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kbn-yarn-lock-validator title: "@kbn/yarn-lock-validator" image: https://source.unsplash.com/400x175/?github description: API docs for the @kbn/yarn-lock-validator plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', '@kbn/yarn-lock-validator'] --- import kbnYarnLockValidatorObj from './kbn_yarn_lock_validator.devdocs.json'; diff --git a/api_docs/kibana_overview.mdx b/api_docs/kibana_overview.mdx index 1cbdf607979ab..2a28c3743374d 100644 --- a/api_docs/kibana_overview.mdx +++ b/api_docs/kibana_overview.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kibanaOverview title: "kibanaOverview" image: https://source.unsplash.com/400x175/?github description: API docs for the kibanaOverview plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'kibanaOverview'] --- import kibanaOverviewObj from './kibana_overview.devdocs.json'; diff --git a/api_docs/kibana_react.mdx b/api_docs/kibana_react.mdx index 60ffe9f9f9cac..7ab80f87e401c 100644 --- a/api_docs/kibana_react.mdx +++ b/api_docs/kibana_react.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kibanaReact title: "kibanaReact" image: https://source.unsplash.com/400x175/?github description: API docs for the kibanaReact plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'kibanaReact'] --- import kibanaReactObj from './kibana_react.devdocs.json'; diff --git a/api_docs/kibana_utils.mdx b/api_docs/kibana_utils.mdx index 5b9aa1fc4b26b..21d349683d8e3 100644 --- a/api_docs/kibana_utils.mdx +++ b/api_docs/kibana_utils.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kibanaUtils title: "kibanaUtils" image: https://source.unsplash.com/400x175/?github description: API docs for the kibanaUtils plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'kibanaUtils'] --- import kibanaUtilsObj from './kibana_utils.devdocs.json'; diff --git a/api_docs/kubernetes_security.mdx b/api_docs/kubernetes_security.mdx index 25c547b62bd9b..b7d40f28432aa 100644 --- a/api_docs/kubernetes_security.mdx +++ b/api_docs/kubernetes_security.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/kubernetesSecurity title: "kubernetesSecurity" image: https://source.unsplash.com/400x175/?github description: API docs for the kubernetesSecurity plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'kubernetesSecurity'] --- import kubernetesSecurityObj from './kubernetes_security.devdocs.json'; diff --git a/api_docs/lens.devdocs.json b/api_docs/lens.devdocs.json index 4fc56c34842e9..4d4561547ed2a 100644 --- a/api_docs/lens.devdocs.json +++ b/api_docs/lens.devdocs.json @@ -1527,6 +1527,24 @@ "children": [], "returnComment": [] }, + { + "parentPluginId": "lens", + "id": "def-public.DatasourcePublicAPI.isTextBasedLanguage", + "type": "Function", + "tags": [], + "label": "isTextBasedLanguage", + "description": [ + "\nReturns true if this is a text based language datasource" + ], + "signature": [ + "() => boolean" + ], + "path": "x-pack/plugins/lens/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "returnComment": [] + }, { "parentPluginId": "lens", "id": "def-public.DatasourcePublicAPI.getFilters", @@ -11347,6 +11365,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "lens", + "id": "def-common.ENABLE_SQL", + "type": "string", + "tags": [], + "label": "ENABLE_SQL", + "description": [], + "signature": [ + "\"discover:enableSql\"" + ], + "path": "x-pack/plugins/lens/common/constants.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "lens", "id": "def-common.FormatFactory", @@ -11495,6 +11528,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "lens", + "id": "def-common.OriginalColumn", + "type": "Type", + "tags": [], + "label": "OriginalColumn", + "description": [], + "signature": [ + "{ id: string; label: string; } & ({ operationType: \"date_histogram\"; sourceField: string; } | { operationType: string; sourceField: never; })" + ], + "path": "x-pack/plugins/lens/common/expressions/map_to_columns/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "lens", "id": "def-common.PieChartType", diff --git a/api_docs/lens.mdx b/api_docs/lens.mdx index 57912de87ecfc..0cb5e40b3b4cb 100644 --- a/api_docs/lens.mdx +++ b/api_docs/lens.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/lens title: "lens" image: https://source.unsplash.com/400x175/?github description: API docs for the lens plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'lens'] --- import lensObj from './lens.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 646 | 0 | 558 | 42 | +| 649 | 0 | 560 | 42 | ## Client diff --git a/api_docs/license_api_guard.devdocs.json b/api_docs/license_api_guard.devdocs.json index a554c2c4b7895..03acec45780d4 100644 --- a/api_docs/license_api_guard.devdocs.json +++ b/api_docs/license_api_guard.devdocs.json @@ -94,13 +94,7 @@ "description": [], "signature": [ "(handler: ", { "pluginId": "core", diff --git a/api_docs/license_api_guard.mdx b/api_docs/license_api_guard.mdx index c5ae4cf492113..63d15a7c40650 100644 --- a/api_docs/license_api_guard.mdx +++ b/api_docs/license_api_guard.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/licenseApiGuard title: "licenseApiGuard" image: https://source.unsplash.com/400x175/?github description: API docs for the licenseApiGuard plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'licenseApiGuard'] --- import licenseApiGuardObj from './license_api_guard.devdocs.json'; diff --git a/api_docs/license_management.mdx b/api_docs/license_management.mdx index 51291ac526da1..88e17bcee6feb 100644 --- a/api_docs/license_management.mdx +++ b/api_docs/license_management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/licenseManagement title: "licenseManagement" image: https://source.unsplash.com/400x175/?github description: API docs for the licenseManagement plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'licenseManagement'] --- import licenseManagementObj from './license_management.devdocs.json'; diff --git a/api_docs/licensing.mdx b/api_docs/licensing.mdx index fe67f8623dad7..c7000d51761c4 100644 --- a/api_docs/licensing.mdx +++ b/api_docs/licensing.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/licensing title: "licensing" image: https://source.unsplash.com/400x175/?github description: API docs for the licensing plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'licensing'] --- import licensingObj from './licensing.devdocs.json'; diff --git a/api_docs/lists.mdx b/api_docs/lists.mdx index 25315e4aca2c1..9deb279fb73b6 100644 --- a/api_docs/lists.mdx +++ b/api_docs/lists.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/lists title: "lists" image: https://source.unsplash.com/400x175/?github description: API docs for the lists plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'lists'] --- import listsObj from './lists.devdocs.json'; diff --git a/api_docs/management.mdx b/api_docs/management.mdx index 421951a45f4de..2cec82774807b 100644 --- a/api_docs/management.mdx +++ b/api_docs/management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/management title: "management" image: https://source.unsplash.com/400x175/?github description: API docs for the management plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'management'] --- import managementObj from './management.devdocs.json'; diff --git a/api_docs/maps.mdx b/api_docs/maps.mdx index 93bf7efb3e546..2667e8f19bae6 100644 --- a/api_docs/maps.mdx +++ b/api_docs/maps.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/maps title: "maps" image: https://source.unsplash.com/400x175/?github description: API docs for the maps plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'maps'] --- import mapsObj from './maps.devdocs.json'; diff --git a/api_docs/maps_ems.mdx b/api_docs/maps_ems.mdx index 1b8da980d454d..558352f89505a 100644 --- a/api_docs/maps_ems.mdx +++ b/api_docs/maps_ems.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/mapsEms title: "mapsEms" image: https://source.unsplash.com/400x175/?github description: API docs for the mapsEms plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'mapsEms'] --- import mapsEmsObj from './maps_ems.devdocs.json'; diff --git a/api_docs/ml.mdx b/api_docs/ml.mdx index f1a20952c6833..b1abe52cefe17 100644 --- a/api_docs/ml.mdx +++ b/api_docs/ml.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/ml title: "ml" image: https://source.unsplash.com/400x175/?github description: API docs for the ml plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'ml'] --- import mlObj from './ml.devdocs.json'; diff --git a/api_docs/monitoring.mdx b/api_docs/monitoring.mdx index 021ad1e483ce2..b9332eb4163e6 100644 --- a/api_docs/monitoring.mdx +++ b/api_docs/monitoring.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/monitoring title: "monitoring" image: https://source.unsplash.com/400x175/?github description: API docs for the monitoring plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'monitoring'] --- import monitoringObj from './monitoring.devdocs.json'; diff --git a/api_docs/monitoring_collection.mdx b/api_docs/monitoring_collection.mdx index 83f556aea3173..23c398899ccbf 100644 --- a/api_docs/monitoring_collection.mdx +++ b/api_docs/monitoring_collection.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/monitoringCollection title: "monitoringCollection" image: https://source.unsplash.com/400x175/?github description: API docs for the monitoringCollection plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'monitoringCollection'] --- import monitoringCollectionObj from './monitoring_collection.devdocs.json'; diff --git a/api_docs/navigation.mdx b/api_docs/navigation.mdx index cf5c08c4b7ca9..bfa907ab09267 100644 --- a/api_docs/navigation.mdx +++ b/api_docs/navigation.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/navigation title: "navigation" image: https://source.unsplash.com/400x175/?github description: API docs for the navigation plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'navigation'] --- import navigationObj from './navigation.devdocs.json'; diff --git a/api_docs/newsfeed.mdx b/api_docs/newsfeed.mdx index 0da031f9285c5..4336085d004ce 100644 --- a/api_docs/newsfeed.mdx +++ b/api_docs/newsfeed.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/newsfeed title: "newsfeed" image: https://source.unsplash.com/400x175/?github description: API docs for the newsfeed plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'newsfeed'] --- import newsfeedObj from './newsfeed.devdocs.json'; diff --git a/api_docs/observability.devdocs.json b/api_docs/observability.devdocs.json index 625317137d6c3..fd03a2f285ab5 100644 --- a/api_docs/observability.devdocs.json +++ b/api_docs/observability.devdocs.json @@ -3704,11 +3704,29 @@ "description": [], "signature": [ "{ get: (id: string) => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "; list: () => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "[]; register: (objectType: ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ") => void; has: (id: string) => boolean; }" ], "path": "x-pack/plugins/observability/public/plugin.ts", @@ -7595,13 +7613,7 @@ "label": "context", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { licensing: Promise<", { "pluginId": "licensing", @@ -7619,13 +7631,7 @@ "text": "AlertingApiRequestHandlerContext" }, ">; core: Promise<", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.CoreRequestHandlerContext", - "text": "CoreRequestHandlerContext" - }, + "CoreRequestHandlerContext", ">; }" ], "path": "x-pack/plugins/observability/server/routes/types.ts", @@ -7737,13 +7743,35 @@ "section": "def-server.ObservabilityRouteCreateOptions", "text": "ObservabilityRouteCreateOptions" }, + "> | undefined; \"GET /api/observability/slos/{id}\"?: ", + "ServerRoute", + "<\"GET /api/observability/slos/{id}\", ", + "TypeC", + "<{ path: ", + "TypeC", + "<{ id: ", + "StringC", + "; }>; }>, ", + { + "pluginId": "observability", + "scope": "server", + "docId": "kibObservabilityPluginApi", + "section": "def-server.ObservabilityRouteHandlerResources", + "text": "ObservabilityRouteHandlerResources" + }, + ", { id: string; } & { name: string; description: string; indicator: { type: \"slo.apm.transaction_duration\"; params: { environment: string; service: string; transaction_type: string; transaction_name: string; 'threshold.us': number; }; } | { type: \"slo.apm.transaction_error_rate\"; params: { environment: string; service: string; transaction_type: string; transaction_name: string; } & { good_status_codes?: (\"2xx\" | \"3xx\" | \"4xx\" | \"5xx\")[] | undefined; }; }; time_window: { duration: string; is_rolling: true; }; budgeting_method: \"occurrences\"; objective: { target: number; }; }, ", + { + "pluginId": "observability", + "scope": "server", + "docId": "kibObservabilityPluginApi", + "section": "def-server.ObservabilityRouteCreateOptions", + "text": "ObservabilityRouteCreateOptions" + }, "> | undefined; \"POST /api/observability/slos\"?: ", "ServerRoute", "<\"POST /api/observability/slos\", ", "TypeC", "<{ body: ", - "IntersectionC", - "<[", "TypeC", "<{ name: ", "StringC", @@ -7841,13 +7869,7 @@ "TypeC", "<{ target: ", "NumberC", - "; }>; }>, ", - "PartialC", - "<{ settings: ", - "PartialC", - "<{ destination_index: ", - "StringC", - "; }>; }>]>; }>, ", + "; }>; }>; }>, ", { "pluginId": "observability", "scope": "server", @@ -7910,7 +7932,7 @@ "label": "ObservabilityConfig", "description": [], "signature": [ - "{ readonly unsafe: Readonly<{} & { slo: Readonly<{} & { enabled: boolean; }>; alertDetails: Readonly<{} & { enabled: boolean; }>; }>; readonly annotations: Readonly<{} & { index: string; enabled: boolean; }>; }" + "{ readonly unsafe: Readonly<{} & { slo: Readonly<{} & { enabled: boolean; }>; alertDetails: Readonly<{} & { enabled: boolean; }>; }>; readonly annotations: Readonly<{} & { enabled: boolean; index: string; }>; }" ], "path": "x-pack/plugins/observability/server/index.ts", "deprecated": false, @@ -7949,13 +7971,35 @@ "section": "def-server.ObservabilityRouteCreateOptions", "text": "ObservabilityRouteCreateOptions" }, + "> | undefined; \"GET /api/observability/slos/{id}\"?: ", + "ServerRoute", + "<\"GET /api/observability/slos/{id}\", ", + "TypeC", + "<{ path: ", + "TypeC", + "<{ id: ", + "StringC", + "; }>; }>, ", + { + "pluginId": "observability", + "scope": "server", + "docId": "kibObservabilityPluginApi", + "section": "def-server.ObservabilityRouteHandlerResources", + "text": "ObservabilityRouteHandlerResources" + }, + ", { id: string; } & { name: string; description: string; indicator: { type: \"slo.apm.transaction_duration\"; params: { environment: string; service: string; transaction_type: string; transaction_name: string; 'threshold.us': number; }; } | { type: \"slo.apm.transaction_error_rate\"; params: { environment: string; service: string; transaction_type: string; transaction_name: string; } & { good_status_codes?: (\"2xx\" | \"3xx\" | \"4xx\" | \"5xx\")[] | undefined; }; }; time_window: { duration: string; is_rolling: true; }; budgeting_method: \"occurrences\"; objective: { target: number; }; }, ", + { + "pluginId": "observability", + "scope": "server", + "docId": "kibObservabilityPluginApi", + "section": "def-server.ObservabilityRouteCreateOptions", + "text": "ObservabilityRouteCreateOptions" + }, "> | undefined; \"POST /api/observability/slos\"?: ", "ServerRoute", "<\"POST /api/observability/slos\", ", "TypeC", "<{ body: ", - "IntersectionC", - "<[", "TypeC", "<{ name: ", "StringC", @@ -8053,13 +8097,7 @@ "TypeC", "<{ target: ", "NumberC", - "; }>; }>, ", - "PartialC", - "<{ settings: ", - "PartialC", - "<{ destination_index: ", - "StringC", - "; }>; }>]>; }>, ", + "; }>; }>; }>, ", { "pluginId": "observability", "scope": "server", @@ -9748,13 +9786,7 @@ "description": [], "signature": [ "{ getScopedAnnotationsClient: (requestContext: ", - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { licensing: Promise<", { "pluginId": "licensing", diff --git a/api_docs/observability.mdx b/api_docs/observability.mdx index 80235fb0c5de6..db3f0906e6142 100644 --- a/api_docs/observability.mdx +++ b/api_docs/observability.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/observability title: "observability" image: https://source.unsplash.com/400x175/?github description: API docs for the observability plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'observability'] --- import observabilityObj from './observability.devdocs.json'; diff --git a/api_docs/osquery.mdx b/api_docs/osquery.mdx index f81af5365ebf2..c569e301708df 100644 --- a/api_docs/osquery.mdx +++ b/api_docs/osquery.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/osquery title: "osquery" image: https://source.unsplash.com/400x175/?github description: API docs for the osquery plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'osquery'] --- import osqueryObj from './osquery.devdocs.json'; diff --git a/api_docs/plugin_directory.mdx b/api_docs/plugin_directory.mdx index 909445d75e7e2..568f38705df0a 100644 --- a/api_docs/plugin_directory.mdx +++ b/api_docs/plugin_directory.mdx @@ -7,7 +7,7 @@ id: kibDevDocsPluginDirectory slug: /kibana-dev-docs/api-meta/plugin-api-directory title: Directory description: Directory of public APIs available through plugins or packages. -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana'] --- @@ -15,13 +15,13 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | Count | Plugins or Packages with a
public API | Number of teams | |--------------|----------|------------------------| -| 473 | 395 | 38 | +| 477 | 397 | 38 | ### Public API health stats | API Count | Any Count | Missing comments | Missing exports | |--------------|----------|-----------------|--------| -| 31641 | 179 | 21224 | 998 | +| 31953 | 179 | 21502 | 1003 | ## Plugin Directory @@ -30,7 +30,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 214 | 0 | 209 | 19 | | | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 36 | 1 | 32 | 2 | | | [Machine Learning UI](https://github.com/orgs/elastic/teams/ml-ui) | AIOps plugin maintained by ML team. | 9 | 0 | 0 | 2 | -| | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 370 | 0 | 361 | 22 | +| | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 379 | 0 | 370 | 24 | | | [APM UI](https://github.com/orgs/elastic/teams/apm-ui) | The user interface for Elastic APM | 38 | 0 | 38 | 52 | | | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 9 | 0 | 9 | 0 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Considering using bfetch capabilities when fetching large amounts of data. This services supports batching HTTP requests and streaming responses back. | 80 | 1 | 71 | 2 | @@ -42,12 +42,12 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Cloud Security Posture](https://github.com/orgs/elastic/teams/cloud-posture-security) | The cloud security posture plugin | 18 | 0 | 2 | 3 | | | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 13 | 0 | 13 | 1 | | | [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-presentation) | The Controls Plugin contains embeddable components intended to create a simple query interface for end users, and a powerful editing suite that allows dashboard authors to build controls | 212 | 0 | 204 | 7 | -| | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 2684 | 0 | 35 | 0 | +| | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 2688 | 0 | 30 | 0 | | crossClusterReplication | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 0 | 0 | 0 | 0 | -| | [Fleet](https://github.com/orgs/elastic/teams/fleet) | Add custom data integrations so they can be displayed in the Fleet integrations app | 103 | 0 | 84 | 1 | -| | [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-presentation) | Adds the Dashboard app to Kibana | 144 | 0 | 139 | 10 | +| | [Fleet](https://github.com/orgs/elastic/teams/fleet) | Add custom data integrations so they can be displayed in the Fleet integrations app | 104 | 0 | 85 | 1 | +| | [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-presentation) | Adds the Dashboard app to Kibana | 120 | 0 | 113 | 3 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | - | 52 | 0 | 51 | 0 | -| | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Data services are useful for searching and querying data from Elasticsearch. Helpful utilities include: a re-usable react query bar, KQL autocomplete, async search, Data Views (Index Patterns) and field formatters. | 3132 | 33 | 2429 | 23 | +| | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Data services are useful for searching and querying data from Elasticsearch. Helpful utilities include: a re-usable react query bar, KQL autocomplete, async search, Data Views (Index Patterns) and field formatters. | 3213 | 33 | 2509 | 23 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | This plugin provides the ability to create data views via a modal flyout inside Kibana apps | 15 | 0 | 7 | 0 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Reusable data view field editor across Kibana | 60 | 0 | 30 | 0 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Data view management app | 2 | 0 | 2 | 0 | @@ -60,7 +60,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Extends embeddable plugin with more functionality | 14 | 0 | 14 | 0 | | | [Platform Security](https://github.com/orgs/elastic/teams/kibana-security) | This plugin provides encryption and decryption utilities for saved objects containing sensitive information. | 51 | 0 | 42 | 0 | | | [Enterprise Search](https://github.com/orgs/elastic/teams/enterprise-search-frontend) | Adds dashboards for discovering and managing Enterprise Search products. | 9 | 0 | 9 | 0 | -| | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 114 | 3 | 110 | 3 | +| | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 114 | 3 | 110 | 5 | | | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | The Event Annotation service contains expressions for event annotations | 174 | 0 | 174 | 3 | | | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 106 | 0 | 106 | 10 | | | [Kibana Presentation](https://github.com/orgs/elastic/teams/kibana-presentation) | Adds 'error' renderer to expressions | 17 | 0 | 15 | 2 | @@ -80,8 +80,8 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 222 | 0 | 95 | 2 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Index pattern fields and ambiguous values formatters | 288 | 5 | 249 | 3 | | | [Machine Learning UI](https://github.com/orgs/elastic/teams/ml-ui) | The file upload plugin contains components and services for uploading a file, analyzing its data, and then importing the data into an Elasticsearch index. Supported file types include CSV, TSV, newline-delimited JSON and GeoJSON. | 62 | 0 | 62 | 2 | -| | [@elastic/kibana-app-services](https://github.com/orgs/elastic/teams/team:AppServicesUx) | File upload, download, sharing, and serving over HTTP implementation in Kibana. | 263 | 0 | 15 | 2 | -| | [Fleet](https://github.com/orgs/elastic/teams/fleet) | - | 986 | 3 | 886 | 17 | +| | [@elastic/kibana-app-services](https://github.com/orgs/elastic/teams/team:AppServicesUx) | File upload, download, sharing, and serving over HTTP implementation in Kibana. | 263 | 0 | 14 | 2 | +| | [Fleet](https://github.com/orgs/elastic/teams/fleet) | - | 996 | 3 | 893 | 17 | | | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 68 | 0 | 14 | 5 | | globalSearchBar | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 0 | 0 | 0 | 0 | | globalSearchProviders | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 0 | 0 | 0 | 0 | @@ -101,7 +101,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | kibanaUsageCollection | [Kibana Telemetry](https://github.com/orgs/elastic/teams/kibana-telemetry) | - | 0 | 0 | 0 | 0 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | - | 615 | 3 | 418 | 9 | | | [Security Team](https://github.com/orgs/elastic/teams/security-team) | - | 3 | 0 | 3 | 1 | -| | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Visualization editor allowing to quickly and easily configure compelling visualizations to use on dashboards and canvas workpads. Exposes components to embed visualizations and link into the Lens editor from within other apps in Kibana. | 646 | 0 | 558 | 42 | +| | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Visualization editor allowing to quickly and easily configure compelling visualizations to use on dashboards and canvas workpads. Exposes components to embed visualizations and link into the Lens editor from within other apps in Kibana. | 649 | 0 | 560 | 42 | | | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 8 | 0 | 8 | 0 | | | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 3 | 0 | 3 | 0 | | | [Kibana Core](https://github.com/orgs/elastic/teams/kibana-core) | - | 117 | 0 | 42 | 10 | @@ -152,7 +152,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Security solution](https://github.com/orgs/elastic/teams/security-solution) | - | 452 | 1 | 346 | 33 | | | [Machine Learning UI](https://github.com/orgs/elastic/teams/ml-ui) | This plugin provides access to the transforms features provided by Elastic. Transforms enable you to convert existing Elasticsearch indices into summarized indices, which provide opportunities for new insights and analytics. | 4 | 0 | 4 | 1 | | translations | [Kibana Localization](https://github.com/orgs/elastic/teams/kibana-localization) | - | 0 | 0 | 0 | 0 | -| | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 437 | 1 | 416 | 45 | +| | [Response Ops](https://github.com/orgs/elastic/teams/response-ops) | - | 512 | 1 | 485 | 48 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Adds UI Actions service to Kibana | 132 | 0 | 91 | 11 | | | [App Services](https://github.com/orgs/elastic/teams/kibana-app-services) | Extends UI Actions plugin with more functionality | 206 | 0 | 142 | 9 | | | [Data Discovery](https://github.com/orgs/elastic/teams/kibana-data-discovery) | Contains functionality for the field list which can be integrated into apps | 61 | 0 | 59 | 2 | @@ -175,7 +175,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Registers the vega visualization. Is the elastic version of vega and vega-lite libraries. | 2 | 0 | 2 | 0 | | | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Contains the vislib visualizations. These are the classical area/line/bar, pie, gauge/goal and heatmap charts. We want to replace them with elastic-charts. | 26 | 0 | 25 | 1 | | | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Contains the new xy-axis chart using the elastic-charts library, which will eventually replace the vislib xy-axis charts including bar, area, and line. | 53 | 0 | 50 | 5 | -| | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Contains the shared architecture among all the legacy visualizations, e.g. the visualization type registry or the visualization embeddable. | 631 | 12 | 602 | 14 | +| | [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Contains the shared architecture among all the legacy visualizations, e.g. the visualization type registry or the visualization embeddable. | 693 | 12 | 663 | 18 | | watcher | [Stack Management](https://github.com/orgs/elastic/teams/kibana-stack-management) | - | 0 | 0 | 0 | 0 | ## Package Directory @@ -261,6 +261,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | Kibana Core | - | 16 | 0 | 16 | 0 | | | Kibana Core | - | 4 | 0 | 0 | 0 | | | Kibana Core | - | 10 | 1 | 10 | 0 | +| | Kibana Core | - | 14 | 0 | 11 | 0 | | | Kibana Core | - | 25 | 5 | 25 | 1 | | | Kibana Core | - | 7 | 0 | 7 | 1 | | | Kibana Core | - | 392 | 1 | 154 | 0 | @@ -367,7 +368,7 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | App Services | - | 35 | 4 | 35 | 0 | | | [Owner missing] | - | 20 | 0 | 20 | 2 | | | [Owner missing] | - | 13 | 0 | 13 | 0 | -| | [Owner missing] | - | 62 | 0 | 57 | 5 | +| | [Owner missing] | - | 64 | 0 | 59 | 5 | | | [Owner missing] | - | 96 | 0 | 95 | 0 | | | Kibana Core | - | 30 | 0 | 5 | 37 | | | Kibana Core | - | 8 | 0 | 8 | 0 | @@ -388,10 +389,11 @@ tags: ['contributor', 'dev', 'apidocs', 'kibana'] | | [Owner missing] | - | 74 | 0 | 71 | 0 | | | [Owner missing] | Security Solution auto complete | 56 | 1 | 41 | 1 | | | [Owner missing] | security solution elastic search utilities to use across plugins such lists, security_solution, cases, etc... | 67 | 0 | 61 | 1 | +| | [Owner missing] | - | 76 | 0 | 67 | 1 | | | [Owner missing] | Security Solution utilities for React hooks | 15 | 0 | 7 | 0 | -| | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 148 | 0 | 129 | 0 | +| | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 145 | 0 | 127 | 0 | | | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 505 | 1 | 492 | 0 | -| | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 63 | 0 | 33 | 0 | +| | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 65 | 0 | 36 | 0 | | | [Owner missing] | io ts utilities and types to be shared with plugins from the security solution project | 28 | 0 | 21 | 0 | | | [Owner missing] | security solution list REST API | 67 | 0 | 64 | 0 | | | [Owner missing] | security solution list constants to use across plugins such lists, security_solution, cases, etc... | 33 | 0 | 17 | 0 | diff --git a/api_docs/presentation_util.mdx b/api_docs/presentation_util.mdx index 6624c8da62bc0..099351a2d0f2e 100644 --- a/api_docs/presentation_util.mdx +++ b/api_docs/presentation_util.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/presentationUtil title: "presentationUtil" image: https://source.unsplash.com/400x175/?github description: API docs for the presentationUtil plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'presentationUtil'] --- import presentationUtilObj from './presentation_util.devdocs.json'; diff --git a/api_docs/profiling.mdx b/api_docs/profiling.mdx index b6918294e2a03..2ef17ce2192fa 100644 --- a/api_docs/profiling.mdx +++ b/api_docs/profiling.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/profiling title: "profiling" image: https://source.unsplash.com/400x175/?github description: API docs for the profiling plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'profiling'] --- import profilingObj from './profiling.devdocs.json'; diff --git a/api_docs/remote_clusters.mdx b/api_docs/remote_clusters.mdx index 654fe2d108913..8a248f78f1fa8 100644 --- a/api_docs/remote_clusters.mdx +++ b/api_docs/remote_clusters.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/remoteClusters title: "remoteClusters" image: https://source.unsplash.com/400x175/?github description: API docs for the remoteClusters plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'remoteClusters'] --- import remoteClustersObj from './remote_clusters.devdocs.json'; diff --git a/api_docs/reporting.mdx b/api_docs/reporting.mdx index 2bc4d41ac91fa..9589edc812df2 100644 --- a/api_docs/reporting.mdx +++ b/api_docs/reporting.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/reporting title: "reporting" image: https://source.unsplash.com/400x175/?github description: API docs for the reporting plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'reporting'] --- import reportingObj from './reporting.devdocs.json'; diff --git a/api_docs/rollup.mdx b/api_docs/rollup.mdx index cdf7e02e91c3f..1964dc994cd2e 100644 --- a/api_docs/rollup.mdx +++ b/api_docs/rollup.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/rollup title: "rollup" image: https://source.unsplash.com/400x175/?github description: API docs for the rollup plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'rollup'] --- import rollupObj from './rollup.devdocs.json'; diff --git a/api_docs/rule_registry.devdocs.json b/api_docs/rule_registry.devdocs.json index 424057fd0db70..089f973bc0bf0 100644 --- a/api_docs/rule_registry.devdocs.json +++ b/api_docs/rule_registry.devdocs.json @@ -1917,7 +1917,7 @@ "\nID of the Kibana feature associated with the index.\nUsed by alerts-as-data RBAC.\n\nNote from @dhurley14\nThe purpose of the `feature` param is to force the user to update\nthe data structure which contains the mapping of consumers to alerts\nas data indices. The idea is it is typed such that it forces the\nuser to go to the code and modify it. At least until a better system\nis put in place or we move the alerts as data client out of rule registry.\n" ], "signature": [ - "\"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\" | \"infrastructure\"" + "\"infrastructure\" | \"observability\" | \"logs\" | \"apm\" | \"uptime\" | \"siem\"" ], "path": "x-pack/plugins/rule_registry/server/rule_data_plugin_service/index_options.ts", "deprecated": false, @@ -4270,7 +4270,7 @@ "label": "ParsedTechnicalFields", "description": [], "signature": [ - "{ readonly '@timestamp': string; readonly \"kibana.alert.rule.rule_type_id\": string; readonly \"kibana.alert.rule.consumer\": string; readonly \"kibana.alert.rule.producer\": string; readonly \"kibana.space_ids\": string[]; readonly \"kibana.alert.uuid\": string; readonly \"kibana.alert.instance.id\": string; readonly \"kibana.alert.status\": string; readonly \"kibana.alert.rule.category\": string; readonly \"kibana.alert.rule.uuid\": string; readonly \"kibana.alert.rule.name\": string; readonly tags?: string[] | undefined; readonly 'event.action'?: string | undefined; readonly \"kibana.alert.rule.parameters\"?: { [key: string]: unknown; } | undefined; readonly \"kibana.alert.start\"?: string | undefined; readonly \"kibana.alert.end\"?: string | undefined; readonly \"kibana.alert.duration.us\"?: number | undefined; readonly \"kibana.alert.severity\"?: string | undefined; readonly \"kibana.version\"?: string | undefined; readonly \"ecs.version\"?: string | undefined; readonly \"kibana.alert.risk_score\"?: number | undefined; readonly \"kibana.alert.workflow_status\"?: string | undefined; readonly \"kibana.alert.workflow_user\"?: string | undefined; readonly \"kibana.alert.workflow_reason\"?: string | undefined; readonly \"kibana.alert.system_status\"?: string | undefined; readonly \"kibana.alert.action_group\"?: string | undefined; readonly \"kibana.alert.reason\"?: string | undefined; readonly \"kibana.alert.rule.author\"?: string | undefined; readonly \"kibana.alert.rule.created_at\"?: string | undefined; readonly \"kibana.alert.rule.created_by\"?: string | undefined; readonly \"kibana.alert.rule.description\"?: string | undefined; readonly \"kibana.alert.rule.enabled\"?: string | undefined; readonly \"kibana.alert.rule.execution.uuid\"?: string | undefined; readonly \"kibana.alert.rule.from\"?: string | undefined; readonly \"kibana.alert.rule.interval\"?: string | undefined; readonly \"kibana.alert.rule.license\"?: string | undefined; readonly \"kibana.alert.rule.note\"?: string | undefined; readonly \"kibana.alert.rule.references\"?: string[] | undefined; readonly \"kibana.alert.rule.rule_id\"?: string | undefined; readonly \"kibana.alert.rule.rule_name_override\"?: string | undefined; readonly \"kibana.alert.rule.tags\"?: string[] | undefined; readonly \"kibana.alert.rule.to\"?: string | undefined; readonly \"kibana.alert.rule.type\"?: string | undefined; readonly \"kibana.alert.rule.updated_at\"?: string | undefined; readonly \"kibana.alert.rule.updated_by\"?: string | undefined; readonly \"kibana.alert.rule.version\"?: string | undefined; readonly 'event.kind'?: string | undefined; }" + "{ readonly '@timestamp': string; readonly \"kibana.alert.rule.rule_type_id\": string; readonly \"kibana.alert.rule.consumer\": string; readonly \"kibana.alert.rule.producer\": string; readonly \"kibana.space_ids\": string[]; readonly \"kibana.alert.uuid\": string; readonly \"kibana.alert.instance.id\": string; readonly \"kibana.alert.status\": string; readonly \"kibana.alert.rule.category\": string; readonly \"kibana.alert.rule.uuid\": string; readonly \"kibana.alert.rule.name\": string; readonly tags?: string[] | undefined; readonly 'event.action'?: string | undefined; readonly \"kibana.alert.rule.execution.uuid\"?: string | undefined; readonly \"kibana.alert.rule.parameters\"?: { [key: string]: unknown; } | undefined; readonly \"kibana.alert.start\"?: string | undefined; readonly \"kibana.alert.end\"?: string | undefined; readonly \"kibana.alert.duration.us\"?: number | undefined; readonly \"kibana.alert.severity\"?: string | undefined; readonly \"kibana.version\"?: string | undefined; readonly \"ecs.version\"?: string | undefined; readonly \"kibana.alert.risk_score\"?: number | undefined; readonly \"kibana.alert.workflow_status\"?: string | undefined; readonly \"kibana.alert.workflow_user\"?: string | undefined; readonly \"kibana.alert.workflow_reason\"?: string | undefined; readonly \"kibana.alert.system_status\"?: string | undefined; readonly \"kibana.alert.action_group\"?: string | undefined; readonly \"kibana.alert.reason\"?: string | undefined; readonly \"kibana.alert.rule.author\"?: string | undefined; readonly \"kibana.alert.rule.created_at\"?: string | undefined; readonly \"kibana.alert.rule.created_by\"?: string | undefined; readonly \"kibana.alert.rule.description\"?: string | undefined; readonly \"kibana.alert.rule.enabled\"?: string | undefined; readonly \"kibana.alert.rule.from\"?: string | undefined; readonly \"kibana.alert.rule.interval\"?: string | undefined; readonly \"kibana.alert.rule.license\"?: string | undefined; readonly \"kibana.alert.rule.note\"?: string | undefined; readonly \"kibana.alert.rule.references\"?: string[] | undefined; readonly \"kibana.alert.rule.rule_id\"?: string | undefined; readonly \"kibana.alert.rule.rule_name_override\"?: string | undefined; readonly \"kibana.alert.rule.tags\"?: string[] | undefined; readonly \"kibana.alert.rule.to\"?: string | undefined; readonly \"kibana.alert.rule.type\"?: string | undefined; readonly \"kibana.alert.rule.updated_at\"?: string | undefined; readonly \"kibana.alert.rule.updated_by\"?: string | undefined; readonly \"kibana.alert.rule.version\"?: string | undefined; readonly 'event.kind'?: string | undefined; }" ], "path": "x-pack/plugins/rule_registry/common/parse_technical_fields.ts", "deprecated": false, diff --git a/api_docs/rule_registry.mdx b/api_docs/rule_registry.mdx index 4ddc32f331d94..d4539ef64efa0 100644 --- a/api_docs/rule_registry.mdx +++ b/api_docs/rule_registry.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/ruleRegistry title: "ruleRegistry" image: https://source.unsplash.com/400x175/?github description: API docs for the ruleRegistry plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'ruleRegistry'] --- import ruleRegistryObj from './rule_registry.devdocs.json'; diff --git a/api_docs/runtime_fields.mdx b/api_docs/runtime_fields.mdx index d84f83787e909..8112f8684b552 100644 --- a/api_docs/runtime_fields.mdx +++ b/api_docs/runtime_fields.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/runtimeFields title: "runtimeFields" image: https://source.unsplash.com/400x175/?github description: API docs for the runtimeFields plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'runtimeFields'] --- import runtimeFieldsObj from './runtime_fields.devdocs.json'; diff --git a/api_docs/saved_objects.devdocs.json b/api_docs/saved_objects.devdocs.json index 6d40e242e3cd5..71d53634b7540 100644 --- a/api_docs/saved_objects.devdocs.json +++ b/api_docs/saved_objects.devdocs.json @@ -1557,18 +1557,6 @@ "plugin": "savedObjectsTaggingOss", "path": "src/plugins/saved_objects_tagging_oss/public/api.ts" }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/services/saved_object_loader.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/services/saved_object_loader.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/services/saved_object_loader.ts" - }, { "plugin": "dashboard", "path": "src/plugins/dashboard/public/application/actions/clone_panel_action.tsx" @@ -1580,22 +1568,6 @@ { "plugin": "dashboard", "path": "src/plugins/dashboard/public/application/actions/clone_panel_action.tsx" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/application/lib/dashboard_tagging.ts" - }, - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/application/lib/dashboard_tagging.ts" } ], "children": [ @@ -3121,12 +3093,7 @@ "deprecated": true, "removeBy": "8.8.0", "trackAdoption": false, - "references": [ - { - "plugin": "dashboard", - "path": "src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts" - } - ] + "references": [] }, { "parentPluginId": "savedObjects", diff --git a/api_docs/saved_objects.mdx b/api_docs/saved_objects.mdx index 4444520e994a7..613f942ef9065 100644 --- a/api_docs/saved_objects.mdx +++ b/api_docs/saved_objects.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedObjects title: "savedObjects" image: https://source.unsplash.com/400x175/?github description: API docs for the savedObjects plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedObjects'] --- import savedObjectsObj from './saved_objects.devdocs.json'; diff --git a/api_docs/saved_objects_finder.mdx b/api_docs/saved_objects_finder.mdx index 15a8248a430dd..23cf7d31ca48e 100644 --- a/api_docs/saved_objects_finder.mdx +++ b/api_docs/saved_objects_finder.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedObjectsFinder title: "savedObjectsFinder" image: https://source.unsplash.com/400x175/?github description: API docs for the savedObjectsFinder plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedObjectsFinder'] --- import savedObjectsFinderObj from './saved_objects_finder.devdocs.json'; diff --git a/api_docs/saved_objects_management.mdx b/api_docs/saved_objects_management.mdx index b82b505e41344..c9cc4aa61ea7c 100644 --- a/api_docs/saved_objects_management.mdx +++ b/api_docs/saved_objects_management.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedObjectsManagement title: "savedObjectsManagement" image: https://source.unsplash.com/400x175/?github description: API docs for the savedObjectsManagement plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedObjectsManagement'] --- import savedObjectsManagementObj from './saved_objects_management.devdocs.json'; diff --git a/api_docs/saved_objects_tagging.mdx b/api_docs/saved_objects_tagging.mdx index 85434d08daeba..1450399aefd83 100644 --- a/api_docs/saved_objects_tagging.mdx +++ b/api_docs/saved_objects_tagging.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedObjectsTagging title: "savedObjectsTagging" image: https://source.unsplash.com/400x175/?github description: API docs for the savedObjectsTagging plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedObjectsTagging'] --- import savedObjectsTaggingObj from './saved_objects_tagging.devdocs.json'; diff --git a/api_docs/saved_objects_tagging_oss.mdx b/api_docs/saved_objects_tagging_oss.mdx index fc726fe5227b6..1ed5aa9d511ea 100644 --- a/api_docs/saved_objects_tagging_oss.mdx +++ b/api_docs/saved_objects_tagging_oss.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedObjectsTaggingOss title: "savedObjectsTaggingOss" image: https://source.unsplash.com/400x175/?github description: API docs for the savedObjectsTaggingOss plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedObjectsTaggingOss'] --- import savedObjectsTaggingOssObj from './saved_objects_tagging_oss.devdocs.json'; diff --git a/api_docs/saved_search.devdocs.json b/api_docs/saved_search.devdocs.json index df52fe959fea2..8e6b2e5503d3c 100644 --- a/api_docs/saved_search.devdocs.json +++ b/api_docs/saved_search.devdocs.json @@ -661,7 +661,7 @@ "label": "sharingSavedObjectProps", "description": [], "signature": [ - "{ outcome?: \"exactMatch\" | \"aliasMatch\" | \"conflict\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" + "{ outcome?: \"conflict\" | \"exactMatch\" | \"aliasMatch\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" ], "path": "src/plugins/saved_search/public/services/saved_searches/types.ts", "deprecated": false, diff --git a/api_docs/saved_search.mdx b/api_docs/saved_search.mdx index bb71e1eb7e460..6c1900781f66a 100644 --- a/api_docs/saved_search.mdx +++ b/api_docs/saved_search.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/savedSearch title: "savedSearch" image: https://source.unsplash.com/400x175/?github description: API docs for the savedSearch plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'savedSearch'] --- import savedSearchObj from './saved_search.devdocs.json'; diff --git a/api_docs/screenshot_mode.devdocs.json b/api_docs/screenshot_mode.devdocs.json index c6be83e928479..ab834dfc733bc 100644 --- a/api_docs/screenshot_mode.devdocs.json +++ b/api_docs/screenshot_mode.devdocs.json @@ -139,13 +139,7 @@ "label": "ScreenshotModeRequestHandlerContext", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.RequestHandlerContext", - "text": "RequestHandlerContext" - }, + "RequestHandlerContext", " & { screenshotMode: Promise<{ isScreenshot: boolean; }>; }" ], "path": "src/plugins/screenshot_mode/server/types.ts", diff --git a/api_docs/screenshot_mode.mdx b/api_docs/screenshot_mode.mdx index c8f54246304fc..883f8e26e2cc0 100644 --- a/api_docs/screenshot_mode.mdx +++ b/api_docs/screenshot_mode.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/screenshotMode title: "screenshotMode" image: https://source.unsplash.com/400x175/?github description: API docs for the screenshotMode plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'screenshotMode'] --- import screenshotModeObj from './screenshot_mode.devdocs.json'; diff --git a/api_docs/screenshotting.mdx b/api_docs/screenshotting.mdx index 8da7ec4e85bfa..df0feab2c445c 100644 --- a/api_docs/screenshotting.mdx +++ b/api_docs/screenshotting.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/screenshotting title: "screenshotting" image: https://source.unsplash.com/400x175/?github description: API docs for the screenshotting plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'screenshotting'] --- import screenshottingObj from './screenshotting.devdocs.json'; diff --git a/api_docs/security.mdx b/api_docs/security.mdx index 641107ddb0e5b..814d0173f69cf 100644 --- a/api_docs/security.mdx +++ b/api_docs/security.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/security title: "security" image: https://source.unsplash.com/400x175/?github description: API docs for the security plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'security'] --- import securityObj from './security.devdocs.json'; diff --git a/api_docs/security_solution.devdocs.json b/api_docs/security_solution.devdocs.json index 1d69c84ad5c82..c3ab461b2eb22 100644 --- a/api_docs/security_solution.devdocs.json +++ b/api_docs/security_solution.devdocs.json @@ -58,7 +58,7 @@ "label": "experimentalFeatures", "description": [], "signature": [ - "{ readonly tGridEnabled: boolean; readonly tGridEventRenderedViewEnabled: boolean; readonly excludePoliciesInFilterEnabled: boolean; readonly kubernetesEnabled: boolean; readonly disableIsolationUIPendingStatuses: boolean; readonly pendingActionResponsesWithAck: boolean; readonly policyListEnabled: boolean; readonly policyResponseInFleetEnabled: boolean; readonly threatIntelligenceEnabled: boolean; readonly previewTelemetryUrlEnabled: boolean; readonly responseActionsConsoleEnabled: boolean; readonly insightsRelatedAlertsByProcessAncestry: boolean; readonly extendedRuleExecutionLoggingEnabled: boolean; readonly socTrendsEnabled: boolean; readonly responseActionsEnabled: boolean; }" + "{ readonly tGridEnabled: boolean; readonly tGridEventRenderedViewEnabled: boolean; readonly excludePoliciesInFilterEnabled: boolean; readonly kubernetesEnabled: boolean; readonly disableIsolationUIPendingStatuses: boolean; readonly pendingActionResponsesWithAck: boolean; readonly policyListEnabled: boolean; readonly policyResponseInFleetEnabled: boolean; readonly previewTelemetryUrlEnabled: boolean; readonly responseActionsConsoleEnabled: boolean; readonly insightsRelatedAlertsByProcessAncestry: boolean; readonly extendedRuleExecutionLoggingEnabled: boolean; readonly socTrendsEnabled: boolean; readonly responseActionsEnabled: boolean; readonly endpointRbacEnabled: boolean; }" ], "path": "x-pack/plugins/security_solution/public/plugin.tsx", "deprecated": false, @@ -768,13 +768,7 @@ "label": "core", "description": [], "signature": [ - { - "pluginId": "core", - "scope": "server", - "docId": "kibCorePluginApi", - "section": "def-server.CoreRequestHandlerContext", - "text": "CoreRequestHandlerContext" - } + "CoreRequestHandlerContext" ], "path": "x-pack/plugins/security_solution/server/types.ts", "deprecated": false, @@ -1061,7 +1055,7 @@ "label": "ConfigType", "description": [], "signature": [ - "Readonly<{} & { signalsIndex: string; maxRuleImportExportSize: number; maxRuleImportPayloadBytes: number; maxTimelineImportExportSize: number; maxTimelineImportPayloadBytes: number; alertMergeStrategy: \"allFields\" | \"missingFields\" | \"noFields\"; alertIgnoreFields: string[]; enableExperimental: string[]; packagerTaskInterval: string; prebuiltRulesFromFileSystem: boolean; prebuiltRulesFromSavedObjects: boolean; }> & { experimentalFeatures: Readonly<{ tGridEnabled: boolean; tGridEventRenderedViewEnabled: boolean; excludePoliciesInFilterEnabled: boolean; kubernetesEnabled: boolean; disableIsolationUIPendingStatuses: boolean; pendingActionResponsesWithAck: boolean; policyListEnabled: boolean; policyResponseInFleetEnabled: boolean; threatIntelligenceEnabled: boolean; previewTelemetryUrlEnabled: boolean; responseActionsConsoleEnabled: boolean; insightsRelatedAlertsByProcessAncestry: boolean; extendedRuleExecutionLoggingEnabled: boolean; socTrendsEnabled: boolean; responseActionsEnabled: boolean; }>; }" + "Readonly<{} & { signalsIndex: string; maxRuleImportExportSize: number; maxRuleImportPayloadBytes: number; maxTimelineImportExportSize: number; maxTimelineImportPayloadBytes: number; alertMergeStrategy: \"allFields\" | \"missingFields\" | \"noFields\"; alertIgnoreFields: string[]; enableExperimental: string[]; packagerTaskInterval: string; prebuiltRulesFromFileSystem: boolean; prebuiltRulesFromSavedObjects: boolean; }> & { experimentalFeatures: Readonly<{ tGridEnabled: boolean; tGridEventRenderedViewEnabled: boolean; excludePoliciesInFilterEnabled: boolean; kubernetesEnabled: boolean; disableIsolationUIPendingStatuses: boolean; pendingActionResponsesWithAck: boolean; policyListEnabled: boolean; policyResponseInFleetEnabled: boolean; previewTelemetryUrlEnabled: boolean; responseActionsConsoleEnabled: boolean; insightsRelatedAlertsByProcessAncestry: boolean; extendedRuleExecutionLoggingEnabled: boolean; socTrendsEnabled: boolean; responseActionsEnabled: boolean; endpointRbacEnabled: boolean; }>; }" ], "path": "x-pack/plugins/security_solution/server/config.ts", "deprecated": false, diff --git a/api_docs/security_solution.mdx b/api_docs/security_solution.mdx index 4dfc5304eeabc..a86c48a48dfce 100644 --- a/api_docs/security_solution.mdx +++ b/api_docs/security_solution.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/securitySolution title: "securitySolution" image: https://source.unsplash.com/400x175/?github description: API docs for the securitySolution plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'securitySolution'] --- import securitySolutionObj from './security_solution.devdocs.json'; diff --git a/api_docs/session_view.mdx b/api_docs/session_view.mdx index 3d6c984a674d4..66978ad664e04 100644 --- a/api_docs/session_view.mdx +++ b/api_docs/session_view.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/sessionView title: "sessionView" image: https://source.unsplash.com/400x175/?github description: API docs for the sessionView plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'sessionView'] --- import sessionViewObj from './session_view.devdocs.json'; diff --git a/api_docs/share.mdx b/api_docs/share.mdx index c99d1ff617c66..0086ad02ab5ac 100644 --- a/api_docs/share.mdx +++ b/api_docs/share.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/share title: "share" image: https://source.unsplash.com/400x175/?github description: API docs for the share plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'share'] --- import shareObj from './share.devdocs.json'; diff --git a/api_docs/snapshot_restore.mdx b/api_docs/snapshot_restore.mdx index 3e77d10e0c059..7bce31d6e1832 100644 --- a/api_docs/snapshot_restore.mdx +++ b/api_docs/snapshot_restore.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/snapshotRestore title: "snapshotRestore" image: https://source.unsplash.com/400x175/?github description: API docs for the snapshotRestore plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'snapshotRestore'] --- import snapshotRestoreObj from './snapshot_restore.devdocs.json'; diff --git a/api_docs/spaces.mdx b/api_docs/spaces.mdx index 992d92531e643..decf22f6da092 100644 --- a/api_docs/spaces.mdx +++ b/api_docs/spaces.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/spaces title: "spaces" image: https://source.unsplash.com/400x175/?github description: API docs for the spaces plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'spaces'] --- import spacesObj from './spaces.devdocs.json'; diff --git a/api_docs/stack_alerts.mdx b/api_docs/stack_alerts.mdx index c2e72b56ca6cd..e68ecfcdfb999 100644 --- a/api_docs/stack_alerts.mdx +++ b/api_docs/stack_alerts.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/stackAlerts title: "stackAlerts" image: https://source.unsplash.com/400x175/?github description: API docs for the stackAlerts plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'stackAlerts'] --- import stackAlertsObj from './stack_alerts.devdocs.json'; diff --git a/api_docs/stack_connectors.mdx b/api_docs/stack_connectors.mdx index 26e060f27c7b3..5363b913fbe0c 100644 --- a/api_docs/stack_connectors.mdx +++ b/api_docs/stack_connectors.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/stackConnectors title: "stackConnectors" image: https://source.unsplash.com/400x175/?github description: API docs for the stackConnectors plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'stackConnectors'] --- import stackConnectorsObj from './stack_connectors.devdocs.json'; diff --git a/api_docs/task_manager.mdx b/api_docs/task_manager.mdx index f5999857a32d8..7377ef34d529c 100644 --- a/api_docs/task_manager.mdx +++ b/api_docs/task_manager.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/taskManager title: "taskManager" image: https://source.unsplash.com/400x175/?github description: API docs for the taskManager plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'taskManager'] --- import taskManagerObj from './task_manager.devdocs.json'; diff --git a/api_docs/telemetry.mdx b/api_docs/telemetry.mdx index 3fb0b4f960ea8..1a95f8384f249 100644 --- a/api_docs/telemetry.mdx +++ b/api_docs/telemetry.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/telemetry title: "telemetry" image: https://source.unsplash.com/400x175/?github description: API docs for the telemetry plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'telemetry'] --- import telemetryObj from './telemetry.devdocs.json'; diff --git a/api_docs/telemetry_collection_manager.mdx b/api_docs/telemetry_collection_manager.mdx index f111e7af6b6be..355a38255c9c3 100644 --- a/api_docs/telemetry_collection_manager.mdx +++ b/api_docs/telemetry_collection_manager.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/telemetryCollectionManager title: "telemetryCollectionManager" image: https://source.unsplash.com/400x175/?github description: API docs for the telemetryCollectionManager plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'telemetryCollectionManager'] --- import telemetryCollectionManagerObj from './telemetry_collection_manager.devdocs.json'; diff --git a/api_docs/telemetry_collection_xpack.mdx b/api_docs/telemetry_collection_xpack.mdx index 8af81d0546f13..e607fc3598bd1 100644 --- a/api_docs/telemetry_collection_xpack.mdx +++ b/api_docs/telemetry_collection_xpack.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/telemetryCollectionXpack title: "telemetryCollectionXpack" image: https://source.unsplash.com/400x175/?github description: API docs for the telemetryCollectionXpack plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'telemetryCollectionXpack'] --- import telemetryCollectionXpackObj from './telemetry_collection_xpack.devdocs.json'; diff --git a/api_docs/telemetry_management_section.mdx b/api_docs/telemetry_management_section.mdx index ef4366af03426..f538309dd4628 100644 --- a/api_docs/telemetry_management_section.mdx +++ b/api_docs/telemetry_management_section.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/telemetryManagementSection title: "telemetryManagementSection" image: https://source.unsplash.com/400x175/?github description: API docs for the telemetryManagementSection plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'telemetryManagementSection'] --- import telemetryManagementSectionObj from './telemetry_management_section.devdocs.json'; diff --git a/api_docs/threat_intelligence.mdx b/api_docs/threat_intelligence.mdx index 3ee232106709f..bcebf8f8b9342 100644 --- a/api_docs/threat_intelligence.mdx +++ b/api_docs/threat_intelligence.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/threatIntelligence title: "threatIntelligence" image: https://source.unsplash.com/400x175/?github description: API docs for the threatIntelligence plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'threatIntelligence'] --- import threatIntelligenceObj from './threat_intelligence.devdocs.json'; diff --git a/api_docs/timelines.devdocs.json b/api_docs/timelines.devdocs.json index be005c7cd4081..4b5ec5ce28970 100644 --- a/api_docs/timelines.devdocs.json +++ b/api_docs/timelines.devdocs.json @@ -3192,7 +3192,7 @@ "IFieldSubType", " | undefined; type?: string | undefined; })[]; id: string; title: string; filters?: ", "Filter", - "[] | undefined; dataViewId: string | null; sort: ", + "[] | undefined; dataViewId: string | null; savedObjectId: string | null; sort: ", "SortColumnTimeline", "[]; version: string | null; filterManager?: ", { @@ -3218,7 +3218,7 @@ }, "; description?: string | null | undefined; esTypes?: string[] | undefined; example?: string | number | null | undefined; format?: string | undefined; linkField?: string | undefined; placeholder?: string | undefined; subType?: ", "IFieldSubType", - " | undefined; type?: string | undefined; })[]; savedObjectId: string | null; isLoading: boolean; dataProviders: ", + " | undefined; type?: string | undefined; })[]; isLoading: boolean; dataProviders: ", { "pluginId": "timelines", "scope": "common", @@ -6073,7 +6073,7 @@ "label": "language", "description": [], "signature": [ - "\"eql\" | \"kuery\" | \"lucene\"" + "\"eql\" | \"lucene\" | \"kuery\"" ], "path": "x-pack/plugins/timelines/common/search_strategy/timeline/events/all/index.ts", "deprecated": false, diff --git a/api_docs/timelines.mdx b/api_docs/timelines.mdx index d84205e784a76..7a96d016a99c9 100644 --- a/api_docs/timelines.mdx +++ b/api_docs/timelines.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/timelines title: "timelines" image: https://source.unsplash.com/400x175/?github description: API docs for the timelines plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'timelines'] --- import timelinesObj from './timelines.devdocs.json'; diff --git a/api_docs/transform.mdx b/api_docs/transform.mdx index de5cb836726ce..7d3c611c084ba 100644 --- a/api_docs/transform.mdx +++ b/api_docs/transform.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/transform title: "transform" image: https://source.unsplash.com/400x175/?github description: API docs for the transform plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'transform'] --- import transformObj from './transform.devdocs.json'; diff --git a/api_docs/triggers_actions_ui.devdocs.json b/api_docs/triggers_actions_ui.devdocs.json index 59be983bb00f5..d6351e414ae46 100644 --- a/api_docs/triggers_actions_ui.devdocs.json +++ b/api_docs/triggers_actions_ui.devdocs.json @@ -303,6 +303,38 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ButtonGroupField", + "type": "Function", + "tags": [], + "label": "ButtonGroupField", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/button_group_field.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ButtonGroupField.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.CreateConnectorFlyout", @@ -832,6 +864,145 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.hasMustacheTokens", + "type": "Function", + "tags": [], + "label": "hasMustacheTokens", + "description": [], + "signature": [ + "(str: string) => boolean" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/has_mustache_tokens.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.hasMustacheTokens.$1", + "type": "string", + "tags": [], + "label": "str", + "description": [], + "signature": [ + "string" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/has_mustache_tokens.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.HiddenField", + "type": "Function", + "tags": [], + "label": "HiddenField", + "description": [], + "signature": [ + "React.NamedExoticComponent<", + "Props", + "> & { readonly type: (props: ", + "Props", + ") => JSX.Element; }" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/hidden_field.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.HiddenField.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.JsonEditorWithMessageVariables", + "type": "Function", + "tags": [], + "label": "JsonEditorWithMessageVariables", + "description": [], + "signature": [ + "({ buttonTitle, messageVariables, paramsProperty, inputTargetValue, label, errors, areaLabel, onDocumentsChange, helpText, onBlur, showButtonTitle, euiCodeEditorProps, }: React.PropsWithChildren) => JSX.Element" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.JsonEditorWithMessageVariables.$1", + "type": "CompoundType", + "tags": [], + "label": "{\n buttonTitle,\n messageVariables,\n paramsProperty,\n inputTargetValue,\n label,\n errors,\n areaLabel,\n onDocumentsChange,\n helpText,\n onBlur,\n showButtonTitle,\n euiCodeEditorProps = {},\n}", + "description": [], + "signature": [ + "React.PropsWithChildren" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.JsonFieldWrapper", + "type": "Function", + "tags": [], + "label": "JsonFieldWrapper", + "description": [], + "signature": [ + "({ field, ...rest }: Props) => JSX.Element" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/json_field_wrapper.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.JsonFieldWrapper.$1", + "type": "Object", + "tags": [], + "label": "{ field, ...rest }", + "description": [], + "signature": [ + "Props" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/json_field_wrapper.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.loadActionErrorLog", @@ -1398,6 +1569,39 @@ "returnComment": [], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.MustacheTextFieldWrapper", + "type": "Function", + "tags": [], + "label": "MustacheTextFieldWrapper", + "description": [], + "signature": [ + "({ field, euiFieldProps, idAria, ...rest }: Props) => JSX.Element" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/mustache_text_field_wrapper.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.MustacheTextFieldWrapper.$1", + "type": "Object", + "tags": [], + "label": "{ field, euiFieldProps, idAria, ...rest }", + "description": [], + "signature": [ + "Props" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/mustache_text_field_wrapper.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.muteRule", @@ -1490,6 +1694,70 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.PasswordField", + "type": "Function", + "tags": [], + "label": "PasswordField", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/password_field.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.PasswordField.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.SimpleConnectorForm", + "type": "Function", + "tags": [], + "label": "SimpleConnectorForm", + "description": [], + "signature": [ + "React.NamedExoticComponent" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.tsx", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.SimpleConnectorForm.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.snoozeRule", @@ -1614,72 +1882,185 @@ }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.ThresholdExpression", + "id": "def-public.templateActionVariable", "type": "Function", "tags": [], - "label": "ThresholdExpression", + "label": "templateActionVariable", "description": [], "signature": [ - "(props: ", - "ThresholdExpressionProps", - ") => JSX.Element" + "(variable: ", + { + "pluginId": "alerting", + "scope": "common", + "docId": "kibAlertingPluginApi", + "section": "def-common.ActionVariable", + "text": "ActionVariable" + }, + ") => string" ], - "path": "x-pack/plugins/triggers_actions_ui/public/common/expression_items/index.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/template_action_variable.ts", "deprecated": false, "trackAdoption": false, - "returnComment": [], "children": [ { "parentPluginId": "triggersActionsUi", - "id": "def-public.ThresholdExpression.$1", - "type": "Uncategorized", + "id": "def-public.templateActionVariable.$1", + "type": "Object", "tags": [], - "label": "props", + "label": "variable", "description": [], "signature": [ - "T" + { + "pluginId": "alerting", + "scope": "common", + "docId": "kibAlertingPluginApi", + "section": "def-common.ActionVariable", + "text": "ActionVariable" + } ], - "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/suspended_component_with_props.tsx", + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/template_action_variable.ts", "deprecated": false, - "trackAdoption": false + "trackAdoption": false, + "isRequired": true } ], + "returnComment": [], "initialIsOpen": false }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.unmuteRule", + "id": "def-public.TextAreaWithMessageVariables", "type": "Function", "tags": [], - "label": "unmuteRule", + "label": "TextAreaWithMessageVariables", "description": [], "signature": [ - "({ id, http }: { id: string; http: ", - "HttpSetup", - "; }) => Promise" + "({ messageVariables, paramsProperty, index, inputTargetValue, isDisabled, editAction, label, errors, }: React.PropsWithChildren) => JSX.Element" ], - "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unmute.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/text_area_with_message_variables.tsx", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "triggersActionsUi", - "id": "def-public.unmuteRule.$1", - "type": "Object", + "id": "def-public.TextAreaWithMessageVariables.$1", + "type": "CompoundType", "tags": [], - "label": "{ id, http }", + "label": "{\n messageVariables,\n paramsProperty,\n index,\n inputTargetValue,\n isDisabled = false,\n editAction,\n label,\n errors,\n}", "description": [], - "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unmute.ts", + "signature": [ + "React.PropsWithChildren" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/text_area_with_message_variables.tsx", "deprecated": false, "trackAdoption": false, - "children": [ - { - "parentPluginId": "triggersActionsUi", - "id": "def-public.unmuteRule.$1.id", - "type": "string", - "tags": [], - "label": "id", - "description": [], + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.TextFieldWithMessageVariables", + "type": "Function", + "tags": [], + "label": "TextFieldWithMessageVariables", + "description": [], + "signature": [ + "({ buttonTitle, messageVariables, paramsProperty, index, inputTargetValue, editAction, errors, formRowProps, defaultValue, wrapField, showButtonTitle, }: React.PropsWithChildren) => JSX.Element" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/text_field_with_message_variables.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.TextFieldWithMessageVariables.$1", + "type": "CompoundType", + "tags": [], + "label": "{\n buttonTitle,\n messageVariables,\n paramsProperty,\n index,\n inputTargetValue,\n editAction,\n errors,\n formRowProps,\n defaultValue,\n wrapField = false,\n showButtonTitle,\n}", + "description": [], + "signature": [ + "React.PropsWithChildren" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/text_field_with_message_variables.tsx", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ThresholdExpression", + "type": "Function", + "tags": [], + "label": "ThresholdExpression", + "description": [], + "signature": [ + "(props: ", + "ThresholdExpressionProps", + ") => JSX.Element" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/common/expression_items/index.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ThresholdExpression.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "T" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/suspended_component_with_props.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.unmuteRule", + "type": "Function", + "tags": [], + "label": "unmuteRule", + "description": [], + "signature": [ + "({ id, http }: { id: string; http: ", + "HttpSetup", + "; }) => Promise" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unmute.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.unmuteRule.$1", + "type": "Object", + "tags": [], + "label": "{ id, http }", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unmute.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.unmuteRule.$1.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unmute.ts", "deprecated": false, "trackAdoption": false @@ -1776,6 +2157,106 @@ "returnComment": [], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.updateActionConnector", + "type": "Function", + "tags": [], + "label": "updateActionConnector", + "description": [], + "signature": [ + "({\n http,\n connector,\n id,\n}: { http: ", + "HttpSetup", + "; connector: Pick<", + "ActionConnectorWithoutId", + ", Record>, \"name\" | \"config\" | \"secrets\">; id: string; }) => Promise<", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionConnector", + "text": "ActionConnector" + }, + ", Record>>" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_connector_api/update.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.updateActionConnector.$1", + "type": "Object", + "tags": [], + "label": "{\n http,\n connector,\n id,\n}", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_connector_api/update.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.updateActionConnector.$1.http", + "type": "Object", + "tags": [], + "label": "http", + "description": [], + "signature": [ + "HttpSetup" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_connector_api/update.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.updateActionConnector.$1.connector", + "type": "Object", + "tags": [], + "label": "connector", + "description": [], + "signature": [ + "{ name: string; config: Record; secrets: Record; }" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_connector_api/update.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.updateActionConnector.$1.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_connector_api/update.ts", + "deprecated": false, + "trackAdoption": false + } + ] + } + ], + "returnComment": [], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.useConnectorContext", + "type": "Function", + "tags": [], + "label": "useConnectorContext", + "description": [], + "signature": [ + "() => ", + "ConnectorContextValue" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/context/use_connector_context.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.useLoadRuleTypes", @@ -1819,6 +2300,41 @@ "returnComment": [], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.useTypedKibana", + "type": "Function", + "tags": [], + "label": "useTypedKibana", + "description": [], + "signature": [ + "() => ", + { + "pluginId": "kibanaReact", + "scope": "public", + "docId": "kibKibanaReactPluginApi", + "section": "def-public.KibanaReactContextValue", + "text": "KibanaReactContextValue" + }, + " & ", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.TriggersAndActionsUiServices", + "text": "TriggersAndActionsUiServices" + }, + ">" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/common/lib/kibana/kibana_react.ts", + "deprecated": false, + "trackAdoption": false, + "children": [], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.ValueExpression", @@ -1891,95 +2407,651 @@ "interfaces": [ { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType", + "id": "def-public.ActionConnectorFieldsProps", "type": "Interface", "tags": [], - "label": "ActionType", + "label": "ActionConnectorFieldsProps", "description": [], - "path": "x-pack/plugins/actions/common/types.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.id", - "type": "string", - "tags": [], - "label": "id", - "description": [], - "path": "x-pack/plugins/actions/common/types.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.name", - "type": "string", - "tags": [], - "label": "name", - "description": [], - "path": "x-pack/plugins/actions/common/types.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.enabled", + "id": "def-public.ActionConnectorFieldsProps.readOnly", "type": "boolean", "tags": [], - "label": "enabled", + "label": "readOnly", "description": [], - "path": "x-pack/plugins/actions/common/types.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.enabledInConfig", + "id": "def-public.ActionConnectorFieldsProps.isEdit", "type": "boolean", "tags": [], - "label": "enabledInConfig", + "label": "isEdit", "description": [], - "path": "x-pack/plugins/actions/common/types.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.enabledInLicense", - "type": "boolean", + "id": "def-public.ActionConnectorFieldsProps.registerPreSubmitValidator", + "type": "Function", "tags": [], - "label": "enabledInLicense", + "label": "registerPreSubmitValidator", "description": [], - "path": "x-pack/plugins/actions/common/types.ts", + "signature": [ + "(validator: ", + "ConnectorValidationFunc", + ") => void" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionConnectorFieldsProps.registerPreSubmitValidator.$1", + "type": "Function", + "tags": [], + "label": "validator", + "description": [], + "signature": [ + "ConnectorValidationFunc" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps", + "type": "Interface", + "tags": [], + "label": "ActionParamsProps", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionParamsProps", + "text": "ActionParamsProps" + }, + "" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.actionParams", + "type": "Object", + "tags": [], + "label": "actionParams", + "description": [], + "signature": [ + "{ [P in keyof TParams]?: TParams[P] | undefined; }" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.index", + "type": "number", + "tags": [], + "label": "index", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.editAction", + "type": "Function", + "tags": [], + "label": "editAction", + "description": [], + "signature": [ + "(key: string, value: ", + "SavedObjectAttribute", + ", index: number) => void" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.editAction.$1", + "type": "string", + "tags": [], + "label": "key", + "description": [], + "signature": [ + "string" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.editAction.$2", + "type": "CompoundType", + "tags": [], + "label": "value", + "description": [], + "signature": [ + "SavedObjectAttribute" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.editAction.$3", + "type": "number", + "tags": [], + "label": "index", + "description": [], + "signature": [ + "number" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.errors", + "type": "Object", + "tags": [], + "label": "errors", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.IErrorObject", + "text": "IErrorObject" + } + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.messageVariables", + "type": "Array", + "tags": [], + "label": "messageVariables", + "description": [], + "signature": [ + { + "pluginId": "alerting", + "scope": "common", + "docId": "kibAlertingPluginApi", + "section": "def-common.ActionVariable", + "text": "ActionVariable" + }, + "[] | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.defaultMessage", + "type": "string", + "tags": [], + "label": "defaultMessage", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.actionConnector", + "type": "CompoundType", + "tags": [], + "label": "actionConnector", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionConnector", + "text": "ActionConnector" + }, + ", Record> | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.isLoading", + "type": "CompoundType", + "tags": [], + "label": "isLoading", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.isDisabled", + "type": "CompoundType", + "tags": [], + "label": "isDisabled", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionParamsProps.showEmailSubjectAndMessage", + "type": "CompoundType", + "tags": [], + "label": "showEmailSubjectAndMessage", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType", + "type": "Interface", + "tags": [], + "label": "ActionType", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.name", + "type": "string", + "tags": [], + "label": "name", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.enabled", + "type": "boolean", + "tags": [], + "label": "enabled", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.enabledInConfig", + "type": "boolean", + "tags": [], + "label": "enabledInConfig", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.enabledInLicense", + "type": "boolean", + "tags": [], + "label": "enabledInLicense", + "description": [], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.minimumLicenseRequired", + "type": "CompoundType", + "tags": [], + "label": "minimumLicenseRequired", + "description": [], + "signature": [ + "\"basic\" | \"standard\" | \"gold\" | \"platinum\" | \"enterprise\" | \"trial\"" + ], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionType.supportedFeatureIds", + "type": "Array", + "tags": [], + "label": "supportedFeatureIds", + "description": [], + "signature": [ + "string[]" + ], + "path": "x-pack/plugins/actions/common/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel", + "type": "Interface", + "tags": [], + "label": "ActionTypeModel", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, + "" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.id", + "type": "string", + "tags": [], + "label": "id", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.iconClass", + "type": "CompoundType", + "tags": [], + "label": "iconClass", + "description": [], + "signature": [ + "string | React.ComponentType<{}>" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.selectMessage", + "type": "string", + "tags": [], + "label": "selectMessage", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.actionTypeTitle", + "type": "string", + "tags": [], + "label": "actionTypeTitle", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.validateParams", + "type": "Function", + "tags": [], + "label": "validateParams", + "description": [], + "signature": [ + "(actionParams: ActionParams) => Promise<", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.GenericValidationResult", + "text": "GenericValidationResult" + }, + ">" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.validateParams.$1", + "type": "Uncategorized", + "tags": [], + "label": "actionParams", + "description": [], + "signature": [ + "ActionParams" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [] + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.actionConnectorFields", + "type": "CompoundType", + "tags": [], + "label": "actionConnectorFields", + "description": [], + "signature": [ + "React.LazyExoticComponent> | null" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.actionParamsFields", + "type": "Function", + "tags": [], + "label": "actionParamsFields", + "description": [], + "signature": [ + "React.ExoticComponent<(", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionParamsProps", + "text": "ActionParamsProps" + }, + " & React.RefAttributes, any, any>>) | (", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionParamsProps", + "text": "ActionParamsProps" + }, + " & { children?: React.ReactNode; })> & { readonly _result: React.ComponentType<", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionParamsProps", + "text": "ActionParamsProps" + }, + ">; }" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "returnComment": [], + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.actionParamsFields.$1", + "type": "Uncategorized", + "tags": [], + "label": "props", + "description": [], + "signature": [ + "P" + ], + "path": "node_modules/@types/react/index.d.ts", + "deprecated": false, + "trackAdoption": false + } + ] + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.defaultActionParams", + "type": "Object", + "tags": [], + "label": "defaultActionParams", + "description": [], + "signature": [ + "Partial | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ActionTypeModel.defaultRecoveredActionParams", + "type": "Object", + "tags": [], + "label": "defaultRecoveredActionParams", + "description": [], + "signature": [ + "Partial | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.minimumLicenseRequired", - "type": "CompoundType", + "id": "def-public.ActionTypeModel.customConnectorSelectItem", + "type": "Object", "tags": [], - "label": "minimumLicenseRequired", + "label": "customConnectorSelectItem", "description": [], "signature": [ - "\"basic\" | \"standard\" | \"gold\" | \"platinum\" | \"enterprise\" | \"trial\"" + "CustomConnectorSelectionItem | undefined" ], - "path": "x-pack/plugins/actions/common/types.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false }, { "parentPluginId": "triggersActionsUi", - "id": "def-public.ActionType.supportedFeatureIds", - "type": "Array", + "id": "def-public.ActionTypeModel.isExperimental", + "type": "CompoundType", "tags": [], - "label": "supportedFeatureIds", + "label": "isExperimental", "description": [], "signature": [ - "string[]" + "boolean | undefined" ], - "path": "x-pack/plugins/actions/common/types.ts", + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, "trackAdoption": false } @@ -2067,7 +3139,7 @@ "description": [], "signature": [ "BasicFields", - " & { tags?: string[] | undefined; kibana?: string[] | undefined; \"@timestamp\"?: string[] | undefined; \"event.action\"?: string[] | undefined; \"kibana.alert.rule.parameters\"?: string[] | undefined; \"kibana.alert.rule.rule_type_id\"?: string[] | undefined; \"kibana.alert.rule.consumer\"?: string[] | undefined; \"kibana.alert.rule.producer\"?: string[] | undefined; \"kibana.space_ids\"?: string[] | undefined; \"kibana.alert.uuid\"?: string[] | undefined; \"kibana.alert.instance.id\"?: string[] | undefined; \"kibana.alert.start\"?: string[] | undefined; \"kibana.alert.end\"?: string[] | undefined; \"kibana.alert.duration.us\"?: string[] | undefined; \"kibana.alert.severity\"?: string[] | undefined; \"kibana.alert.status\"?: string[] | undefined; \"kibana.version\"?: string[] | undefined; \"ecs.version\"?: string[] | undefined; \"kibana.alert.risk_score\"?: string[] | undefined; \"kibana.alert.workflow_status\"?: string[] | undefined; \"kibana.alert.workflow_user\"?: string[] | undefined; \"kibana.alert.workflow_reason\"?: string[] | undefined; \"kibana.alert.system_status\"?: string[] | undefined; \"kibana.alert.action_group\"?: string[] | undefined; \"kibana.alert.reason\"?: string[] | undefined; \"kibana.alert.rule.author\"?: string[] | undefined; \"kibana.alert.rule.category\"?: string[] | undefined; \"kibana.alert.rule.uuid\"?: string[] | undefined; \"kibana.alert.rule.created_at\"?: string[] | undefined; \"kibana.alert.rule.created_by\"?: string[] | undefined; \"kibana.alert.rule.description\"?: string[] | undefined; \"kibana.alert.rule.enabled\"?: string[] | undefined; \"kibana.alert.rule.execution.uuid\"?: string[] | undefined; \"kibana.alert.rule.from\"?: string[] | undefined; \"kibana.alert.rule.interval\"?: string[] | undefined; \"kibana.alert.rule.license\"?: string[] | undefined; \"kibana.alert.rule.name\"?: string[] | undefined; \"kibana.alert.rule.note\"?: string[] | undefined; \"kibana.alert.rule.references\"?: string[] | undefined; \"kibana.alert.rule.rule_id\"?: string[] | undefined; \"kibana.alert.rule.rule_name_override\"?: string[] | undefined; \"kibana.alert.rule.tags\"?: string[] | undefined; \"kibana.alert.rule.to\"?: string[] | undefined; \"kibana.alert.rule.type\"?: string[] | undefined; \"kibana.alert.rule.updated_at\"?: string[] | undefined; \"kibana.alert.rule.updated_by\"?: string[] | undefined; \"kibana.alert.rule.version\"?: string[] | undefined; \"event.kind\"?: string[] | undefined; \"event.module\"?: string[] | undefined; \"kibana.alert.evaluation.threshold\"?: string[] | undefined; \"kibana.alert.evaluation.value\"?: string[] | undefined; \"kibana.alert.building_block_type\"?: string[] | undefined; \"kibana.alert.rule.exceptions_list\"?: string[] | undefined; \"kibana.alert.rule.namespace\"?: string[] | undefined; \"kibana.alert\"?: string[] | undefined; \"kibana.alert.rule\"?: string[] | undefined; } & { [x: string]: unknown[]; }" + " & { tags?: string[] | undefined; kibana?: string[] | undefined; \"@timestamp\"?: string[] | undefined; \"kibana.alert.rule.rule_type_id\"?: string[] | undefined; \"kibana.alert.rule.consumer\"?: string[] | undefined; \"event.action\"?: string[] | undefined; \"kibana.alert.rule.execution.uuid\"?: string[] | undefined; \"kibana.alert.rule.parameters\"?: string[] | undefined; \"kibana.alert.rule.producer\"?: string[] | undefined; \"kibana.space_ids\"?: string[] | undefined; \"kibana.alert.uuid\"?: string[] | undefined; \"kibana.alert.instance.id\"?: string[] | undefined; \"kibana.alert.start\"?: string[] | undefined; \"kibana.alert.end\"?: string[] | undefined; \"kibana.alert.duration.us\"?: string[] | undefined; \"kibana.alert.severity\"?: string[] | undefined; \"kibana.alert.status\"?: string[] | undefined; \"kibana.version\"?: string[] | undefined; \"ecs.version\"?: string[] | undefined; \"kibana.alert.risk_score\"?: string[] | undefined; \"kibana.alert.workflow_status\"?: string[] | undefined; \"kibana.alert.workflow_user\"?: string[] | undefined; \"kibana.alert.workflow_reason\"?: string[] | undefined; \"kibana.alert.system_status\"?: string[] | undefined; \"kibana.alert.action_group\"?: string[] | undefined; \"kibana.alert.reason\"?: string[] | undefined; \"kibana.alert.rule.author\"?: string[] | undefined; \"kibana.alert.rule.category\"?: string[] | undefined; \"kibana.alert.rule.uuid\"?: string[] | undefined; \"kibana.alert.rule.created_at\"?: string[] | undefined; \"kibana.alert.rule.created_by\"?: string[] | undefined; \"kibana.alert.rule.description\"?: string[] | undefined; \"kibana.alert.rule.enabled\"?: string[] | undefined; \"kibana.alert.rule.from\"?: string[] | undefined; \"kibana.alert.rule.interval\"?: string[] | undefined; \"kibana.alert.rule.license\"?: string[] | undefined; \"kibana.alert.rule.name\"?: string[] | undefined; \"kibana.alert.rule.note\"?: string[] | undefined; \"kibana.alert.rule.references\"?: string[] | undefined; \"kibana.alert.rule.rule_id\"?: string[] | undefined; \"kibana.alert.rule.rule_name_override\"?: string[] | undefined; \"kibana.alert.rule.tags\"?: string[] | undefined; \"kibana.alert.rule.to\"?: string[] | undefined; \"kibana.alert.rule.type\"?: string[] | undefined; \"kibana.alert.rule.updated_at\"?: string[] | undefined; \"kibana.alert.rule.updated_by\"?: string[] | undefined; \"kibana.alert.rule.version\"?: string[] | undefined; \"event.kind\"?: string[] | undefined; \"event.module\"?: string[] | undefined; \"kibana.alert.evaluation.threshold\"?: string[] | undefined; \"kibana.alert.evaluation.value\"?: string[] | undefined; \"kibana.alert.building_block_type\"?: string[] | undefined; \"kibana.alert.rule.exceptions_list\"?: string[] | undefined; \"kibana.alert.rule.namespace\"?: string[] | undefined; \"kibana.alert\"?: string[] | undefined; \"kibana.alert.rule\"?: string[] | undefined; } & { [x: string]: unknown[]; }" ], "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", "deprecated": false, @@ -2513,20 +3585,6 @@ "deprecated": false, "trackAdoption": false }, - { - "parentPluginId": "triggersActionsUi", - "id": "def-public.AlertStatus.actionSubgroup", - "type": "string", - "tags": [], - "label": "actionSubgroup", - "description": [], - "signature": [ - "string | undefined" - ], - "path": "x-pack/plugins/alerting/common/alert_summary.ts", - "deprecated": false, - "trackAdoption": false - }, { "parentPluginId": "triggersActionsUi", "id": "def-public.AlertStatus.activeStartDate", @@ -2805,6 +3863,45 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ConfigFieldSchema", + "type": "Interface", + "tags": [], + "label": "ConfigFieldSchema", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ConfigFieldSchema", + "text": "ConfigFieldSchema" + }, + " extends ", + "CommonFieldSchema" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ConfigFieldSchema.isUrlField", + "type": "CompoundType", + "tags": [], + "label": "isUrlField", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.FieldBrowserOptions", @@ -3010,6 +4107,44 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.GenericValidationResult", + "type": "Interface", + "tags": [], + "label": "GenericValidationResult", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.GenericValidationResult", + "text": "GenericValidationResult" + }, + "" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.GenericValidationResult.errors", + "type": "Object", + "tags": [], + "label": "errors", + "description": [], + "signature": [ + "{ [P in Extract]: unknown; }" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.IErrorObject", @@ -3218,11 +4353,29 @@ "description": [], "signature": [ "{ get: (id: string) => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "; list: () => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "[]; register: (objectType: ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ") => void; has: (id: string) => boolean; }" ], "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", @@ -4147,6 +5300,45 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.SecretsFieldSchema", + "type": "Interface", + "tags": [], + "label": "SecretsFieldSchema", + "description": [], + "signature": [ + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.SecretsFieldSchema", + "text": "SecretsFieldSchema" + }, + " extends ", + "CommonFieldSchema" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.tsx", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.SecretsFieldSchema.isPasswordField", + "type": "CompoundType", + "tags": [], + "label": "isPasswordField", + "description": [], + "signature": [ + "boolean | undefined" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.tsx", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.TriggersAndActionsUiServices", @@ -4390,11 +5582,29 @@ "description": [], "signature": [ "{ get: (id: string) => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "; list: () => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "[]; register: (objectType: ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ") => void; has: (id: string) => boolean; }" ], "path": "x-pack/plugins/triggers_actions_ui/public/application/app.tsx", @@ -4603,6 +5813,18 @@ } ], "enums": [ + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.AlertProvidedActionVariables", + "type": "Enum", + "tags": [], + "label": "AlertProvidedActionVariables", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.COMPARATORS", @@ -4690,11 +5912,29 @@ "description": [], "signature": [ "{ get: (id: string) => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "; list: () => ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, "[]; register: (objectType: ", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ") => void; has: (id: string) => boolean; }" ], "path": "x-pack/plugins/triggers_actions_ui/public/types.ts", @@ -4717,6 +5957,63 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ALERT_HISTORY_PREFIX", + "type": "string", + "tags": [], + "label": "ALERT_HISTORY_PREFIX", + "description": [], + "signature": [ + "\"kibana-alert-history-\"" + ], + "path": "x-pack/plugins/actions/common/alert_history_schema.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.AlertHistoryDefaultIndexName", + "type": "string", + "tags": [], + "label": "AlertHistoryDefaultIndexName", + "description": [], + "path": "x-pack/plugins/actions/common/alert_history_schema.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.AlertHistoryDocumentTemplate", + "type": "CompoundType", + "tags": [], + "label": "AlertHistoryDocumentTemplate", + "description": [], + "signature": [ + "Readonly<{ event: { kind: string; }; kibana?: { alert: { actionGroupName?: string | undefined; actionGroup?: string | undefined; context?: { [x: string]: Record; } | undefined; id?: string | undefined; }; } | undefined; rule?: { type?: string | undefined; space?: string | undefined; params?: { [x: string]: Record; } | undefined; name?: string | undefined; id?: string | undefined; } | undefined; message?: unknown; tags?: string[] | undefined; '@timestamp': string; }> | null" + ], + "path": "x-pack/plugins/actions/common/alert_history_schema.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.AlertHistoryEsIndexConnectorId", + "type": "string", + "tags": [], + "label": "AlertHistoryEsIndexConnectorId", + "description": [], + "signature": [ + "\"preconfigured-alert-history-es-index\"" + ], + "path": "x-pack/plugins/actions/common/alert_history_schema.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.AlertsTableConfigurationRegistryContract", @@ -4784,6 +6081,51 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.connectorDeprecatedMessage", + "type": "string", + "tags": [], + "label": "connectorDeprecatedMessage", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/common/connectors_selection.tsx", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.ConnectorFormSchema", + "type": "Type", + "tags": [], + "label": "ConnectorFormSchema", + "description": [ + "\nThe following type is equivalent to:\n\ninterface ConnectorFormSchema {\n id?: string,\n name?: string,\n actionTypeId: string,\n isDeprecated: boolean,\n config: Config,\n secrets: Secrets,\n}" + ], + "signature": [ + "Pick<", + "UserConfiguredActionConnector", + ", \"config\" | \"secrets\" | \"actionTypeId\" | \"isDeprecated\"> & Partial, \"name\" | \"id\">>" + ], + "path": "x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "triggersActionsUi", + "id": "def-public.deprecatedMessage", + "type": "string", + "tags": [], + "label": "deprecatedMessage", + "description": [], + "path": "x-pack/plugins/triggers_actions_ui/public/common/connectors_selection.tsx", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "triggersActionsUi", "id": "def-public.GetRenderCellValue", @@ -5801,7 +7143,13 @@ "signature": [ "TypeRegistry", "<", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ">" ], "path": "x-pack/plugins/triggers_actions_ui/public/plugin.ts", @@ -5873,7 +7221,13 @@ "signature": [ "TypeRegistry", "<", - "ActionTypeModel", + { + "pluginId": "triggersActionsUi", + "scope": "public", + "docId": "kibTriggersActionsUiPluginApi", + "section": "def-public.ActionTypeModel", + "text": "ActionTypeModel" + }, ">" ], "path": "x-pack/plugins/triggers_actions_ui/public/plugin.ts", diff --git a/api_docs/triggers_actions_ui.mdx b/api_docs/triggers_actions_ui.mdx index 3f536cddf81ed..e40b4b0c4d440 100644 --- a/api_docs/triggers_actions_ui.mdx +++ b/api_docs/triggers_actions_ui.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/triggersActionsUi title: "triggersActionsUi" image: https://source.unsplash.com/400x175/?github description: API docs for the triggersActionsUi plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'triggersActionsUi'] --- import triggersActionsUiObj from './triggers_actions_ui.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Response Ops](https://github.com/orgs/elastic/teams/response-ops) for q | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 437 | 1 | 416 | 45 | +| 512 | 1 | 485 | 48 | ## Client diff --git a/api_docs/ui_actions.mdx b/api_docs/ui_actions.mdx index cb2edf03ef9bd..9a49946469889 100644 --- a/api_docs/ui_actions.mdx +++ b/api_docs/ui_actions.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/uiActions title: "uiActions" image: https://source.unsplash.com/400x175/?github description: API docs for the uiActions plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'uiActions'] --- import uiActionsObj from './ui_actions.devdocs.json'; diff --git a/api_docs/ui_actions_enhanced.mdx b/api_docs/ui_actions_enhanced.mdx index 198157440ac2b..e1fd951d5e2a2 100644 --- a/api_docs/ui_actions_enhanced.mdx +++ b/api_docs/ui_actions_enhanced.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/uiActionsEnhanced title: "uiActionsEnhanced" image: https://source.unsplash.com/400x175/?github description: API docs for the uiActionsEnhanced plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'uiActionsEnhanced'] --- import uiActionsEnhancedObj from './ui_actions_enhanced.devdocs.json'; diff --git a/api_docs/unified_field_list.mdx b/api_docs/unified_field_list.mdx index 7ab32ae9e80e9..254b1228a31fd 100644 --- a/api_docs/unified_field_list.mdx +++ b/api_docs/unified_field_list.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/unifiedFieldList title: "unifiedFieldList" image: https://source.unsplash.com/400x175/?github description: API docs for the unifiedFieldList plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'unifiedFieldList'] --- import unifiedFieldListObj from './unified_field_list.devdocs.json'; diff --git a/api_docs/unified_search.mdx b/api_docs/unified_search.mdx index 975909dbd1859..5015d2debdc41 100644 --- a/api_docs/unified_search.mdx +++ b/api_docs/unified_search.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/unifiedSearch title: "unifiedSearch" image: https://source.unsplash.com/400x175/?github description: API docs for the unifiedSearch plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'unifiedSearch'] --- import unifiedSearchObj from './unified_search.devdocs.json'; diff --git a/api_docs/unified_search_autocomplete.mdx b/api_docs/unified_search_autocomplete.mdx index bcd8790a9ef03..5a40018e6081e 100644 --- a/api_docs/unified_search_autocomplete.mdx +++ b/api_docs/unified_search_autocomplete.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/unifiedSearch-autocomplete title: "unifiedSearch.autocomplete" image: https://source.unsplash.com/400x175/?github description: API docs for the unifiedSearch.autocomplete plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'unifiedSearch.autocomplete'] --- import unifiedSearchAutocompleteObj from './unified_search_autocomplete.devdocs.json'; diff --git a/api_docs/url_forwarding.mdx b/api_docs/url_forwarding.mdx index 01be62ca3cbc1..f57d70892e70d 100644 --- a/api_docs/url_forwarding.mdx +++ b/api_docs/url_forwarding.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/urlForwarding title: "urlForwarding" image: https://source.unsplash.com/400x175/?github description: API docs for the urlForwarding plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'urlForwarding'] --- import urlForwardingObj from './url_forwarding.devdocs.json'; diff --git a/api_docs/usage_collection.mdx b/api_docs/usage_collection.mdx index 937cfe134fca4..f40f15636c943 100644 --- a/api_docs/usage_collection.mdx +++ b/api_docs/usage_collection.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/usageCollection title: "usageCollection" image: https://source.unsplash.com/400x175/?github description: API docs for the usageCollection plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'usageCollection'] --- import usageCollectionObj from './usage_collection.devdocs.json'; diff --git a/api_docs/ux.mdx b/api_docs/ux.mdx index 22f7f14e7b87e..d462e4d19616c 100644 --- a/api_docs/ux.mdx +++ b/api_docs/ux.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/ux title: "ux" image: https://source.unsplash.com/400x175/?github description: API docs for the ux plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'ux'] --- import uxObj from './ux.devdocs.json'; diff --git a/api_docs/vis_default_editor.mdx b/api_docs/vis_default_editor.mdx index a989426eb17c7..0b2993331260b 100644 --- a/api_docs/vis_default_editor.mdx +++ b/api_docs/vis_default_editor.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visDefaultEditor title: "visDefaultEditor" image: https://source.unsplash.com/400x175/?github description: API docs for the visDefaultEditor plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visDefaultEditor'] --- import visDefaultEditorObj from './vis_default_editor.devdocs.json'; diff --git a/api_docs/vis_type_gauge.mdx b/api_docs/vis_type_gauge.mdx index 1902e6787e057..cc20cda9db105 100644 --- a/api_docs/vis_type_gauge.mdx +++ b/api_docs/vis_type_gauge.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeGauge title: "visTypeGauge" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeGauge plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeGauge'] --- import visTypeGaugeObj from './vis_type_gauge.devdocs.json'; diff --git a/api_docs/vis_type_heatmap.mdx b/api_docs/vis_type_heatmap.mdx index 0c2173d8562a2..609c06b1a92cf 100644 --- a/api_docs/vis_type_heatmap.mdx +++ b/api_docs/vis_type_heatmap.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeHeatmap title: "visTypeHeatmap" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeHeatmap plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeHeatmap'] --- import visTypeHeatmapObj from './vis_type_heatmap.devdocs.json'; diff --git a/api_docs/vis_type_pie.mdx b/api_docs/vis_type_pie.mdx index 00f0bedd3b44c..3f8c15b314a0e 100644 --- a/api_docs/vis_type_pie.mdx +++ b/api_docs/vis_type_pie.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypePie title: "visTypePie" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypePie plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypePie'] --- import visTypePieObj from './vis_type_pie.devdocs.json'; diff --git a/api_docs/vis_type_table.mdx b/api_docs/vis_type_table.mdx index 2af9256f17d00..5aa2bd8b01f5a 100644 --- a/api_docs/vis_type_table.mdx +++ b/api_docs/vis_type_table.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeTable title: "visTypeTable" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeTable plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeTable'] --- import visTypeTableObj from './vis_type_table.devdocs.json'; diff --git a/api_docs/vis_type_timelion.mdx b/api_docs/vis_type_timelion.mdx index 6f9803ae692e7..2219fc96f2e31 100644 --- a/api_docs/vis_type_timelion.mdx +++ b/api_docs/vis_type_timelion.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeTimelion title: "visTypeTimelion" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeTimelion plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeTimelion'] --- import visTypeTimelionObj from './vis_type_timelion.devdocs.json'; diff --git a/api_docs/vis_type_timeseries.mdx b/api_docs/vis_type_timeseries.mdx index f1b4cd2f37124..2608ea12c24f9 100644 --- a/api_docs/vis_type_timeseries.mdx +++ b/api_docs/vis_type_timeseries.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeTimeseries title: "visTypeTimeseries" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeTimeseries plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeTimeseries'] --- import visTypeTimeseriesObj from './vis_type_timeseries.devdocs.json'; diff --git a/api_docs/vis_type_vega.mdx b/api_docs/vis_type_vega.mdx index 3ac63c8449032..e535d8ca970e3 100644 --- a/api_docs/vis_type_vega.mdx +++ b/api_docs/vis_type_vega.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeVega title: "visTypeVega" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeVega plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeVega'] --- import visTypeVegaObj from './vis_type_vega.devdocs.json'; diff --git a/api_docs/vis_type_vislib.mdx b/api_docs/vis_type_vislib.mdx index f1167efa39ac4..c6bd5fba0b068 100644 --- a/api_docs/vis_type_vislib.mdx +++ b/api_docs/vis_type_vislib.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeVislib title: "visTypeVislib" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeVislib plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeVislib'] --- import visTypeVislibObj from './vis_type_vislib.devdocs.json'; diff --git a/api_docs/vis_type_xy.devdocs.json b/api_docs/vis_type_xy.devdocs.json index 5468fa97bdb7a..e9d569dcbde48 100644 --- a/api_docs/vis_type_xy.devdocs.json +++ b/api_docs/vis_type_xy.devdocs.json @@ -825,12 +825,20 @@ "Omit<", { "pluginId": "visualizations", - "scope": "public", + "scope": "common", "docId": "kibVisualizationsPluginApi", - "section": "def-public.SchemaConfig", + "section": "def-common.SchemaConfig", "text": "SchemaConfig" }, - ", \"params\"> & { params: {} | ", + "<", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.SupportedAggregation", + "text": "SupportedAggregation" + }, + ">, \"params\"> & { params: {} | ", { "pluginId": "visualizations", "scope": "common", diff --git a/api_docs/vis_type_xy.mdx b/api_docs/vis_type_xy.mdx index a89e736598144..8caa2a67dab8d 100644 --- a/api_docs/vis_type_xy.mdx +++ b/api_docs/vis_type_xy.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visTypeXy title: "visTypeXy" image: https://source.unsplash.com/400x175/?github description: API docs for the visTypeXy plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visTypeXy'] --- import visTypeXyObj from './vis_type_xy.devdocs.json'; diff --git a/api_docs/visualizations.devdocs.json b/api_docs/visualizations.devdocs.json index 086c698e01e8e..95b3390b94cea 100644 --- a/api_docs/visualizations.devdocs.json +++ b/api_docs/visualizations.devdocs.json @@ -97,21 +97,21 @@ "label": "navigateToLens", "description": [], "signature": [ - "((params?: ", + "((vis?: ", { "pluginId": "visualizations", - "scope": "common", + "scope": "public", "docId": "kibVisualizationsPluginApi", - "section": "def-common.VisParams", - "text": "VisParams" + "section": "def-public.Vis", + "text": "Vis" }, - " | undefined, timeRange?: ", + " | undefined, timeFilter?: ", { "pluginId": "data", - "scope": "common", + "scope": "public", "docId": "kibDataQueryPluginApi", - "section": "def-common.TimeRange", - "text": "TimeRange" + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" }, " | undefined) => Promise<", { @@ -126,8 +126,8 @@ "pluginId": "visualizations", "scope": "common", "docId": "kibVisualizationsPluginApi", - "section": "def-common.XYConfiguration", - "text": "XYConfiguration" + "section": "def-common.Configuration", + "text": "Configuration" }, "> | null> | undefined) | undefined" ], @@ -135,6 +135,36 @@ "deprecated": false, "trackAdoption": false }, + { + "parentPluginId": "visualizations", + "id": "def-public.BaseVisType.getExpressionVariables", + "type": "Function", + "tags": [], + "label": "getExpressionVariables", + "description": [], + "signature": [ + "((vis?: ", + { + "pluginId": "visualizations", + "scope": "public", + "docId": "kibVisualizationsPluginApi", + "section": "def-public.Vis", + "text": "Vis" + }, + " | undefined, timeFilter?: ", + { + "pluginId": "data", + "scope": "public", + "docId": "kibDataQueryPluginApi", + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" + }, + " | undefined) => Promise>) | undefined" + ], + "path": "src/plugins/visualizations/public/vis_types/base_vis_type.ts", + "deprecated": false, + "trackAdoption": false + }, { "parentPluginId": "visualizations", "id": "def-public.BaseVisType.icon", @@ -1981,6 +2011,76 @@ } ], "functions": [ + { + "parentPluginId": "visualizations", + "id": "def-public.getDataViewByIndexPatternId", + "type": "Function", + "tags": [], + "label": "getDataViewByIndexPatternId", + "description": [], + "signature": [ + "(indexPatternId: string | undefined, dataViews: ", + { + "pluginId": "dataViews", + "scope": "public", + "docId": "kibDataViewsPluginApi", + "section": "def-public.DataViewsServicePublic", + "text": "DataViewsServicePublic" + }, + ") => Promise<", + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataView", + "text": "DataView" + }, + " | null>" + ], + "path": "src/plugins/visualizations/public/convert_to_lens/datasource.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-public.getDataViewByIndexPatternId.$1", + "type": "string", + "tags": [], + "label": "indexPatternId", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/public/convert_to_lens/datasource.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + }, + { + "parentPluginId": "visualizations", + "id": "def-public.getDataViewByIndexPatternId.$2", + "type": "Object", + "tags": [], + "label": "dataViews", + "description": [], + "signature": [ + { + "pluginId": "dataViews", + "scope": "public", + "docId": "kibDataViewsPluginApi", + "section": "def-public.DataViewsServicePublic", + "text": "DataViewsServicePublic" + } + ], + "path": "src/plugins/visualizations/public/convert_to_lens/datasource.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-public.getFullPath", @@ -2030,7 +2130,7 @@ "section": "def-public.Vis", "text": "Vis" }, - ", { timeRange, timefilter }: ", + ", params: ", { "pluginId": "visualizations", "scope": "public", @@ -2072,7 +2172,7 @@ "id": "def-public.getVisSchemas.$2", "type": "Object", "tags": [], - "label": "{ timeRange, timefilter }", + "label": "params", "description": [], "signature": [ { @@ -2942,7 +3042,7 @@ "label": "sharingSavedObjectProps", "description": [], "signature": [ - "{ outcome?: \"exactMatch\" | \"aliasMatch\" | \"conflict\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" + "{ outcome?: \"conflict\" | \"exactMatch\" | \"aliasMatch\" | undefined; aliasTargetId?: string | undefined; aliasPurpose?: \"savedObjectConversion\" | \"savedObjectImport\" | undefined; errorJSON?: string | undefined; } | undefined" ], "path": "src/plugins/visualizations/public/types.ts", "deprecated": false, @@ -3219,83 +3319,6 @@ ], "initialIsOpen": false }, - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig", - "type": "Interface", - "tags": [], - "label": "SchemaConfig", - "description": [], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false, - "children": [ - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig.accessor", - "type": "number", - "tags": [], - "label": "accessor", - "description": [], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig.label", - "type": "string", - "tags": [], - "label": "label", - "description": [], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig.format", - "type": "Object", - "tags": [], - "label": "format", - "description": [], - "signature": [ - "{ id?: string | undefined; params?: ", - "SerializableRecord", - " | undefined; }" - ], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig.params", - "type": "Object", - "tags": [], - "label": "params", - "description": [], - "signature": [ - "SchemaConfigParams" - ], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false - }, - { - "parentPluginId": "visualizations", - "id": "def-public.SchemaConfig.aggType", - "type": "string", - "tags": [], - "label": "aggType", - "description": [], - "path": "src/plugins/visualizations/public/vis_schemas.ts", - "deprecated": false, - "trackAdoption": false - } - ], - "initialIsOpen": false - }, { "parentPluginId": "visualizations", "id": "def-public.SerializedVis", @@ -4538,21 +4561,21 @@ "\nIf given, it will navigateToLens with the given viz params.\nEvery visualization that wants to be edited also in Lens should have this function.\nIt receives the current visualization params as a parameter and should return the correct config\nin order to be displayed in the Lens editor." ], "signature": [ - "((params?: ", + "((vis?: ", { "pluginId": "visualizations", - "scope": "common", + "scope": "public", "docId": "kibVisualizationsPluginApi", - "section": "def-common.VisParams", - "text": "VisParams" + "section": "def-public.Vis", + "text": "Vis" }, - " | undefined, timeRange?: ", + " | undefined, timeFilter?: ", { "pluginId": "data", - "scope": "common", + "scope": "public", "docId": "kibDataQueryPluginApi", - "section": "def-common.TimeRange", - "text": "TimeRange" + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" }, " | undefined) => Promise<", { @@ -4567,8 +4590,8 @@ "pluginId": "visualizations", "scope": "common", "docId": "kibVisualizationsPluginApi", - "section": "def-common.XYConfiguration", - "text": "XYConfiguration" + "section": "def-common.Configuration", + "text": "Configuration" }, "> | null> | undefined) | undefined" ], @@ -4581,17 +4604,17 @@ "id": "def-public.VisTypeDefinition.navigateToLens.$1", "type": "Object", "tags": [], - "label": "params", + "label": "vis", "description": [], "signature": [ { "pluginId": "visualizations", - "scope": "common", + "scope": "public", "docId": "kibVisualizationsPluginApi", - "section": "def-common.VisParams", - "text": "VisParams" + "section": "def-public.Vis", + "text": "Vis" }, - " | undefined" + " | undefined" ], "path": "src/plugins/visualizations/public/vis_types/types.ts", "deprecated": false, @@ -4603,15 +4626,94 @@ "id": "def-public.VisTypeDefinition.navigateToLens.$2", "type": "Object", "tags": [], - "label": "timeRange", + "label": "timeFilter", "description": [], "signature": [ { "pluginId": "data", - "scope": "common", + "scope": "public", + "docId": "kibDataQueryPluginApi", + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" + }, + " | undefined" + ], + "path": "src/plugins/visualizations/public/vis_types/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + } + ], + "returnComment": [] + }, + { + "parentPluginId": "visualizations", + "id": "def-public.VisTypeDefinition.getExpressionVariables", + "type": "Function", + "tags": [], + "label": "getExpressionVariables", + "description": [ + "\nIf given, it will provide variables for expression params.\nEvery visualization that wants to add variables for expression params should have this method." + ], + "signature": [ + "((vis?: ", + { + "pluginId": "visualizations", + "scope": "public", + "docId": "kibVisualizationsPluginApi", + "section": "def-public.Vis", + "text": "Vis" + }, + " | undefined, timeFilter?: ", + { + "pluginId": "data", + "scope": "public", + "docId": "kibDataQueryPluginApi", + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" + }, + " | undefined) => Promise>) | undefined" + ], + "path": "src/plugins/visualizations/public/vis_types/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-public.VisTypeDefinition.getExpressionVariables.$1", + "type": "Object", + "tags": [], + "label": "vis", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "public", + "docId": "kibVisualizationsPluginApi", + "section": "def-public.Vis", + "text": "Vis" + }, + " | undefined" + ], + "path": "src/plugins/visualizations/public/vis_types/types.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + }, + { + "parentPluginId": "visualizations", + "id": "def-public.VisTypeDefinition.getExpressionVariables.$2", + "type": "Object", + "tags": [], + "label": "timeFilter", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "public", "docId": "kibDataQueryPluginApi", - "section": "def-common.TimeRange", - "text": "TimeRange" + "section": "def-public.TimefilterContract", + "text": "TimefilterContract" }, " | undefined" ], @@ -5639,13 +5741,13 @@ "misc": [ { "parentPluginId": "visualizations", - "id": "def-public.ACTION_CONVERT_TO_LENS", + "id": "def-public.ACTION_CONVERT_AGG_BASED_TO_LENS", "type": "string", "tags": [], - "label": "ACTION_CONVERT_TO_LENS", + "label": "ACTION_CONVERT_AGG_BASED_TO_LENS", "description": [], "signature": [ - "\"ACTION_CONVERT_TO_LENS\"" + "\"ACTION_CONVERT_AGG_BASED_TO_LENS\"" ], "path": "src/plugins/visualizations/public/triggers/index.ts", "deprecated": false, @@ -5654,17 +5756,47 @@ }, { "parentPluginId": "visualizations", - "id": "def-public.DEFAULT_LEGEND_SIZE", + "id": "def-public.ACTION_CONVERT_TO_LENS", "type": "string", "tags": [], - "label": "DEFAULT_LEGEND_SIZE", + "label": "ACTION_CONVERT_TO_LENS", "description": [], "signature": [ - { - "pluginId": "visualizations", - "scope": "common", - "docId": "kibVisualizationsPluginApi", - "section": "def-common.LegendSize", + "\"ACTION_CONVERT_TO_LENS\"" + ], + "path": "src/plugins/visualizations/public/triggers/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "visualizations", + "id": "def-public.AGG_BASED_VISUALIZATION_TRIGGER", + "type": "string", + "tags": [], + "label": "AGG_BASED_VISUALIZATION_TRIGGER", + "description": [], + "signature": [ + "\"AGG_BASED_VISUALIZATION_TRIGGER\"" + ], + "path": "src/plugins/visualizations/public/triggers/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, + { + "parentPluginId": "visualizations", + "id": "def-public.DEFAULT_LEGEND_SIZE", + "type": "string", + "tags": [], + "label": "DEFAULT_LEGEND_SIZE", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.LegendSize", "text": "LegendSize" }, ".MEDIUM" @@ -5804,6 +5936,29 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-public.SchemaConfig", + "type": "Type", + "tags": [], + "label": "SchemaConfig", + "description": [], + "signature": [ + "{ [Agg in Aggs]: ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.GenericSchemaConfig", + "text": "GenericSchemaConfig" + }, + "; }[Aggs]" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-public.VisToExpressionAst", @@ -6383,6 +6538,23 @@ } ], "objects": [ + { + "parentPluginId": "visualizations", + "id": "def-public.convertToLensModule", + "type": "Object", + "tags": [], + "label": "convertToLensModule", + "description": [], + "signature": [ + "Promise" + ], + "path": "src/plugins/visualizations/public/index.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-public.LegendSizeToPixels", @@ -6679,6 +6851,69 @@ "common": { "classes": [], "functions": [ + { + "parentPluginId": "visualizations", + "id": "def-common.convertToSchemaConfig", + "type": "Function", + "tags": [], + "label": "convertToSchemaConfig", + "description": [], + "signature": [ + "(agg: ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + }, + ") => ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.SchemaConfig", + "text": "SchemaConfig" + }, + "<", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.METRIC_TYPES", + "text": "METRIC_TYPES" + }, + ">" + ], + "path": "src/plugins/visualizations/common/vis_schemas.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.convertToSchemaConfig.$1", + "type": "Object", + "tags": [], + "label": "agg", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggConfig", + "text": "AggConfig" + } + ], + "path": "src/plugins/visualizations/common/vis_schemas.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.findAccessorOrFail", @@ -7080,6 +7315,54 @@ "returnComment": [], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.getIndexPatternIds", + "type": "Function", + "tags": [], + "label": "getIndexPatternIds", + "description": [], + "signature": [ + "(layers: ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.Layer", + "text": "Layer" + }, + "[]) => string[]" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/utils.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.getIndexPatternIds.$1", + "type": "Array", + "tags": [], + "label": "layers", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.Layer", + "text": "Layer" + }, + "[]" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/utils.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.isAnnotationsLayer", @@ -7136,6 +7419,78 @@ "returnComment": [], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.isFieldValid", + "type": "Function", + "tags": [], + "label": "isFieldValid", + "description": [], + "signature": [ + "(field: ", + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataViewField", + "text": "DataViewField" + }, + " | undefined, aggregation: ", + "SupportedMetric", + ") => field is ", + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataViewField", + "text": "DataViewField" + } + ], + "path": "src/plugins/visualizations/common/convert_to_lens/utils.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.isFieldValid.$1", + "type": "Object", + "tags": [], + "label": "field", + "description": [], + "signature": [ + { + "pluginId": "dataViews", + "scope": "common", + "docId": "kibDataViewsPluginApi", + "section": "def-common.DataViewField", + "text": "DataViewField" + }, + " | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/utils.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.isFieldValid.$2", + "type": "CompoundType", + "tags": [], + "label": "aggregation", + "description": [], + "signature": [ + "SupportedMetric" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/utils.ts", + "deprecated": false, + "trackAdoption": false, + "isRequired": true + } + ], + "returnComment": [], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.isVisDimension", @@ -7886,63 +8241,130 @@ }, { "parentPluginId": "visualizations", - "id": "def-common.ColumnWithReferences", + "id": "def-common.ColumnState", "type": "Interface", "tags": [], - "label": "ColumnWithReferences", + "label": "ColumnState", "description": [], - "signature": [ - { - "pluginId": "visualizations", - "scope": "common", - "docId": "kibVisualizationsPluginApi", - "section": "def-common.ColumnWithReferences", - "text": "ColumnWithReferences" - }, - " extends ", - { - "pluginId": "visualizations", - "scope": "common", - "docId": "kibVisualizationsPluginApi", - "section": "def-common.BaseColumn", - "text": "BaseColumn" - }, - "" - ], - "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", "deprecated": false, "trackAdoption": false, "children": [ { "parentPluginId": "visualizations", - "id": "def-common.ColumnWithReferences.references", - "type": "Array", + "id": "def-common.ColumnState.columnId", + "type": "string", "tags": [], - "label": "references", + "label": "columnId", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.ColumnState.summaryRow", + "type": "CompoundType", + "tags": [], + "label": "summaryRow", "description": [], "signature": [ - "string[]" + "\"min\" | \"none\" | \"max\" | \"count\" | \"sum\" | \"avg\" | undefined" ], - "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", "deprecated": false, "trackAdoption": false - } - ], - "initialIsOpen": false - }, - { - "parentPluginId": "visualizations", - "id": "def-common.ColumnWithSourceField", - "type": "Interface", - "tags": [], - "label": "ColumnWithSourceField", - "description": [], - "signature": [ + }, { - "pluginId": "visualizations", - "scope": "common", - "docId": "kibVisualizationsPluginApi", - "section": "def-common.ColumnWithSourceField", + "parentPluginId": "visualizations", + "id": "def-common.ColumnState.alignment", + "type": "CompoundType", + "tags": [], + "label": "alignment", + "description": [], + "signature": [ + "\"left\" | \"right\" | \"center\" | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.ColumnState.collapseFn", + "type": "string", + "tags": [], + "label": "collapseFn", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.ColumnWithReferences", + "type": "Interface", + "tags": [], + "label": "ColumnWithReferences", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.ColumnWithReferences", + "text": "ColumnWithReferences" + }, + " extends ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.BaseColumn", + "text": "BaseColumn" + }, + "" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.ColumnWithReferences.references", + "type": "Array", + "tags": [], + "label": "references", + "description": [], + "signature": [ + "string[]" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.ColumnWithSourceField", + "type": "Interface", + "tags": [], + "label": "ColumnWithSourceField", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.ColumnWithSourceField", "text": "ColumnWithSourceField" }, " extends ", @@ -8227,6 +8649,9 @@ "tags": [], "label": "label", "description": [], + "signature": [ + "string | undefined" + ], "path": "src/plugins/visualizations/common/convert_to_lens/types/common.ts", "deprecated": false, "trackAdoption": false @@ -8402,6 +8827,131 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig", + "type": "Interface", + "tags": [], + "label": "GenericSchemaConfig", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.GenericSchemaConfig", + "text": "GenericSchemaConfig" + }, + "" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.accessor", + "type": "number", + "tags": [], + "label": "accessor", + "description": [], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.label", + "type": "string", + "tags": [], + "label": "label", + "description": [], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.format", + "type": "Object", + "tags": [], + "label": "format", + "description": [], + "signature": [ + "{ id?: string | undefined; params?: ", + "SerializableRecord", + " | undefined; }" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.params", + "type": "Object", + "tags": [], + "label": "params", + "description": [], + "signature": [ + "SchemaConfigParams" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.aggType", + "type": "Uncategorized", + "tags": [], + "label": "aggType", + "description": [], + "signature": [ + "Agg" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.aggId", + "type": "string", + "tags": [], + "label": "aggId", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericSchemaConfig.aggParams", + "type": "Uncategorized", + "tags": [], + "label": "aggParams", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.AggParamsMapping", + "text": "AggParamsMapping" + }, + "[Agg] | undefined" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.LabelsOrientationConfig", @@ -8734,6 +9284,203 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration", + "type": "Interface", + "tags": [], + "label": "MetricVisConfiguration", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.layerId", + "type": "string", + "tags": [], + "label": "layerId", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.layerType", + "type": "string", + "tags": [], + "label": "layerType", + "description": [], + "signature": [ + "\"data\"" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.metricAccessor", + "type": "string", + "tags": [], + "label": "metricAccessor", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.secondaryMetricAccessor", + "type": "string", + "tags": [], + "label": "secondaryMetricAccessor", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.maxAccessor", + "type": "string", + "tags": [], + "label": "maxAccessor", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.breakdownByAccessor", + "type": "string", + "tags": [], + "label": "breakdownByAccessor", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.collapseFn", + "type": "string", + "tags": [], + "label": "collapseFn", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.subtitle", + "type": "string", + "tags": [], + "label": "subtitle", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.secondaryPrefix", + "type": "string", + "tags": [], + "label": "secondaryPrefix", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.progressDirection", + "type": "CompoundType", + "tags": [], + "label": "progressDirection", + "description": [], + "signature": [ + "LayoutDirection", + " | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.color", + "type": "string", + "tags": [], + "label": "color", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.palette", + "type": "Object", + "tags": [], + "label": "palette", + "description": [], + "signature": [ + "PaletteOutput", + "<", + "CustomPaletteParams", + "> | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.MetricVisConfiguration.maxCols", + "type": "number", + "tags": [], + "label": "maxCols", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.MovingAverageParams", @@ -8825,6 +9572,20 @@ "path": "src/plugins/visualizations/common/convert_to_lens/types/context.ts", "deprecated": false, "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.NavigateToLensContext.indexPatternIds", + "type": "Array", + "tags": [], + "label": "indexPatternIds", + "description": [], + "signature": [ + "string[]" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/context.ts", + "deprecated": false, + "trackAdoption": false } ], "initialIsOpen": false @@ -8868,6 +9629,42 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.PagingState", + "type": "Interface", + "tags": [], + "label": "PagingState", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.PagingState.size", + "type": "number", + "tags": [], + "label": "size", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.PagingState.enabled", + "type": "boolean", + "tags": [], + "label": "enabled", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.PercentileParams", @@ -9339,15 +10136,57 @@ }, { "parentPluginId": "visualizations", - "id": "def-common.SerializedVisData.savedSearchId", - "type": "string", + "id": "def-common.SerializedVisData.savedSearchId", + "type": "string", + "tags": [], + "label": "savedSearchId", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.SortingState", + "type": "Interface", + "tags": [], + "label": "SortingState", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.SortingState.columnId", + "type": "string", + "tags": [], + "label": "columnId", + "description": [], + "signature": [ + "string | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.SortingState.direction", + "type": "CompoundType", "tags": [], - "label": "savedSearchId", + "label": "direction", "description": [], "signature": [ - "string | undefined" + "\"none\" | \"asc\" | \"desc\"" ], - "path": "src/plugins/visualizations/common/types.ts", + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", "deprecated": false, "trackAdoption": false } @@ -9399,6 +10238,164 @@ ], "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration", + "type": "Interface", + "tags": [], + "label": "TableVisConfiguration", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false, + "children": [ + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.columns", + "type": "Array", + "tags": [], + "label": "columns", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.ColumnState", + "text": "ColumnState" + }, + "[]" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.layerId", + "type": "string", + "tags": [], + "label": "layerId", + "description": [], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.layerType", + "type": "string", + "tags": [], + "label": "layerType", + "description": [], + "signature": [ + "\"data\"" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.sorting", + "type": "Object", + "tags": [], + "label": "sorting", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.SortingState", + "text": "SortingState" + }, + " | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.rowHeight", + "type": "CompoundType", + "tags": [], + "label": "rowHeight", + "description": [], + "signature": [ + "\"auto\" | \"custom\" | \"single\" | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.headerRowHeight", + "type": "CompoundType", + "tags": [], + "label": "headerRowHeight", + "description": [], + "signature": [ + "\"auto\" | \"custom\" | \"single\" | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.rowHeightLines", + "type": "number", + "tags": [], + "label": "rowHeightLines", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.headerRowHeightLines", + "type": "number", + "tags": [], + "label": "headerRowHeightLines", + "description": [], + "signature": [ + "number | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + }, + { + "parentPluginId": "visualizations", + "id": "def-common.TableVisConfiguration.paging", + "type": "Object", + "tags": [], + "label": "paging", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.PagingState", + "text": "PagingState" + }, + " | undefined" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", + "deprecated": false, + "trackAdoption": false + } + ], + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.TermsParams", @@ -10689,6 +11686,39 @@ } ], "misc": [ + { + "parentPluginId": "visualizations", + "id": "def-common.AggBasedColumn", + "type": "Type", + "tags": [], + "label": "AggBasedColumn", + "description": [], + "signature": [ + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.GenericColumnWithMeta", + "text": "GenericColumnWithMeta" + }, + "<", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.Column", + "text": "Column" + }, + ", ", + "Meta", + "> | ", + "BucketColumn" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/lib/convert/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.AnyColumnWithReferences", @@ -11022,7 +12052,14 @@ "label": "ColumnWithMeta", "description": [], "signature": [ - "Col & (Meta extends undefined ? undefined : { meta: Meta; })" + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.Column", + "text": "Column" + }, + " & { meta: unknown; }" ], "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", "deprecated": false, @@ -11043,6 +12080,22 @@ "docId": "kibVisualizationsPluginApi", "section": "def-common.XYConfiguration", "text": "XYConfiguration" + }, + " | ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.TableVisConfiguration", + "text": "TableVisConfiguration" + }, + " | ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.MetricVisConfiguration", + "text": "MetricVisConfiguration" } ], "path": "src/plugins/visualizations/common/convert_to_lens/types/configurations.ts", @@ -11434,6 +12487,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.GenericColumnWithMeta", + "type": "Type", + "tags": [], + "label": "GenericColumnWithMeta", + "description": [], + "signature": [ + "Col & (Meta extends undefined ? undefined : { meta: Meta; })" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/columns.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.LastValueColumn", @@ -11782,6 +12850,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.RangeMode", + "type": "Type", + "tags": [], + "label": "RangeMode", + "description": [], + "signature": [ + "\"range\" | \"histogram\"" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/types/params.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.SavedVisState", @@ -11799,6 +12882,29 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.SchemaConfig", + "type": "Type", + "tags": [], + "label": "SchemaConfig", + "description": [], + "signature": [ + "{ [Agg in Aggs]: ", + { + "pluginId": "visualizations", + "scope": "common", + "docId": "kibVisualizationsPluginApi", + "section": "def-common.GenericSchemaConfig", + "text": "GenericSchemaConfig" + }, + "; }[Aggs]" + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.SeriesType", @@ -11961,6 +13067,35 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.SupportedAggregation", + "type": "Type", + "tags": [], + "label": "SupportedAggregation", + "description": [], + "signature": [ + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.METRIC_TYPES", + "text": "METRIC_TYPES" + }, + " | ", + { + "pluginId": "data", + "scope": "common", + "docId": "kibDataSearchPluginApi", + "section": "def-common.BUCKET_TYPES", + "text": "BUCKET_TYPES" + } + ], + "path": "src/plugins/visualizations/common/types.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.TermsColumn", @@ -12150,6 +13285,21 @@ "trackAdoption": false, "initialIsOpen": false }, + { + "parentPluginId": "visualizations", + "id": "def-common.RANGE_MODES", + "type": "Object", + "tags": [], + "label": "RANGE_MODES", + "description": [], + "signature": [ + "{ readonly Range: \"range\"; readonly Histogram: \"histogram\"; }" + ], + "path": "src/plugins/visualizations/common/convert_to_lens/constants.ts", + "deprecated": false, + "trackAdoption": false, + "initialIsOpen": false + }, { "parentPluginId": "visualizations", "id": "def-common.SeriesTypes", diff --git a/api_docs/visualizations.mdx b/api_docs/visualizations.mdx index 524429916331f..6e29fc3d03f29 100644 --- a/api_docs/visualizations.mdx +++ b/api_docs/visualizations.mdx @@ -8,7 +8,7 @@ slug: /kibana-dev-docs/api/visualizations title: "visualizations" image: https://source.unsplash.com/400x175/?github description: API docs for the visualizations plugin -date: 2022-09-24 +date: 2022-09-29 tags: ['contributor', 'dev', 'apidocs', 'kibana', 'visualizations'] --- import visualizationsObj from './visualizations.devdocs.json'; @@ -21,7 +21,7 @@ Contact [Vis Editors](https://github.com/orgs/elastic/teams/kibana-vis-editors) | Public API count | Any count | Items lacking comments | Missing exports | |-------------------|-----------|------------------------|-----------------| -| 631 | 12 | 602 | 14 | +| 693 | 12 | 663 | 18 | ## Client diff --git a/docs/api-generated/machine-learning/ml-apis-passthru.adoc b/docs/api-generated/machine-learning/ml-apis-passthru.adoc new file mode 100644 index 0000000000000..a1275f2212ad6 --- /dev/null +++ b/docs/api-generated/machine-learning/ml-apis-passthru.adoc @@ -0,0 +1,192 @@ +//// +This content is generated from the open API specification. +Any modifications made to this file will be overwritten. +//// + +++++ +
+

Access

+
    +
  1. APIKey KeyParamName:ApiKey KeyInQuery:false KeyInHeader:true
  2. +
  3. HTTP Basic Authentication
  4. +
+ +

Methods

+ [ Jump to Models ] + +

Table of Contents

+
+

Ml

+ + +

Ml

+
+
+ Up +
get /s/{spaceId}/api/ml/saved_objects/sync
+
Synchronizes Kibana saved objects for machine learning jobs and trained models. (mlSync)
+
You must have all privileges for the Machine Learning feature in the Analytics section of the Kibana feature privileges. This API runs automatically when you start Kibana and periodically thereafter.
+ +

Path parameters

+
+
spaceId (required)
+ +
Path Parameter — An identifier for the space. If /s/ and the identifier are omitted from the path, the default space is used. default: null
+
+ + + + +

Query parameters

+
+
simulate (optional)
+ +
Query Parameter — When true, simulates the synchronization by returning only the list actions that would be performed. default: null
+
+ + +

Return type

+ + + + +

Example data

+
Content-Type: application/json
+
{
+  "datafeedsAdded" : {
+    "key" : {
+      "success" : true
+    }
+  },
+  "savedObjectsCreated" : {
+    "anomaly-detector" : {
+      "key" : {
+        "success" : true
+      }
+    },
+    "data-frame-analytics" : {
+      "key" : {
+        "success" : true
+      }
+    },
+    "trained-model" : {
+      "key" : {
+        "success" : true
+      }
+    }
+  },
+  "savedObjectsDeleted" : {
+    "anomaly-detector" : {
+      "key" : {
+        "success" : true
+      }
+    },
+    "data-frame-analytics" : {
+      "key" : {
+        "success" : true
+      }
+    },
+    "trained-model" : {
+      "key" : {
+        "success" : true
+      }
+    }
+  },
+  "datafeedsRemoved" : {
+    "key" : {
+      "success" : true
+    }
+  }
+}
+ +

Produces

+ This API call produces the following media types according to the Accept request header; + the media type will be conveyed by the Content-Type response header. +
    +
  • application/json
  • +
+ +

Responses

+

200

+ Indicates a successful call + mlSyncResponse +
+
+ +

Models

+ [ Jump to Methods ] + +

Table of Contents

+
    +
  1. mlSyncResponse - Sync API response
  2. +
  3. mlSyncResponseAnomalyDetectors - Sync API response for anomaly detection jobs
  4. +
  5. mlSyncResponseDataFrameAnalytics - Sync API response for data frame analytics jobs
  6. +
  7. mlSyncResponseDatafeeds - Sync API response for datafeeds
  8. +
  9. mlSyncResponseSavedObjectsCreated - Sync API response for created saved objects
  10. +
  11. mlSyncResponseSavedObjectsDeleted - Sync API response for deleted saved objects
  12. +
  13. mlSyncResponseTrainedModels - Sync API response for trained models
  14. +
+ +
+

mlSyncResponse - Sync API response Up

+
+
+
datafeedsAdded (optional)
map[String, mlSyncResponseDatafeeds] If a saved object for an anomaly detection job is missing a datafeed identifier, it is added when you run the sync machine learning saved objects API.
+
datafeedsRemoved (optional)
map[String, mlSyncResponseDatafeeds] If a saved object for an anomaly detection job references a datafeed that no longer exists, it is deleted when you run the sync machine learning saved objects API.
+
savedObjectsCreated (optional)
+
savedObjectsDeleted (optional)
+
+
+
+

mlSyncResponseAnomalyDetectors - Sync API response for anomaly detection jobs Up

+
The sync machine learning saved objects API response contains this object when there are anomaly detection jobs affected by the synchronization. There is an object for each relevant job, which contains the synchronization status.
+
+
success (optional)
Boolean The success or failure of the synchronization.
+
+
+
+

mlSyncResponseDataFrameAnalytics - Sync API response for data frame analytics jobs Up

+
The sync machine learning saved objects API response contains this object when there are data frame analytics jobs affected by the synchronization. There is an object for each relevant job, which contains the synchronization status.
+
+
success (optional)
Boolean The success or failure of the synchronization.
+
+
+
+

mlSyncResponseDatafeeds - Sync API response for datafeeds Up

+
The sync machine learning saved objects API response contains this object when there are datafeeds affected by the synchronization. There is an object for each relevant datafeed, which contains the synchronization status.
+
+
success (optional)
Boolean The success or failure of the synchronization.
+
+
+
+

mlSyncResponseSavedObjectsCreated - Sync API response for created saved objects Up

+
If saved objects are missing for machine learning jobs or trained models, they are created when you run the sync machine learning saved objects API.
+
+
anomalyMinusdetector (optional)
map[String, mlSyncResponseAnomalyDetectors] If saved objects are missing for anomaly detection jobs, they are created.
+
dataMinusframeMinusanalytics (optional)
map[String, mlSyncResponseDataFrameAnalytics] If saved objects are missing for data frame analytics jobs, they are created.
+
trainedMinusmodel (optional)
map[String, mlSyncResponseTrainedModels] If saved objects are missing for trained models, they are created.
+
+
+
+

mlSyncResponseSavedObjectsDeleted - Sync API response for deleted saved objects Up

+
If saved objects exist for machine learning jobs or trained models that no longer exist, they are deleted when you run the sync machine learning saved objects API.
+
+
anomalyMinusdetector (optional)
map[String, mlSyncResponseAnomalyDetectors] If there are saved objects exist for nonexistent anomaly detection jobs, they are deleted.
+
dataMinusframeMinusanalytics (optional)
map[String, mlSyncResponseDataFrameAnalytics] If there are saved objects exist for nonexistent data frame analytics jobs, they are deleted.
+
trainedMinusmodel (optional)
map[String, mlSyncResponseTrainedModels] If there are saved objects exist for nonexistent trained models, they are deleted.
+
+
+
+

mlSyncResponseTrainedModels - Sync API response for trained models Up

+
The sync machine learning saved objects API response contains this object when there are trained models affected by the synchronization. There is an object for each relevant trained model, which contains the synchronization status.
+
+
success (optional)
Boolean The success or failure of the synchronization.
+
+
+
+++++ diff --git a/docs/api-generated/machine-learning/ml-apis.asciidoc b/docs/api-generated/machine-learning/ml-apis.asciidoc new file mode 100644 index 0000000000000..3482109d4ab3e --- /dev/null +++ b/docs/api-generated/machine-learning/ml-apis.asciidoc @@ -0,0 +1,10 @@ +[[machine-learning-api]] +== Machine learning APIs + +preview::[] + +//// +This file includes content that has been generated from https://github.com/elastic/kibana/tree/main/x-pack/plugins/ml/common/openapi. Any modifications required must be done in that open API specification. +//// + +include::ml-apis-passthru.adoc[] \ No newline at end of file diff --git a/docs/api-generated/template/index.mustache b/docs/api-generated/template/index.mustache new file mode 100644 index 0000000000000..8c1162f909508 --- /dev/null +++ b/docs/api-generated/template/index.mustache @@ -0,0 +1,170 @@ +//// +This content is generated from the open API specification. +Any modifications made to this file will be overwritten. +//// + +++++ +
+

Access

+ {{#hasAuthMethods}} +
    + {{#authMethods}} +
  1. {{#isBasic}}HTTP Basic Authentication{{/isBasic}}{{#isOAuth}}OAuth AuthorizationUrl:{{authorizationUrl}}TokenUrl:{{tokenUrl}}{{/isOAuth}}{{#isApiKey}}APIKey KeyParamName:{{keyParamName}} KeyInQuery:{{isKeyInQuery}} KeyInHeader:{{isKeyInHeader}}{{/isApiKey}}
  2. + {{/authMethods}} +
+ {{/hasAuthMethods}} + +

Methods

+ [ Jump to Models ] + + {{! for the tables of content, I cheat and don't use CSS styles.... }} +

Table of Contents

+
{{access}}
+ {{#apiInfo}} + {{#apis}} + {{#operations}} +

{{baseName}}

+ + {{/operations}} + {{/apis}} + {{/apiInfo}} + + {{#apiInfo}} + {{#apis}} + {{#operations}} +

{{baseName}}

+ {{#operation}} +
+
+ Up +
{{httpMethod}} {{path}}
+
{{summary}} ({{nickname}})
+ {{! notes is operation.description. So why rename it and make it super confusing???? }} +
{{notes}}
+ + {{#hasPathParams}} +

Path parameters

+
+ {{#pathParams}}{{>pathParam}}{{/pathParams}} +
+ {{/hasPathParams}} + + {{#hasConsumes}} +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + {{#consumes}} +
  • {{{mediaType}}}
  • + {{/consumes}} +
+ {{/hasConsumes}} + + {{#hasBodyParam}} +

Request body

+
+ {{#bodyParams}}{{>bodyParam}}{{/bodyParams}} +
+ {{/hasBodyParam}} + + {{#hasHeaderParams}} +

Request headers

+
+ {{#headerParams}}{{>headerParam}}{{/headerParams}} +
+ {{/hasHeaderParams}} + + {{#hasQueryParams}} +

Query parameters

+
+ {{#queryParams}}{{>queryParam}}{{/queryParams}} +
+ {{/hasQueryParams}} + + {{#hasFormParams}} +

Form parameters

+
+ {{#formParams}}{{>formParam}}{{/formParams}} +
+ {{/hasFormParams}} + + {{#returnType}} +

Return type

+
+ {{#hasReference}}{{^returnSimpleType}}{{returnContainer}}[{{/returnSimpleType}}{{returnBaseType}}{{^returnSimpleType}}]{{/returnSimpleType}}{{/hasReference}} + {{^hasReference}}{{returnType}}{{/hasReference}} +
+ {{/returnType}} + + + + {{#hasExamples}} + {{#examples}} +

Example data

+
Content-Type: {{{contentType}}}
+
{{{example}}}
+ {{/examples}} + {{/hasExamples}} + + {{#hasProduces}} +

Produces

+ This API call produces the following media types according to the Accept request header; + the media type will be conveyed by the Content-Type response header. +
    + {{#produces}} +
  • {{{mediaType}}}
  • + {{/produces}} +
+ {{/hasProduces}} + +

Responses

+ {{#responses}} +

{{code}}

+ {{message}} + {{^containerType}}{{dataType}}{{/containerType}} + {{#examples}} +

Example data

+
Content-Type: {{{contentType}}}
+
{{example}}
+ {{/examples}} + {{/responses}} +
+
+ {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + +

Models

+ [ Jump to Methods ] + +

Table of Contents

+
    + {{#models}} + {{#model}} +
  1. {{name}}{{#title}} - {{.}}{{/title}}
  2. + {{/model}} + {{/models}} +
+ + {{#models}} + {{#model}} +
+

{{name}}{{#title}} - {{.}}{{/title}} Up

+ {{#unescapedDescription}}
{{.}}
{{/unescapedDescription}} +
+ {{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{^isPrimitiveType}}{{dataType}}{{/isPrimitiveType}} {{unescapedDescription}} {{#dataFormat}}format: {{{.}}}{{/dataFormat}}
+ {{#isEnum}} +
Enum:
+ {{#_enum}}
{{this}}
{{/_enum}} + {{/isEnum}} + {{/vars}} +
+
+ {{/model}} + {{/models}} +
+++++ diff --git a/docs/api/data-views/update.asciidoc b/docs/api/data-views/update.asciidoc index c1473b8f7079b..790656e6d6057 100644 --- a/docs/api/data-views/update.asciidoc +++ b/docs/api/data-views/update.asciidoc @@ -39,6 +39,7 @@ the data view is updated. The default is `false`. You can partially update the following fields: * `title` +* `name` * `timeFieldName` * `fields` * `sourceFilters` @@ -93,6 +94,7 @@ $ curl -X POST api/data_views/data-view/my-view { "data_view": { "title": "...", + "name": "...", "timeFieldName": "...", "sourceFilters": [], "fieldFormats": {}, diff --git a/docs/api/index-patterns/update.asciidoc b/docs/api/index-patterns/update.asciidoc index 64479f00ef5c5..809c01500b7f9 100644 --- a/docs/api/index-patterns/update.asciidoc +++ b/docs/api/index-patterns/update.asciidoc @@ -38,6 +38,7 @@ the index pattern is updated. The default is `false`. You can partially update the following fields: * `title` +* `name` * `timeFieldName` * `fields` * `sourceFilters` @@ -90,6 +91,7 @@ $ curl -X POST api/index_patterns/index-pattern/my-pattern { "index_pattern": { "title": "...", + "name": "...", "timeFieldName": "...", "sourceFilters": [], "fieldFormats": {}, diff --git a/docs/apis.asciidoc b/docs/apis.asciidoc new file mode 100644 index 0000000000000..8fb4caa7d3fca --- /dev/null +++ b/docs/apis.asciidoc @@ -0,0 +1,14 @@ +[role="exclude",id="apis"] += APIs + +[partintro] +-- + +preview::[] + +These APIs are documented using the OpenAPI specification. The current supported +version of the specification is 3.0. For more information, go to https://openapi-generator.tech/[OpenAPI Generator] + +-- + +include::api-generated/machine-learning/ml-apis.asciidoc[] \ No newline at end of file diff --git a/docs/index.asciidoc b/docs/index.asciidoc index 41321f991c1b0..2823529df18d3 100644 --- a/docs/index.asciidoc +++ b/docs/index.asciidoc @@ -29,4 +29,7 @@ include::CHANGELOG.asciidoc[] include::developer/index.asciidoc[] +include::apis.asciidoc[] + include::redirects.asciidoc[] + diff --git a/docs/redirects.asciidoc b/docs/redirects.asciidoc index 1a0757453c855..5c12048315dec 100644 --- a/docs/redirects.asciidoc +++ b/docs/redirects.asciidoc @@ -420,8 +420,3 @@ This page has been deleted. Refer to <>. == Sync machine learning saved objects API This page has been deleted. Refer to <>. - -[role="exclude",id="machine-learning-api"] -== Machine learning APIs - -This page has been deleted. Refer to <>. \ No newline at end of file diff --git a/docs/user/alerting/alerting-setup.asciidoc b/docs/user/alerting/alerting-setup.asciidoc index 819f20005d7a4..36c8b46e7b801 100644 --- a/docs/user/alerting/alerting-setup.asciidoc +++ b/docs/user/alerting/alerting-setup.asciidoc @@ -98,3 +98,10 @@ user without those privileges updates the rule, the rule will no longer function. Conversely, if a user with greater or administrator privileges modifies the rule, it will begin running with increased privileges. ============================================== + +[float] +[[alerting-ccs-setup]] +=== {ccs-cap} + +If you want to use alerting rules with {ccs}, you must configure +{ref}/remote-clusters-privileges.html#clusters-privileges-ccs-kibana[privileges for {ccs-init} and {kib}]. \ No newline at end of file diff --git a/docs/user/dashboard/images/dashboard_timeSliderControl_8.5.0.gif b/docs/user/dashboard/images/dashboard_timeSliderControl_8.5.0.gif new file mode 100644 index 0000000000000..89ca09dccc71e Binary files /dev/null and b/docs/user/dashboard/images/dashboard_timeSliderControl_8.5.0.gif differ diff --git a/docs/user/dashboard/images/dashboard_timeSliderControl_advanceBackward_8.5.0.png b/docs/user/dashboard/images/dashboard_timeSliderControl_advanceBackward_8.5.0.png new file mode 100644 index 0000000000000..e1c2e9921f687 Binary files /dev/null and b/docs/user/dashboard/images/dashboard_timeSliderControl_advanceBackward_8.5.0.png differ diff --git a/docs/user/dashboard/images/dashboard_timeSliderControl_advanceForward_8.5.0.png b/docs/user/dashboard/images/dashboard_timeSliderControl_advanceForward_8.5.0.png new file mode 100644 index 0000000000000..788621037cb07 Binary files /dev/null and b/docs/user/dashboard/images/dashboard_timeSliderControl_advanceForward_8.5.0.png differ diff --git a/docs/user/dashboard/images/dashboard_timeSliderControl_animate_8.5.0.png b/docs/user/dashboard/images/dashboard_timeSliderControl_animate_8.5.0.png new file mode 100644 index 0000000000000..63a93323d6a36 Binary files /dev/null and b/docs/user/dashboard/images/dashboard_timeSliderControl_animate_8.5.0.png differ diff --git a/docs/user/dashboard/make-dashboards-interactive.asciidoc b/docs/user/dashboard/make-dashboards-interactive.asciidoc index 7c80fa8588538..127c0a4a79e05 100644 --- a/docs/user/dashboard/make-dashboards-interactive.asciidoc +++ b/docs/user/dashboard/make-dashboards-interactive.asciidoc @@ -28,7 +28,7 @@ data-type="inline" *Controls* are interactive panels you add to your dashboards to filter and display only the data you want to explore. -There are two types of controls: +There are three types of controls: * *Options list* — Adds a dropdown that allows you to filter the data with one or more options that you select. + @@ -44,11 +44,17 @@ For example, if you are using the *[Logs] Web Traffic* dashboard from the sample [role="screenshot"] image::images/dashboard_controlsRangeSlider_8.3.0.png[Range slider control for the `hour_of_day` field with a range of `9` to `17` selected] +* *Time slider* — Adds a time range slider that allows you to filter the data within a specified range of time, advance the time range backward and forward, and animate your change in data over the specified time range. ++ +For example, you are using the *[Logs] Web Traffic* dashboard from the sample web logs data, and the global time filter is *Last 7 days*. When you add the time slider, you can click the previous and next buttons to advance the time range backward or forward, and click the play button to watch how the data changes over the last 7 days. +[role="screenshot"] +image::images/dashboard_timeSliderControl_8.5.0.gif[Time slider control for the the Last 7 days] + [float] -[[create-and-add-controls]] -==== Create and add controls +[[create-and-add-options-list-and-range-slider-controls]] +==== Create and add Options list and Range slider controls -To add interactive filters, create controls, then add them to your dashboard. +To add interactive Options list and Range slider controls, create the controls, then add them to your dashboard. . Open or create a new dashboard. @@ -79,8 +85,22 @@ The *Control type* is automatically applied for the field you selected. . Click *Save and close*. [float] -[[filter-the-data-with-options-lists]] -==== Filter the data with Options lists +[[add-time-slider-controls]] +==== Add time slider controls + +To add interactive time slider controls, create the control, then add it to your dashboard. + +. Open or create a new dashboard. + +. In the dashboard toolbar, click *Controls*, then select *Add time slider control*. + +. The time slider control uses the time range from the global time filter. To change the time range in the time slider control, <>. + +. Save the dashboard. + +[float] +[[filter-the-data-with-options-list-controls]] +==== Filter the data with Options list controls Filter the data with one or more options that you select. . Open the Options list dropdown. @@ -94,8 +114,8 @@ The dashboard displays only the data for the options you selected. . To display only the options you selected in the dropdown, click image:images/dashboard_showOnlySelectedOptions_8.3.0.png[The icon to display only the options you have selected in the Options list]. [float] -[[filter-the-data-with-range-sliders]] -==== Filter the data with Range sliders +[[filter-the-data-with-range-slider-controls]] +==== Filter the data with Range slider controls Filter the data within a specified range of values. . On the Range slider, click a value. @@ -106,6 +126,21 @@ The dashboard displays only the data for the range of values you specified. . To clear the specified values, click image:images/dashboard_controlsClearSelections_8.3.0.png[The icon to clear all specified values in the Range slider]. +[float] +[[filter-the-data-with-time-slider-controls]] +==== Filter the data with time slider controls +Filter the data within a specified range of time. + +. To view a different time range, click the time slider, then move the sliders to specify the time range you want to display. + +. To advance the time range forward, click image:images/dashboard_timeSliderControl_advanceForward_8.5.0.png[The icon to advance the time range forward]. + +. To advance the time range backward, click image:images/dashboard_timeSliderControl_advanceBackward_8.5.0.png[The icon to advance the time range backward]. + +. To animate the data changes over time, click image:images/dashboard_timeSliderControl_animate_8.5.0.png[The icon to clear all specified values in the Range slider]. + +. To clear the specified values, click image:images/dashboard_controlsClearSelections_8.3.0.png[The icon to clear all specified values in the Range slider]. + [float] [[configure-controls-settings]] ==== Configure the controls settings @@ -126,9 +161,9 @@ The dashboard displays only the data for the range of values you specified. [float] [[edit-controls]] -==== Edit controls +==== Edit Options list and Range slider control settings -Change the settings for a control. +Change the settings for the Options list and Range slider controls. . Hover over the control you want to edit, then click image:images/dashboard_controlsEditControl_8.3.0.png[The Edit control icon that opens the Edit control flyout]. diff --git a/docs/user/management.asciidoc b/docs/user/management.asciidoc index 908cdc792431c..02261d062e826 100644 --- a/docs/user/management.asciidoc +++ b/docs/user/management.asciidoc @@ -176,8 +176,6 @@ see the https://www.elastic.co/subscriptions[subscription page]. -- -include::{kib-repo-dir}/management/advanced-options.asciidoc[] - include::{kib-repo-dir}/management/cases/index.asciidoc[] include::{kib-repo-dir}/management/action-types.asciidoc[] @@ -196,6 +194,10 @@ include::security/index.asciidoc[] include::{kib-repo-dir}/spaces/index.asciidoc[] +include::{kib-repo-dir}/management/advanced-options.asciidoc[] + include::{kib-repo-dir}/management/managing-tags.asciidoc[] include::{kib-repo-dir}/management/watcher-ui/index.asciidoc[] + + diff --git a/docs/user/ml/images/classification.png b/docs/user/ml/images/classification.png new file mode 100644 index 0000000000000..492c44bfa5ce8 Binary files /dev/null and b/docs/user/ml/images/classification.png differ diff --git a/docs/user/ml/images/ml-explain-log-rate-before.png b/docs/user/ml/images/ml-explain-log-rate-before.png index e154ddbeebebf..2fcfae8951567 100644 Binary files a/docs/user/ml/images/ml-explain-log-rate-before.png and b/docs/user/ml/images/ml-explain-log-rate-before.png differ diff --git a/docs/user/ml/images/ml-explain-log-rate.png b/docs/user/ml/images/ml-explain-log-rate.png index c814ec50d6774..be007b22e1d4c 100644 Binary files a/docs/user/ml/images/ml-explain-log-rate.png and b/docs/user/ml/images/ml-explain-log-rate.png differ diff --git a/docs/user/ml/images/outliers.png b/docs/user/ml/images/outliers.png deleted file mode 100644 index 874ebbc79201c..0000000000000 Binary files a/docs/user/ml/images/outliers.png and /dev/null differ diff --git a/docs/user/ml/index.asciidoc b/docs/user/ml/index.asciidoc index fd86906f4b989..c58408d85d37b 100644 --- a/docs/user/ml/index.asciidoc +++ b/docs/user/ml/index.asciidoc @@ -94,16 +94,16 @@ If you have a license that includes the {ml-features}, you can create {kib}. For example: [role="screenshot"] -image::user/ml/images/outliers.png[{oldetection-cap} results in {kib}] +image::user/ml/images/classification.png[{classification-cap} results in {kib}] For more information about the {dfanalytics} feature, see {ml-docs}/ml-dfanalytics.html[{ml-cap} {dfanalytics}]. [[xpack-ml-aiops]] -== AIOps +== AIOps Labs -AIOps is a part of {ml-app} in {kib} which provides features that use advanced -statistical methods to help you interpret your data and its behavior. +AIOps Labs is a part of {ml-app} in {kib} which provides features that use +advanced statistical methods to help you interpret your data and its behavior. [discrete] [[explain-log-rate-spikes]] @@ -126,12 +126,14 @@ image::user/ml/images/ml-explain-log-rate-before.png[Log event histogram chart] Select a spike in the log event histogram chart to start the analysis. It identifies statistically significant field-value combinations that contribute to -the spike and displays them in a table. The table also shows an indicator of the -level of impact and a sparkline showing the shape of the impact in the chart. -Hovering over a row displays the impact on the histogram chart in more detail. -You can also pin a table row by clicking on it then move the cursor to the -histogram chart. It displays a tooltip with exact count values for the pinned -field which enables closer investigation. +the spike and displays them in a table. You can optionally choose to summarize +the results into groups. The table also shows an indicator of the level of +impact and a sparkline showing the shape of the impact in the chart. Hovering +over a row displays the impact on the histogram chart in more detail. You can +inspect a field in **Discover** by selecting this option under the **Actions** +column. You can also pin a table row by clicking on it then move the cursor to +the histogram chart. It displays a tooltip with exact count values for the +pinned field which enables closer investigation. Brushes in the chart show the baseline time range and the deviation in the analyzed data. You can move the brushes to redefine both the baseline and the @@ -140,6 +142,3 @@ deviation and rerun the analysis with the modified values. [role="screenshot"] image::user/ml/images/ml-explain-log-rate.png[Log rate spike explained] - - - diff --git a/docs/user/reporting/script-example.asciidoc b/docs/user/reporting/script-example.asciidoc index 1d8e824798e75..937e140bd67a0 100644 --- a/docs/user/reporting/script-example.asciidoc +++ b/docs/user/reporting/script-example.asciidoc @@ -3,7 +3,7 @@ URL that you use to download the report. Use the `GET` method in the HTTP reques To queue CSV report generation using the `POST` URL with cURL: -["source","sh",subs="attributes"] +[source,curl] --------------------------------------------------------- curl \ -XPOST \ <1> @@ -11,7 +11,6 @@ curl \ -H 'kbn-xsrf: true' \ <3> 'http://0.0.0.0:5601/api/reporting/generate/csv?jobParams=...' <4> --------------------------------------------------------- -// CONSOLE <1> The required `POST` method. <2> The user credentials for a user with permission to access {kib} and {report-features}. @@ -20,7 +19,7 @@ curl \ An example response for a successfully queued report: -[source,json] +[source,js] --------------------------------------------------------- { "path": "/api/reporting/jobs/download/jxzaofkc0ykpf4062305t068", <1> @@ -35,7 +34,6 @@ An example response for a successfully queued report: } } --------------------------------------------------------- -// CONSOLE <1> The relative path on the {kib} host for downloading the report. <2> (Not included in the example) Internal representation of the reporting job, as found in the `.reporting-*` index. diff --git a/examples/guided_onboarding_example/public/components/step_one.tsx b/examples/guided_onboarding_example/public/components/step_one.tsx index bacb43ad0f67a..3441b4d8e5d99 100644 --- a/examples/guided_onboarding_example/public/components/step_one.tsx +++ b/examples/guided_onboarding_example/public/components/step_one.tsx @@ -55,9 +55,8 @@ export const StepOne = ({ guidedOnboarding }: GuidedOnboardingExampleAppDeps) =>

diff --git a/examples/guided_onboarding_example/public/components/step_two.tsx b/examples/guided_onboarding_example/public/components/step_two.tsx index 9f96532450bfc..a79ce2329351e 100644 --- a/examples/guided_onboarding_example/public/components/step_two.tsx +++ b/examples/guided_onboarding_example/public/components/step_two.tsx @@ -11,7 +11,6 @@ import React, { useEffect, useState } from 'react'; import { EuiButton, EuiSpacer, EuiText, EuiTitle, EuiTourStep } from '@elastic/eui'; import { GuidedOnboardingPluginStart } from '@kbn/guided-onboarding-plugin/public/types'; -import { useHistory, useLocation } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiPageContentHeader_Deprecated as EuiPageContentHeader, @@ -26,18 +25,18 @@ export const StepTwo = (props: StepTwoProps) => { const { guidedOnboarding: { guidedOnboardingApi }, } = props; - const { search } = useLocation(); - const history = useHistory(); - - const query = React.useMemo(() => new URLSearchParams(search), [search]); - useEffect(() => { - if (query.get('showTour') === 'true') { - setIsTourStepOpen(true); - } - }, [query]); const [isTourStepOpen, setIsTourStepOpen] = useState(false); + useEffect(() => { + const subscription = guidedOnboardingApi + ?.isGuideStepActive$('search', 'browse_docs') + .subscribe((isStepActive) => { + setIsTourStepOpen(isStepActive); + }); + return () => subscription?.unsubscribe(); + }, [guidedOnboardingApi]); + return ( <> @@ -55,7 +54,8 @@ export const StepTwo = (props: StepTwoProps) => {

@@ -69,13 +69,11 @@ export const StepTwo = (props: StepTwoProps) => { isStepOpen={isTourStepOpen} minWidth={300} onFinish={() => { - history.push('/stepTwo'); - query.set('showTour', 'false'); setIsTourStepOpen(false); }} step={1} stepsTotal={1} - title="Step Add data" + title="Step Search experience" anchorPosition="rightUp" > /packages/core/http/core-http-request-handler-context-server-internal'], +}; diff --git a/packages/core/http/core-http-request-handler-context-server-internal/kibana.jsonc b/packages/core/http/core-http-request-handler-context-server-internal/kibana.jsonc new file mode 100644 index 0000000000000..98b452aec0d97 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/kibana.jsonc @@ -0,0 +1,7 @@ +{ + "type": "shared-common", + "id": "@kbn/core-http-request-handler-context-server-internal", + "owner": "@elastic/kibana-core", + "runtimeDeps": [], + "typeDeps": [], +} diff --git a/packages/core/http/core-http-request-handler-context-server-internal/package.json b/packages/core/http/core-http-request-handler-context-server-internal/package.json new file mode 100644 index 0000000000000..672bb6ce72715 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/core-http-request-handler-context-server-internal", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "author": "Kibana Core", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/src/core/server/core_route_handler_context.test.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.test.ts similarity index 86% rename from src/core/server/core_route_handler_context.test.ts rename to packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.test.ts index ace0144eae54f..f8e906650fcf1 100644 --- a/src/core/server/core_route_handler_context.test.ts +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.test.ts @@ -7,13 +7,14 @@ */ import { CoreRouteHandlerContext } from './core_route_handler_context'; -import { coreMock, httpServerMock } from './mocks'; +import { httpServerMock } from '@kbn/core-http-server-mocks'; +import { createCoreRouteHandlerContextParamsMock } from './test_helpers'; describe('#elasticsearch', () => { describe('#client', () => { test('returns the results of coreStart.elasticsearch.client.asScoped', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client = context.elasticsearch.client; @@ -22,7 +23,7 @@ describe('#elasticsearch', () => { test('lazily created', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); expect(coreStart.elasticsearch.client.asScoped).not.toHaveBeenCalled(); @@ -33,7 +34,7 @@ describe('#elasticsearch', () => { test('only creates one instance', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client1 = context.elasticsearch.client; @@ -50,7 +51,7 @@ describe('#savedObjects', () => { describe('#client', () => { test('returns the results of coreStart.savedObjects.getScopedClient', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client = context.savedObjects.client; @@ -59,7 +60,7 @@ describe('#savedObjects', () => { test('lazily created', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const savedObjects = context.savedObjects; @@ -71,7 +72,7 @@ describe('#savedObjects', () => { test('only creates one instance', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client1 = context.savedObjects.client; @@ -86,7 +87,7 @@ describe('#savedObjects', () => { describe('#typeRegistry', () => { test('returns the results of coreStart.savedObjects.getTypeRegistry', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const typeRegistry = context.savedObjects.typeRegistry; @@ -95,7 +96,7 @@ describe('#savedObjects', () => { test('lazily created', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); expect(coreStart.savedObjects.getTypeRegistry).not.toHaveBeenCalled(); @@ -106,7 +107,7 @@ describe('#savedObjects', () => { test('only creates one instance', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const typeRegistry1 = context.savedObjects.typeRegistry; @@ -123,7 +124,7 @@ describe('#uiSettings', () => { describe('#client', () => { test('returns the results of coreStart.uiSettings.asScopedToClient', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client = context.uiSettings.client; @@ -132,7 +133,7 @@ describe('#uiSettings', () => { test('lazily created', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); expect(coreStart.uiSettings.asScopedToClient).not.toHaveBeenCalled(); @@ -143,7 +144,7 @@ describe('#uiSettings', () => { test('only creates one instance', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client1 = context.uiSettings.client; @@ -160,7 +161,7 @@ describe('#deprecations', () => { describe('#client', () => { test('returns the results of coreStart.deprecations.asScopedToClient', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client = context.deprecations.client; @@ -169,7 +170,7 @@ describe('#deprecations', () => { test('lazily created', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); expect(coreStart.deprecations.asScopedToClient).not.toHaveBeenCalled(); @@ -180,7 +181,7 @@ describe('#deprecations', () => { test('only creates one instance', () => { const request = httpServerMock.createKibanaRequest(); - const coreStart = coreMock.createInternalStart(); + const coreStart = createCoreRouteHandlerContextParamsMock(); const context = new CoreRouteHandlerContext(coreStart, request); const client1 = context.deprecations.client; diff --git a/packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.ts new file mode 100644 index 0000000000000..6cc54130a575c --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/core_route_handler_context.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { KibanaRequest } from '@kbn/core-http-server'; +import type { CoreRequestHandlerContext } from '@kbn/core-http-request-handler-context-server'; +import { + CoreElasticsearchRouteHandlerContext, + type InternalElasticsearchServiceStart, +} from '@kbn/core-elasticsearch-server-internal'; +import { + CoreSavedObjectsRouteHandlerContext, + type InternalSavedObjectsServiceStart, +} from '@kbn/core-saved-objects-server-internal'; +import { + CoreDeprecationsRouteHandlerContext, + type InternalDeprecationsServiceStart, +} from '@kbn/core-deprecations-server-internal'; +import { + CoreUiSettingsRouteHandlerContext, + type InternalUiSettingsServiceStart, +} from '@kbn/core-ui-settings-server-internal'; + +/** + * Subset of `InternalCoreStart` used by {@link CoreRouteHandlerContext} + * @internal + */ +export interface CoreRouteHandlerContextParams { + elasticsearch: InternalElasticsearchServiceStart; + savedObjects: InternalSavedObjectsServiceStart; + uiSettings: InternalUiSettingsServiceStart; + deprecations: InternalDeprecationsServiceStart; +} + +/** + * The concrete implementation for Core's route handler context. + * + * @internal + */ +export class CoreRouteHandlerContext implements CoreRequestHandlerContext { + readonly elasticsearch: CoreElasticsearchRouteHandlerContext; + readonly savedObjects: CoreSavedObjectsRouteHandlerContext; + readonly uiSettings: CoreUiSettingsRouteHandlerContext; + readonly deprecations: CoreDeprecationsRouteHandlerContext; + + constructor(coreStart: CoreRouteHandlerContextParams, request: KibanaRequest) { + this.elasticsearch = new CoreElasticsearchRouteHandlerContext(coreStart.elasticsearch, request); + this.savedObjects = new CoreSavedObjectsRouteHandlerContext(coreStart.savedObjects, request); + this.uiSettings = new CoreUiSettingsRouteHandlerContext( + coreStart.uiSettings, + this.savedObjects + ); + this.deprecations = new CoreDeprecationsRouteHandlerContext( + coreStart.deprecations, + this.elasticsearch, + this.savedObjects + ); + } +} diff --git a/packages/core/http/core-http-request-handler-context-server-internal/src/index.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/index.ts new file mode 100644 index 0000000000000..48d93f78b2a48 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { CoreRouteHandlerContext } from './core_route_handler_context'; +export type { CoreRouteHandlerContextParams } from './core_route_handler_context'; +export { PrebootCoreRouteHandlerContext } from './preboot_core_route_handler_context'; +export type { PrebootCoreRouteHandlerContextParams } from './preboot_core_route_handler_context'; diff --git a/src/core/server/preboot_core_route_handler_context.test.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.test.ts similarity index 85% rename from src/core/server/preboot_core_route_handler_context.test.ts rename to packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.test.ts index 8d090d8644637..75bfc39bfdc9a 100644 --- a/src/core/server/preboot_core_route_handler_context.test.ts +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.test.ts @@ -7,12 +7,12 @@ */ import { PrebootCoreRouteHandlerContext } from './preboot_core_route_handler_context'; -import { coreMock } from './mocks'; +import { createPrebootCoreRouteHandlerContextParamsMock } from './test_helpers'; describe('#uiSettings', () => { describe('#client', () => { test('returns the results of corePreboot.uiSettings.createDefaultsClient', () => { - const corePreboot = coreMock.createInternalPreboot(); + const corePreboot = createPrebootCoreRouteHandlerContextParamsMock(); const context = new PrebootCoreRouteHandlerContext(corePreboot); const client = context.uiSettings.client; @@ -21,7 +21,7 @@ describe('#uiSettings', () => { }); test('only creates one instance', () => { - const corePreboot = coreMock.createInternalPreboot(); + const corePreboot = createPrebootCoreRouteHandlerContextParamsMock(); const context = new PrebootCoreRouteHandlerContext(corePreboot); const client1 = context.uiSettings.client; diff --git a/src/core/server/preboot_core_route_handler_context.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.ts similarity index 71% rename from src/core/server/preboot_core_route_handler_context.ts rename to packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.ts index ec5ef594180d1..c0bf184d8c985 100644 --- a/src/core/server/preboot_core_route_handler_context.ts +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/preboot_core_route_handler_context.ts @@ -8,13 +8,17 @@ // eslint-disable-next-line max-classes-per-file import type { IUiSettingsClient } from '@kbn/core-ui-settings-server'; -import type { InternalCorePreboot } from './internal_types'; +import type { + PrebootUiSettingsRequestHandlerContext, + PrebootCoreRequestHandlerContext, +} from '@kbn/core-http-request-handler-context-server'; +import type { InternalUiSettingsServicePreboot } from '@kbn/core-ui-settings-server-internal'; /** - * @public + * @internal */ -export interface PrebootUiSettingsRequestHandlerContext { - client: IUiSettingsClient; +export interface PrebootCoreRouteHandlerContextParams { + uiSettings: InternalUiSettingsServicePreboot; } /** @@ -25,13 +29,6 @@ class PrebootCoreUiSettingsRouteHandlerContext implements PrebootUiSettingsReque constructor(public readonly client: IUiSettingsClient) {} } -/** - * @public - */ -export interface PrebootCoreRequestHandlerContext { - uiSettings: PrebootUiSettingsRequestHandlerContext; -} - /** * Implementation of {@link PrebootCoreRequestHandlerContext}. * @internal @@ -39,7 +36,7 @@ export interface PrebootCoreRequestHandlerContext { export class PrebootCoreRouteHandlerContext implements PrebootCoreRequestHandlerContext { readonly uiSettings: PrebootUiSettingsRequestHandlerContext; - constructor(private readonly corePreboot: InternalCorePreboot) { + constructor(private readonly corePreboot: PrebootCoreRouteHandlerContextParams) { this.uiSettings = new PrebootCoreUiSettingsRouteHandlerContext( this.corePreboot.uiSettings.createDefaultsClient() ); diff --git a/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/core_route_handler_context_params.mock.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/core_route_handler_context_params.mock.ts new file mode 100644 index 0000000000000..eaf46eae3c8b6 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/core_route_handler_context_params.mock.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { elasticsearchServiceMock } from '@kbn/core-elasticsearch-server-mocks'; +import { savedObjectsServiceMock } from '@kbn/core-saved-objects-server-mocks'; +import { uiSettingsServiceMock } from '@kbn/core-ui-settings-server-mocks'; +import { deprecationsServiceMock } from '@kbn/core-deprecations-server-mocks'; + +export const createCoreRouteHandlerContextParamsMock = () => { + return { + elasticsearch: elasticsearchServiceMock.createInternalStart(), + savedObjects: savedObjectsServiceMock.createInternalStartContract(), + uiSettings: uiSettingsServiceMock.createStartContract(), + deprecations: deprecationsServiceMock.createInternalStartContract(), + }; +}; diff --git a/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/index.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/index.ts new file mode 100644 index 0000000000000..5556547d4602f --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { createCoreRouteHandlerContextParamsMock } from './core_route_handler_context_params.mock'; +export { createPrebootCoreRouteHandlerContextParamsMock } from './preboot_core_route_handler_context_params.mock'; diff --git a/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/preboot_core_route_handler_context_params.mock.ts b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/preboot_core_route_handler_context_params.mock.ts new file mode 100644 index 0000000000000..dc4eab6b55672 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/src/test_helpers/preboot_core_route_handler_context_params.mock.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { uiSettingsServiceMock } from '@kbn/core-ui-settings-server-mocks'; + +export const createPrebootCoreRouteHandlerContextParamsMock = () => { + return { + uiSettings: uiSettingsServiceMock.createPrebootContract(), + }; +}; diff --git a/packages/core/http/core-http-request-handler-context-server-internal/tsconfig.json b/packages/core/http/core-http-request-handler-context-server-internal/tsconfig.json new file mode 100644 index 0000000000000..71bb40fe57f3f --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server-internal/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts", + ] +} diff --git a/packages/core/http/core-http-request-handler-context-server/BUILD.bazel b/packages/core/http/core-http-request-handler-context-server/BUILD.bazel new file mode 100644 index 0000000000000..45c5ebc08776f --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/BUILD.bazel @@ -0,0 +1,110 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "core-http-request-handler-context-server" +PKG_REQUIRE_NAME = "@kbn/core-http-request-handler-context-server" + +SOURCE_FILES = glob( + [ + "**/*.ts", + ], + exclude = [ + "**/*.config.js", + "**/*.mock.*", + "**/*.test.*", + "**/*.stories.*", + "**/__snapshots__/**", + "**/integration_tests/**", + "**/mocks/**", + "**/scripts/**", + "**/storybook/**", + "**/test_fixtures/**", + "**/test_helpers/**", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +RUNTIME_DEPS = [ +] + +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "//packages/core/http/core-http-server:npm_module_types", + "//packages/core/elasticsearch/core-elasticsearch-server:npm_module_types", + "//packages/core/saved-objects/core-saved-objects-server:npm_module_types", + "//packages/core/deprecations/core-deprecations-server:npm_module_types", + "//packages/core/ui-settings/core-ui-settings-server:npm_module_types", +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/core/http/core-http-request-handler-context-server/README.md b/packages/core/http/core-http-request-handler-context-server/README.md new file mode 100644 index 0000000000000..b7b191f7345f3 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/README.md @@ -0,0 +1,3 @@ +# @kbn/core-http-request-handler-context-server + +This package contains the public types for Core's server-side `RequestHandlerContext` http subdomain. diff --git a/packages/core/http/core-http-request-handler-context-server/index.ts b/packages/core/http/core-http-request-handler-context-server/index.ts new file mode 100644 index 0000000000000..125c466d25d2c --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type { + RequestHandlerContext, + CoreRequestHandlerContext, + CustomRequestHandlerContext, + PrebootCoreRequestHandlerContext, + PrebootRequestHandlerContext, + PrebootUiSettingsRequestHandlerContext, +} from './src'; diff --git a/src/plugins/dashboard/common/embeddable/types.ts b/packages/core/http/core-http-request-handler-context-server/jest.config.js similarity index 68% rename from src/plugins/dashboard/common/embeddable/types.ts rename to packages/core/http/core-http-request-handler-context-server/jest.config.js index d786078766f78..dc60767ed0880 100644 --- a/src/plugins/dashboard/common/embeddable/types.ts +++ b/packages/core/http/core-http-request-handler-context-server/jest.config.js @@ -6,11 +6,8 @@ * Side Public License, v 1. */ -// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -export type GridData = { - w: number; - h: number; - x: number; - y: number; - i: string; +module.exports = { + preset: '@kbn/test/jest_node', + rootDir: '../../../..', + roots: ['/packages/core/http/core-http-request-handler-context-server'], }; diff --git a/packages/core/http/core-http-request-handler-context-server/kibana.jsonc b/packages/core/http/core-http-request-handler-context-server/kibana.jsonc new file mode 100644 index 0000000000000..3fba38b6444e4 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/kibana.jsonc @@ -0,0 +1,7 @@ +{ + "type": "shared-common", + "id": "@kbn/core-http-request-handler-context-server", + "owner": "@elastic/kibana-core", + "runtimeDeps": [], + "typeDeps": [], +} diff --git a/packages/core/http/core-http-request-handler-context-server/package.json b/packages/core/http/core-http-request-handler-context-server/package.json new file mode 100644 index 0000000000000..da85fc826828d --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/core-http-request-handler-context-server", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "author": "Kibana Core", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_constants.ts b/packages/core/http/core-http-request-handler-context-server/src/index.ts similarity index 53% rename from src/plugins/dashboard/public/application/embeddable/dashboard_constants.ts rename to packages/core/http/core-http-request-handler-context-server/src/index.ts index 2f7854e81ad95..2ab372a0ab975 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_constants.ts +++ b/packages/core/http/core-http-request-handler-context-server/src/index.ts @@ -6,8 +6,13 @@ * Side Public License, v 1. */ -export const DASHBOARD_GRID_COLUMN_COUNT = 48; -export const DASHBOARD_GRID_HEIGHT = 20; -export const DEFAULT_PANEL_WIDTH = DASHBOARD_GRID_COLUMN_COUNT / 2; -export const DEFAULT_PANEL_HEIGHT = 15; -export const DASHBOARD_CONTAINER_TYPE = 'dashboard'; +export type { + RequestHandlerContext, + CoreRequestHandlerContext, + CustomRequestHandlerContext, +} from './request_handler_context'; +export type { + PrebootRequestHandlerContext, + PrebootCoreRequestHandlerContext, + PrebootUiSettingsRequestHandlerContext, +} from './preboot_request_handler_context'; diff --git a/packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts b/packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.ts new file mode 100644 index 0000000000000..62caefe5619c6 --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/src/preboot_request_handler_context.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { RequestHandlerContextBase } from '@kbn/core-http-server'; +import type { IUiSettingsClient } from '@kbn/core-ui-settings-server'; + +/** + * @public + */ +export interface PrebootUiSettingsRequestHandlerContext { + client: IUiSettingsClient; +} + +/** + * @public + */ +export interface PrebootCoreRequestHandlerContext { + uiSettings: PrebootUiSettingsRequestHandlerContext; +} + +/** + * @public + */ +export interface PrebootRequestHandlerContext extends RequestHandlerContextBase { + core: Promise; +} diff --git a/src/core/server/core_route_handler_context.ts b/packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts similarity index 53% rename from src/core/server/core_route_handler_context.ts rename to packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts index 14cc99b501436..07704752bd8ed 100644 --- a/src/core/server/core_route_handler_context.ts +++ b/packages/core/http/core-http-request-handler-context-server/src/request_handler_context.ts @@ -6,16 +6,11 @@ * Side Public License, v 1. */ -import type { KibanaRequest } from '@kbn/core-http-server'; +import type { RequestHandlerContextBase } from '@kbn/core-http-server'; import type { ElasticsearchRequestHandlerContext } from '@kbn/core-elasticsearch-server'; -import { CoreElasticsearchRouteHandlerContext } from '@kbn/core-elasticsearch-server-internal'; import type { SavedObjectsRequestHandlerContext } from '@kbn/core-saved-objects-server'; -import { CoreSavedObjectsRouteHandlerContext } from '@kbn/core-saved-objects-server-internal'; import type { DeprecationsRequestHandlerContext } from '@kbn/core-deprecations-server'; -import { CoreDeprecationsRouteHandlerContext } from '@kbn/core-deprecations-server-internal'; import type { UiSettingsRequestHandlerContext } from '@kbn/core-ui-settings-server'; -import { CoreUiSettingsRouteHandlerContext } from '@kbn/core-ui-settings-server-internal'; -import type { InternalCoreStart } from './internal_types'; /** * The `core` context provided to route handler. @@ -39,27 +34,19 @@ export interface CoreRequestHandlerContext { } /** - * The concrete implementation for Core's route handler context. + * Base context passed to a route handler, containing the `core` context part. * - * @internal + * @public */ -export class CoreRouteHandlerContext implements CoreRequestHandlerContext { - readonly elasticsearch: CoreElasticsearchRouteHandlerContext; - readonly savedObjects: CoreSavedObjectsRouteHandlerContext; - readonly uiSettings: CoreUiSettingsRouteHandlerContext; - readonly deprecations: CoreDeprecationsRouteHandlerContext; - - constructor(coreStart: InternalCoreStart, request: KibanaRequest) { - this.elasticsearch = new CoreElasticsearchRouteHandlerContext(coreStart.elasticsearch, request); - this.savedObjects = new CoreSavedObjectsRouteHandlerContext(coreStart.savedObjects, request); - this.uiSettings = new CoreUiSettingsRouteHandlerContext( - coreStart.uiSettings, - this.savedObjects - ); - this.deprecations = new CoreDeprecationsRouteHandlerContext( - coreStart.deprecations, - this.elasticsearch, - this.savedObjects - ); - } +export interface RequestHandlerContext extends RequestHandlerContextBase { + core: Promise; } + +/** + * Mixin allowing plugins to define their own request handler contexts. + * + * @public + */ +export type CustomRequestHandlerContext = RequestHandlerContext & { + [Key in keyof T]: T[Key] extends Promise ? T[Key] : Promise; +}; diff --git a/packages/core/http/core-http-request-handler-context-server/tsconfig.json b/packages/core/http/core-http-request-handler-context-server/tsconfig.json new file mode 100644 index 0000000000000..71bb40fe57f3f --- /dev/null +++ b/packages/core/http/core-http-request-handler-context-server/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts", + ] +} diff --git a/packages/core/mount-utils/core-mount-utils-browser-internal/index.ts b/packages/core/mount-utils/core-mount-utils-browser-internal/index.ts index 50a2868ddb711..192ca09f6e85b 100644 --- a/packages/core/mount-utils/core-mount-utils-browser-internal/index.ts +++ b/packages/core/mount-utils/core-mount-utils-browser-internal/index.ts @@ -7,4 +7,3 @@ */ export { MountWrapper, mountReactNode } from './src/mount'; -export { KBN_LOAD_MARKS } from './src/consts'; diff --git a/packages/core/root/core-root-browser-internal/BUILD.bazel b/packages/core/root/core-root-browser-internal/BUILD.bazel new file mode 100644 index 0000000000000..d0d5e786d7867 --- /dev/null +++ b/packages/core/root/core-root-browser-internal/BUILD.bazel @@ -0,0 +1,172 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "core-root-browser-internal" +PKG_REQUIRE_NAME = "@kbn/core-root-browser-internal" + +SOURCE_FILES = glob( + [ + "**/*.ts", + "**/*.tsx", + "**/*.scss", + ], + exclude = [ + "**/*.config.js", + "**/*.mock.*", + "**/*.test.*", + "**/*.stories.*", + "**/__snapshots__/**", + "**/integration_tests/**", + "**/mocks/**", + "**/scripts/**", + "**/storybook/**", + "**/test_fixtures/**", + "**/test_helpers/**", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +RUNTIME_DEPS = [ + "@npm//rxjs", + "@npm//@elastic/apm-rum", + "//packages/kbn-std", + "//packages/kbn-i18n", + "//packages/kbn-ebt-tools", + "//packages/core/application/core-application-browser-internal", + "//packages/core/injected-metadata/core-injected-metadata-browser-internal", + "//packages/core/doc-links/core-doc-links-browser-internal", + "//packages/core/theme/core-theme-browser-internal", + "//packages/core/analytics/core-analytics-browser-internal", + "//packages/core/i18n/core-i18n-browser-internal", + "//packages/core/execution-context/core-execution-context-browser-internal", + "//packages/core/fatal-errors/core-fatal-errors-browser-internal", + "//packages/core/http/core-http-browser-internal", + "//packages/core/ui-settings/core-ui-settings-browser-internal", + "//packages/core/deprecations/core-deprecations-browser-internal", + "//packages/core/integrations/core-integrations-browser-internal", + "//packages/core/overlays/core-overlays-browser-internal", + "//packages/core/saved-objects/core-saved-objects-browser-internal", + "//packages/core/notifications/core-notifications-browser-internal", + "//packages/core/chrome/core-chrome-browser-internal", + "//packages/core/rendering/core-rendering-browser-internal", + "//packages/core/apps/core-apps-browser-internal", + "//packages/core/lifecycle/core-lifecycle-browser-internal", + "//packages/core/plugins/core-plugins-browser-internal", +] + +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "@npm//rxjs", + "@npm//@elastic/apm-rum", + "//packages/kbn-std:npm_module_types", + "//packages/kbn-i18n:npm_module_types", + "//packages/kbn-ebt-tools:npm_module_types", + "//packages/core/execution-context/core-execution-context-browser:npm_module_types", + "//packages/core/application/core-application-browser-internal:npm_module_types", + "//packages/core/base/core-base-browser-internal:npm_module_types", + "//packages/core/injected-metadata/core-injected-metadata-browser-internal:npm_module_types", + "//packages/core/doc-links/core-doc-links-browser-internal:npm_module_types", + "//packages/core/theme/core-theme-browser-internal:npm_module_types", + "//packages/core/analytics/core-analytics-browser:npm_module_types", + "//packages/core/analytics/core-analytics-browser-internal:npm_module_types", + "//packages/core/i18n/core-i18n-browser-internal:npm_module_types", + "//packages/core/execution-context/core-execution-context-browser-internal:npm_module_types", + "//packages/core/fatal-errors/core-fatal-errors-browser:npm_module_types", + "//packages/core/fatal-errors/core-fatal-errors-browser-internal:npm_module_types", + "//packages/core/http/core-http-browser-internal:npm_module_types", + "//packages/core/ui-settings/core-ui-settings-browser-internal:npm_module_types", + "//packages/core/deprecations/core-deprecations-browser-internal:npm_module_types", + "//packages/core/integrations/core-integrations-browser-internal:npm_module_types", + "//packages/core/overlays/core-overlays-browser-internal:npm_module_types", + "//packages/core/saved-objects/core-saved-objects-browser-internal:npm_module_types", + "//packages/core/notifications/core-notifications-browser-internal:npm_module_types", + "//packages/core/chrome/core-chrome-browser-internal:npm_module_types", + "//packages/core/rendering/core-rendering-browser-internal:npm_module_types", + "//packages/core/apps/core-apps-browser-internal:npm_module_types", + "//packages/core/lifecycle/core-lifecycle-browser-internal:npm_module_types", + "//packages/core/plugins/core-plugins-browser-internal:npm_module_types", +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +jsts_transpiler( + name = "target_web", + srcs = SRCS, + build_pkg_name = package_name(), + web = True, + additional_args = [ + "--copy-files", + "--quiet" + ], +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node", ":target_web"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/core/root/core-root-browser-internal/README.md b/packages/core/root/core-root-browser-internal/README.md new file mode 100644 index 0000000000000..522df736da29c --- /dev/null +++ b/packages/core/root/core-root-browser-internal/README.md @@ -0,0 +1,5 @@ +# @kbn/core-root-browser-internal + +This package exposes the root components required to start the Core system on the browser side. +- `CoreSystem` +- `__kbnBootstrap__` diff --git a/src/plugins/dashboard/public/saved_dashboards/index.ts b/packages/core/root/core-root-browser-internal/index.ts similarity index 73% rename from src/plugins/dashboard/public/saved_dashboards/index.ts rename to packages/core/root/core-root-browser-internal/index.ts index 7a17aa6f2c0e0..032a4bd1eb8b1 100644 --- a/src/plugins/dashboard/public/saved_dashboards/index.ts +++ b/packages/core/root/core-root-browser-internal/index.ts @@ -6,6 +6,5 @@ * Side Public License, v 1. */ -export * from '../../common/saved_dashboard_references'; -export * from './saved_dashboard'; -export * from './saved_dashboards'; +export { CoreSystem, __kbnBootstrap__ } from './src'; +export type { CoreSystemParams } from './src'; diff --git a/packages/core/root/core-root-browser-internal/jest.config.js b/packages/core/root/core-root-browser-internal/jest.config.js new file mode 100644 index 0000000000000..4f81bcdaaf118 --- /dev/null +++ b/packages/core/root/core-root-browser-internal/jest.config.js @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../..', + roots: ['/packages/core/root/core-root-browser-internal'], +}; diff --git a/packages/core/root/core-root-browser-internal/kibana.jsonc b/packages/core/root/core-root-browser-internal/kibana.jsonc new file mode 100644 index 0000000000000..0dd7d5ae6beb4 --- /dev/null +++ b/packages/core/root/core-root-browser-internal/kibana.jsonc @@ -0,0 +1,7 @@ +{ + "type": "shared-common", + "id": "@kbn/core-root-browser-internal", + "owner": "@elastic/kibana-core", + "runtimeDeps": [], + "typeDeps": [], +} diff --git a/packages/core/root/core-root-browser-internal/package.json b/packages/core/root/core-root-browser-internal/package.json new file mode 100644 index 0000000000000..30a34c02fc4eb --- /dev/null +++ b/packages/core/root/core-root-browser-internal/package.json @@ -0,0 +1,9 @@ +{ + "name": "@kbn/core-root-browser-internal", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "browser": "./target_web/index.js", + "author": "Kibana Core", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/src/core/public/apm_resource_counter.ts b/packages/core/root/core-root-browser-internal/src/apm_resource_counter.ts similarity index 100% rename from src/core/public/apm_resource_counter.ts rename to packages/core/root/core-root-browser-internal/src/apm_resource_counter.ts diff --git a/src/core/public/apm_system.test.ts b/packages/core/root/core-root-browser-internal/src/apm_system.test.ts similarity index 100% rename from src/core/public/apm_system.test.ts rename to packages/core/root/core-root-browser-internal/src/apm_system.test.ts diff --git a/src/core/public/apm_system.ts b/packages/core/root/core-root-browser-internal/src/apm_system.ts similarity index 100% rename from src/core/public/apm_system.ts rename to packages/core/root/core-root-browser-internal/src/apm_system.ts diff --git a/src/core/public/_core.scss b/packages/core/root/core-root-browser-internal/src/core_system.scss similarity index 100% rename from src/core/public/_core.scss rename to packages/core/root/core-root-browser-internal/src/core_system.scss diff --git a/src/core/public/core_system.test.mocks.ts b/packages/core/root/core-root-browser-internal/src/core_system.test.mocks.ts similarity index 100% rename from src/core/public/core_system.test.mocks.ts rename to packages/core/root/core-root-browser-internal/src/core_system.test.mocks.ts diff --git a/src/core/public/core_system.test.ts b/packages/core/root/core-root-browser-internal/src/core_system.test.ts similarity index 100% rename from src/core/public/core_system.test.ts rename to packages/core/root/core-root-browser-internal/src/core_system.test.ts diff --git a/src/core/public/core_system.ts b/packages/core/root/core-root-browser-internal/src/core_system.ts similarity index 98% rename from src/core/public/core_system.ts rename to packages/core/root/core-root-browser-internal/src/core_system.ts index 4381cfdd2abf9..b3eae041b785d 100644 --- a/src/core/public/core_system.ts +++ b/packages/core/root/core-root-browser-internal/src/core_system.ts @@ -26,7 +26,6 @@ import { DeprecationsService } from '@kbn/core-deprecations-browser-internal'; import { IntegrationsService } from '@kbn/core-integrations-browser-internal'; import { reportPerformanceMetricEvent } from '@kbn/ebt-tools'; import { OverlayService } from '@kbn/core-overlays-browser-internal'; -import { KBN_LOAD_MARKS } from '@kbn/core-mount-utils-browser-internal'; import { SavedObjectsService } from '@kbn/core-saved-objects-browser-internal'; import { NotificationsService } from '@kbn/core-notifications-browser-internal'; import { ChromeService } from '@kbn/core-chrome-browser-internal'; @@ -35,6 +34,7 @@ import { RenderingService } from '@kbn/core-rendering-browser-internal'; import { CoreAppsService } from '@kbn/core-apps-browser-internal'; import type { InternalCoreSetup, InternalCoreStart } from '@kbn/core-lifecycle-browser-internal'; import { PluginsService } from '@kbn/core-plugins-browser-internal'; +import { KBN_LOAD_MARKS } from './events'; import { fetchOptionalMemoryInfo } from './fetch_optional_memory_info'; import { @@ -47,7 +47,12 @@ import { LOAD_START, } from './events'; -interface Params { +import './core_system.scss'; + +/** + * @internal + */ +export interface CoreSystemParams { rootDomElement: HTMLElement; browserSupportsCsp: boolean; injectedMetadata: InjectedMetadataParams['injectedMetadata']; @@ -96,7 +101,7 @@ export class CoreSystem { private readonly executionContext: ExecutionContextService; private fatalErrorsSetup: FatalErrorsSetup | null = null; - constructor(params: Params) { + constructor(params: CoreSystemParams) { const { rootDomElement, browserSupportsCsp, injectedMetadata } = params; this.rootDomElement = rootDomElement; diff --git a/src/core/public/events.ts b/packages/core/root/core-root-browser-internal/src/events.ts similarity index 97% rename from src/core/public/events.ts rename to packages/core/root/core-root-browser-internal/src/events.ts index e2f5d48ddfe3d..50337778c8c3c 100644 --- a/src/core/public/events.ts +++ b/packages/core/root/core-root-browser-internal/src/events.ts @@ -6,11 +6,8 @@ * Side Public License, v 1. */ -/** @internal */ export const KBN_LOAD_MARKS = 'kbnLoad'; - export const KIBANA_LOADED_EVENT = 'kibana_loaded'; - export const LOAD_START = 'load_started'; export const LOAD_BOOTSTRAP_START = 'bootstrap_started'; export const LOAD_CORE_CREATED = 'core_created'; diff --git a/src/core/public/fetch_optional_memory_info.test.ts b/packages/core/root/core-root-browser-internal/src/fetch_optional_memory_info.test.ts similarity index 100% rename from src/core/public/fetch_optional_memory_info.test.ts rename to packages/core/root/core-root-browser-internal/src/fetch_optional_memory_info.test.ts diff --git a/src/core/public/fetch_optional_memory_info.ts b/packages/core/root/core-root-browser-internal/src/fetch_optional_memory_info.ts similarity index 100% rename from src/core/public/fetch_optional_memory_info.ts rename to packages/core/root/core-root-browser-internal/src/fetch_optional_memory_info.ts diff --git a/packages/core/root/core-root-browser-internal/src/index.ts b/packages/core/root/core-root-browser-internal/src/index.ts new file mode 100644 index 0000000000000..663af54e573eb --- /dev/null +++ b/packages/core/root/core-root-browser-internal/src/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { __kbnBootstrap__ } from './kbn_bootstrap'; +export { CoreSystem } from './core_system'; +export type { CoreSystemParams } from './core_system'; diff --git a/src/core/public/kbn_bootstrap.test.mocks.ts b/packages/core/root/core-root-browser-internal/src/kbn_bootstrap.test.mocks.ts similarity index 100% rename from src/core/public/kbn_bootstrap.test.mocks.ts rename to packages/core/root/core-root-browser-internal/src/kbn_bootstrap.test.mocks.ts diff --git a/src/core/public/kbn_bootstrap.test.ts b/packages/core/root/core-root-browser-internal/src/kbn_bootstrap.test.ts similarity index 100% rename from src/core/public/kbn_bootstrap.test.ts rename to packages/core/root/core-root-browser-internal/src/kbn_bootstrap.test.ts diff --git a/src/core/public/kbn_bootstrap.ts b/packages/core/root/core-root-browser-internal/src/kbn_bootstrap.ts similarity index 95% rename from src/core/public/kbn_bootstrap.ts rename to packages/core/root/core-root-browser-internal/src/kbn_bootstrap.ts index 0359f9e4d6520..c1ca8cb752d2d 100644 --- a/src/core/public/kbn_bootstrap.ts +++ b/packages/core/root/core-root-browser-internal/src/kbn_bootstrap.ts @@ -7,7 +7,7 @@ */ import { i18n } from '@kbn/i18n'; -import { KBN_LOAD_MARKS } from '@kbn/core-mount-utils-browser-internal'; +import { KBN_LOAD_MARKS } from './events'; import { CoreSystem } from './core_system'; import { ApmSystem } from './apm_system'; diff --git a/packages/core/root/core-root-browser-internal/tsconfig.json b/packages/core/root/core-root-browser-internal/tsconfig.json new file mode 100644 index 0000000000000..4283cbe1b760b --- /dev/null +++ b/packages/core/root/core-root-browser-internal/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "stripInternal": false, + "types": [ + "jest", + "node", + ] + }, + "include": [ + "**/*.ts", + "**/*.tsx", + ] +} diff --git a/packages/kbn-apm-synthtrace/src/cli/run_synthtrace.ts b/packages/kbn-apm-synthtrace/src/cli/run_synthtrace.ts index ecfbd4a387f34..517d2d61d799f 100644 --- a/packages/kbn-apm-synthtrace/src/cli/run_synthtrace.ts +++ b/packages/kbn-apm-synthtrace/src/cli/run_synthtrace.ts @@ -15,7 +15,7 @@ import { parseRunCliFlags } from './utils/parse_run_cli_flags'; import { getCommonServices } from './utils/get_common_services'; import { ApmSynthtraceKibanaClient } from '../lib/apm/client/apm_synthtrace_kibana_client'; import { StreamAggregator } from '../lib/stream_aggregator'; -import { ServiceLatencyAggregator } from '../lib/apm/aggregators/service_latency_aggregator'; +import { ServicMetricsAggregator } from '../lib/apm/aggregators/service_metrics_aggregator'; function options(y: Argv) { return y @@ -207,7 +207,7 @@ export function runSynthtrace() { } const aggregators: StreamAggregator[] = []; const registry = new Map StreamAggregator[]>([ - ['service', () => [new ServiceLatencyAggregator()]], + ['service', () => [new ServicMetricsAggregator()]], ]); if (runOptions.streamProcessors && runOptions.streamProcessors.length > 0) { for (const processorName of runOptions.streamProcessors) { diff --git a/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts b/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts index 720b1b0527e80..54ce5b1b2e328 100644 --- a/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts +++ b/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts @@ -16,7 +16,7 @@ import { StreamProcessor } from '../../lib/stream_processor'; import { Scenario } from '../scenario'; import { EntityIterable, Fields } from '../../..'; import { StreamAggregator } from '../../lib/stream_aggregator'; -import { ServiceLatencyAggregator } from '../../lib/apm/aggregators/service_latency_aggregator'; +import { ServicMetricsAggregator } from '../../lib/apm/aggregators/service_metrics_aggregator'; // logging proxy to main thread, ensures we see real time logging const l = { @@ -63,7 +63,7 @@ async function setup() { parentPort?.postMessage({ workerIndex, lastTimestamp: item['@timestamp'] }); } }; - const aggregators: StreamAggregator[] = [new ServiceLatencyAggregator()]; + const aggregators: StreamAggregator[] = [new ServicMetricsAggregator()]; // If we are sending data to apm-server we do not have to create any aggregates in the stream processor streamProcessor = new StreamProcessor({ version, diff --git a/packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_latency_aggregator.ts b/packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_metrics_aggregator.ts similarity index 78% rename from packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_latency_aggregator.ts rename to packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_metrics_aggregator.ts index e28ba234b2a49..618c9e52b9f2c 100644 --- a/packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_latency_aggregator.ts +++ b/packages/kbn-apm-synthtrace/src/lib/apm/aggregators/service_metrics_aggregator.ts @@ -12,12 +12,14 @@ import { ApmFields } from '../apm_fields'; import { Fields } from '../../entity'; import { StreamAggregator } from '../../stream_aggregator'; -type LatencyState = { +type AggregationState = { count: number; min: number; max: number; sum: number; timestamp: number; + failure_count: number; + success_count: number; } & Pick; export type ServiceFields = Fields & @@ -35,15 +37,22 @@ export type ServiceFields = Fields & | 'transaction.type' > & Partial<{ - 'transaction.duration.aggregate': { - min: number; - max: number; - sum: number; - value_count: number; + _doc_count: number; + transaction: { + duration: { + summary: { + min: number; + max: number; + sum: number; + value_count: number; + }; + }; + failure_count: number; + success_count: number; }; }>; -export class ServiceLatencyAggregator implements StreamAggregator { +export class ServicMetricsAggregator implements StreamAggregator { public readonly name; constructor() { @@ -68,7 +77,7 @@ export class ServiceLatencyAggregator implements StreamAggregator { duration: { type: 'object', properties: { - aggregate: { + summary: { type: 'aggregate_metric_double', metrics: ['min', 'max', 'sum', 'value_count'], default_metric: 'sum', @@ -76,6 +85,12 @@ export class ServiceLatencyAggregator implements StreamAggregator { }, }, }, + failure_count: { + type: { type: 'long' }, + }, + success_count: { + type: { type: 'long' }, + }, }, }, service: { @@ -99,7 +114,7 @@ export class ServiceLatencyAggregator implements StreamAggregator { return null; } - private state: Record = {}; + private state: Record = {}; private processedComponent: number = 0; @@ -120,13 +135,25 @@ export class ServiceLatencyAggregator implements StreamAggregator { 'service.name': service, 'service.environment': environment, 'transaction.type': transactionType, + failure_count: 0, + success_count: 0, }; } + + const state = this.state[key]; + state.count++; + + switch (event['event.outcome']) { + case 'failure': + state.failure_count++; + break; + case 'success': + state.success_count++; + break; + } + const duration = Number(event['transaction.duration.us']); if (duration >= 0) { - const state = this.state[key]; - - state.count++; state.sum += duration; if (duration > state.max) state.max = duration; if (duration < state.min) state.min = Math.min(0, duration); @@ -164,17 +191,24 @@ export class ServiceLatencyAggregator implements StreamAggregator { const component = Date.now() % 100; const state = this.state[key]; return { + _doc_count: state.count, '@timestamp': state.timestamp + random(0, 100) + component + this.processedComponent, 'metricset.name': 'service', 'processor.event': 'metric', 'service.name': state['service.name'], 'service.environment': state['service.environment'], 'transaction.type': state['transaction.type'], - 'transaction.duration.aggregate': { - min: state.min, - max: state.max, - sum: state.sum, - value_count: state.count, + transaction: { + duration: { + summary: { + min: state.min, + max: state.max, + sum: state.sum, + value_count: state.count, + }, + }, + failure_count: state.failure_count, + success_count: state.success_count, }, }; } diff --git a/packages/kbn-apm-synthtrace/src/lib/apm/client/apm_synthtrace_kibana_client.ts b/packages/kbn-apm-synthtrace/src/lib/apm/client/apm_synthtrace_kibana_client.ts index 7bd2443031c80..133ec096370b9 100644 --- a/packages/kbn-apm-synthtrace/src/lib/apm/client/apm_synthtrace_kibana_client.ts +++ b/packages/kbn-apm-synthtrace/src/lib/apm/client/apm_synthtrace_kibana_client.ts @@ -7,7 +7,6 @@ */ import fetch from 'node-fetch'; -import Semver from 'semver'; import { Logger } from '../../utils/create_logger'; export class ApmSynthtraceKibanaClient { @@ -53,31 +52,33 @@ export class ApmSynthtraceKibanaClient { return kibanaUrl; }); } - async fetchLatestApmPackageVersion(currentKibanaVersion: string) { - const url = `https://epr-snapshot.elastic.co/search?package=apm&prerelease=true&all=true&kibana.version=${currentKibanaVersion}`; - const response = await fetch(url, { method: 'GET' }); - const json = (await response.json()) as Array<{ version: string }>; - const packageVersions = (json ?? []).map((item) => item.version).sort(Semver.rcompare); - const validPackageVersions = packageVersions.filter((v) => Semver.valid(v)); - const bestMatch = validPackageVersions[0]; - if (!bestMatch) { - throw new Error( - `None of the available APM package versions matches the current Kibana version (${currentKibanaVersion}). The latest available version is ${packageVersions[0]}. This can happen if the Kibana version was recently bumped, and no matching APM package was released. Reach out to the fleet team if this persists.` - ); - } - return bestMatch; + + async fetchLatestApmPackageVersion( + kibanaUrl: string, + version: string, + username: string, + password: string + ) { + const url = `${kibanaUrl}/api/fleet/epm/packages/apm`; + const response = await fetch(url, { + method: 'GET', + headers: kibanaHeaders(username, password), + }); + const json = (await response.json()) as { item: { latestVersion: string } }; + const { latestVersion } = json.item; + return latestVersion; } async installApmPackage(kibanaUrl: string, version: string, username: string, password: string) { - const packageVersion = await this.fetchLatestApmPackageVersion(version); + const packageVersion = await this.fetchLatestApmPackageVersion( + kibanaUrl, + version, + username, + password + ); const response = await fetch(`${kibanaUrl}/api/fleet/epm/packages/apm/${packageVersion}`, { method: 'POST', - headers: { - Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64'), - Accept: 'application/json', - 'Content-Type': 'application/json', - 'kbn-xsrf': 'kibana', - }, + headers: kibanaHeaders(username, password), body: '{"force":true}', }); @@ -93,3 +94,12 @@ export class ApmSynthtraceKibanaClient { } else this.logger.error(responseJson); } } + +function kibanaHeaders(username: string, password: string) { + return { + Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64'), + Accept: 'application/json', + 'Content-Type': 'application/json', + 'kbn-xsrf': 'kibana', + }; +} diff --git a/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file.ts b/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file.ts index d34df80f3d0a8..da643164a14aa 100644 --- a/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file.ts +++ b/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file.ts @@ -44,12 +44,26 @@ async function getJourneySnapshotHtml(log: ToolingLog, journeyMeta: JourneyMeta) return [ '
', '
Steps
', - ...screenshots.get().flatMap(({ title, path }) => { + ...screenshots.get().flatMap(({ title, path, fullscreenPath }) => { const base64 = Fs.readFileSync(path, 'base64'); + const fullscreenBase64 = Fs.readFileSync(fullscreenPath, 'base64'); return [ `

${escape(title)}

`, - ``, + `
+ + + + +
`, ]; }), '
', @@ -88,7 +102,11 @@ function getFtrScreenshotHtml(log: ToolingLog, failureName: string) { .filter((s) => s.name.startsWith(FtrScreenshotFilename.create(failureName, { ext: false }))) .map((s) => { const base64 = Fs.readFileSync(s.path).toString('base64'); - return ``; + return ` +
+ +
+ `; }) .join('\n'); } diff --git a/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file_html_template.html b/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file_html_template.html index 485a2c2d4eb3f..01ebc4ba22210 100644 --- a/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file_html_template.html +++ b/packages/kbn-failed-test-reporter-cli/failed_tests_reporter/report_failures_to_file_html_template.html @@ -16,12 +16,24 @@ img.screenshot { cursor: pointer; - height: 200px; margin: 5px 0; } + .screenshotContainer:not(.expanded) img.screenshot { + height: 200px; + } + + .screenshotContainer:not(.fs) img.screenshot.fs, + .screenshotContainer:not(.fs) button.toggleFs.off, + .screenshotContainer.fs img.screenshot:not(.fs), + .screenshotContainer.fs button.toggleFs.on { + display: none; + } - img.screenshot.expanded { - height: auto; + .screenshotContainer .toggleFs { + background: none; + border: none; + margin: 0 0 0 5px; + vertical-align: top; } $TITLE @@ -31,11 +43,46 @@
$MAIN
diff --git a/packages/kbn-ftr-common-functional-services/services/es_archiver.ts b/packages/kbn-ftr-common-functional-services/services/es_archiver.ts index 8a81297bf1784..abb0b89544bc1 100644 --- a/packages/kbn-ftr-common-functional-services/services/es_archiver.ts +++ b/packages/kbn-ftr-common-functional-services/services/es_archiver.ts @@ -18,6 +18,7 @@ export function EsArchiverProvider({ getService }: FtrProviderContext): EsArchiv const retry = getService('retry'); const esArchiver = new EsArchiver({ + baseDir: config.get('esArchiver.baseDirectory'), client, log, kbnClient: kibanaServer, diff --git a/packages/kbn-journeys/journey/journey_ftr_config.ts b/packages/kbn-journeys/journey/journey_ftr_config.ts index 392ad69b63ba1..b0d8e33ad01c0 100644 --- a/packages/kbn-journeys/journey/journey_ftr_config.ts +++ b/packages/kbn-journeys/journey/journey_ftr_config.ts @@ -82,7 +82,7 @@ export function makeFtrConfigProvider( kbnTestServer: { ...baseConfig.kbnTestServer, // delay shutdown by 15 seconds to ensure that APM can report the data it collects during test execution - delayShutdown: 15_000, + delayShutdown: process.env.TEST_PERFORMANCE_PHASE === 'TEST' ? 15_000 : 0, serverArgs: [ ...baseConfig.kbnTestServer.serverArgs, diff --git a/packages/kbn-journeys/journey/journey_ftr_harness.ts b/packages/kbn-journeys/journey/journey_ftr_harness.ts index 672b14f0e1a85..6154581738ac7 100644 --- a/packages/kbn-journeys/journey/journey_ftr_harness.ts +++ b/packages/kbn-journeys/journey/journey_ftr_harness.ts @@ -198,7 +198,12 @@ export class JourneyFtrHarness { return; } - await this.screenshots.addSuccess(step, await this.page.screenshot()); + const [screenshot, fs] = await Promise.all([ + this.page.screenshot(), + this.page.screenshot({ fullPage: true }), + ]); + + await this.screenshots.addSuccess(step, screenshot, fs); } private async onStepError(step: AnyStep, err: Error) { @@ -208,7 +213,12 @@ export class JourneyFtrHarness { } if (this.page) { - await this.screenshots.addError(step, await this.page.screenshot()); + const [screenshot, fs] = await Promise.all([ + this.page.screenshot(), + this.page.screenshot({ fullPage: true }), + ]); + + await this.screenshots.addError(step, screenshot, fs); } } diff --git a/packages/kbn-journeys/journey/journey_screenshots.ts b/packages/kbn-journeys/journey/journey_screenshots.ts index 8cd36444ef7ee..adf1021fa163d 100644 --- a/packages/kbn-journeys/journey/journey_screenshots.ts +++ b/packages/kbn-journeys/journey/journey_screenshots.ts @@ -19,6 +19,7 @@ interface StepShot { type: 'success' | 'failure'; title: string; filename: string; + fullscreenFilename: string; } interface Manifest { @@ -87,34 +88,44 @@ export class JourneyScreenshots { } } - async addError(step: AnyStep, screenshot: Buffer) { + async addError(step: AnyStep, screenshot: Buffer, fullscreenScreenshot: Buffer) { await this.lock(async () => { const filename = FtrScreenshotFilename.create(`${step.index}-${step.name}-failure`); + const fullscreenFilename = FtrScreenshotFilename.create( + `${step.index}-${step.name}-failure-fullscreen` + ); this.#manifest.steps.push({ type: 'failure', title: `Step #${step.index + 1}: ${step.name} - FAILED`, filename, + fullscreenFilename, }); await Promise.all([ write(Path.resolve(this.#dir, 'manifest.json'), JSON.stringify(this.#manifest)), write(Path.resolve(this.#dir, filename), screenshot), + write(Path.resolve(this.#dir, fullscreenFilename), fullscreenScreenshot), ]); }); } - async addSuccess(step: AnyStep, screenshot: Buffer) { + async addSuccess(step: AnyStep, screenshot: Buffer, fullscreenScreenshot: Buffer) { await this.lock(async () => { const filename = FtrScreenshotFilename.create(`${step.index}-${step.name}`); + const fullscreenFilename = FtrScreenshotFilename.create( + `${step.index}-${step.name}-fullscreen` + ); this.#manifest.steps.push({ type: 'success', title: `Step #${step.index + 1}: ${step.name} - DONE`, filename, + fullscreenFilename, }); await Promise.all([ write(Path.resolve(this.#dir, 'manifest.json'), JSON.stringify(this.#manifest)), write(Path.resolve(this.#dir, filename), screenshot), + write(Path.resolve(this.#dir, fullscreenFilename), fullscreenScreenshot), ]); }); } @@ -123,6 +134,7 @@ export class JourneyScreenshots { return this.#manifest.steps.map((stepShot) => ({ ...stepShot, path: Path.resolve(this.#dir, stepShot.filename), + fullscreenPath: Path.resolve(this.#dir, stepShot.fullscreenFilename), })); } } diff --git a/packages/kbn-optimizer/limits.yml b/packages/kbn-optimizer/limits.yml index b8de0b6daa3b5..440ff3ce2b12c 100644 --- a/packages/kbn-optimizer/limits.yml +++ b/packages/kbn-optimizer/limits.yml @@ -71,7 +71,7 @@ pageLoadAssetSize: kibanaUsageCollection: 16463 kibanaUtils: 79713 kubernetesSecurity: 77234 - lens: 36000 + lens: 36500 licenseManagement: 41817 licensing: 29004 lists: 22900 @@ -108,6 +108,7 @@ pageLoadAssetSize: snapshotRestore: 79032 spaces: 57868 stackAlerts: 29684 + stackConnectors: 36314 synthetics: 40958 telemetry: 51957 telemetryManagementSection: 38586 diff --git a/packages/kbn-securitysolution-exception-list-components/BUILD.bazel b/packages/kbn-securitysolution-exception-list-components/BUILD.bazel new file mode 100644 index 0000000000000..6436793fa5f30 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/BUILD.bazel @@ -0,0 +1,163 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + + +PKG_DIRNAME = "kbn-securitysolution-exception-list-components" +PKG_REQUIRE_NAME = "@kbn/securitysolution-exception-list-components" + +SOURCE_FILES = glob( + [ + "**/*.ts", + "**/*.tsx", + "**/*.svg", + "**/*.d.ts", + ], + exclude = [ + "**/*.config.js", + "**/*.mock.*", + "**/*.test.*", + "**/*.stories.*", + "**/__snapshots__/**", + "**/integration_tests/**", + "**/mocks/**", + "**/scripts/**", + "**/storybook/**", + "**/test_fixtures/**", + "**/test_helpers/**", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", + "jest.config.js" +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ + "@npm//react", + "//packages/kbn-securitysolution-io-ts-list-types", + "//packages/kbn-securitysolution-autocomplete", + "//packages/kbn-ui-theme", + "//packages/kbn-i18n-react", + "//packages/kbn-i18n", + "@npm//@elastic/eui", + "@npm//@emotion/css", + "@npm//@emotion/react", + "@npm//@testing-library/jest-dom", + "@npm//jest", +] + +# In this array place dependencies necessary to build the types, which will include the +# :npm_module_types target of other packages and packages from NPM, including @types/* +# packages. +# +# To reference the types for another package use: +# "//repo/relative/path/to/package:npm_module_types" +# eg. "//packages/kbn-utils:npm_module_types" +# +# References to NPM packages work the same as RUNTIME_DEPS +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "@npm//@types/react", + "//packages/kbn-securitysolution-io-ts-list-types:npm_module_types", + "//packages/kbn-securitysolution-autocomplete:npm_module_types", + "//packages/kbn-ui-theme:npm_module_types", + "//packages/kbn-i18n-react:npm_module_types", + "@npm//@elastic/eui", + "@npm//@emotion/css", + "@npm//@emotion/react", + "@npm//jest", + +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), + additional_args = [ + "--copy-files" + ], +) + +jsts_transpiler( + name = "target_web", + srcs = SRCS, + build_pkg_name = package_name(), + web = True, + additional_args = [ + "--copy-files" + ], +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node", ":target_web"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/kbn-securitysolution-exception-list-components/README.md b/packages/kbn-securitysolution-exception-list-components/README.md new file mode 100644 index 0000000000000..e23b85e409960 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/README.md @@ -0,0 +1,27 @@ +# @kbn/securitysolution-exception-list-components + +This is where the building UI components of the Exception-List live +Most of the components here are imported from `x-pack/plugins/security_solutions/public/detection_engine` + +# Aim + +TODO + +# Pattern used + +``` +component + index.tsx + index.styles.ts <-- to hold styles if the component has many custom styles + use_component.ts <-- for logic if the Presentational Component has logic + index.test.tsx + use_component.test.tsx +``` + +# Next + +- Now the `ExceptionItems, ExceptionItemCard +and ExceptionItemCardMetaInfo + ` receive `securityLinkAnchorComponent, exceptionsUtilityComponent +, and exceptionsUtilityComponent +` as props to avoid moving all the `common` components under the `x-pack` at once, later we should move all building blocks to this `kbn-package` diff --git a/packages/kbn-securitysolution-exception-list-components/index.ts b/packages/kbn-securitysolution-exception-list-components/index.ts new file mode 100644 index 0000000000000..f5001ff35fd33 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export * from './src/search_bar/search_bar'; +export * from './src/empty_viewer_state/empty_viewer_state'; +export * from './src/pagination/pagination'; +// export * from './src/exceptions_utility/exceptions_utility'; +export * from './src/exception_items/exception_items'; +export * from './src/exception_item_card'; +export * from './src/value_with_space_warning'; +export * from './src/types'; diff --git a/packages/kbn-securitysolution-exception-list-components/jest.config.js b/packages/kbn-securitysolution-exception-list-components/jest.config.js new file mode 100644 index 0000000000000..37a11c23c75ba --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/jest.config.js @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../..', + roots: ['/packages/kbn-securitysolution-exception-list-components'], + coverageReporters: ['text', 'html'], + collectCoverageFrom: [ + '/packages/kbn-securitysolution-exception-list-components/**/*.{ts,tsx}', + '!/packages/kbn-securitysolution-exception-list-components/**/*.test', + ], + setupFilesAfterEnv: [ + '/packages/kbn-securitysolution-exception-list-components/setup_test.ts', + ], +}; diff --git a/packages/kbn-securitysolution-exception-list-components/kibana.jsonc b/packages/kbn-securitysolution-exception-list-components/kibana.jsonc new file mode 100644 index 0000000000000..081c50d35af0d --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/kibana.jsonc @@ -0,0 +1,7 @@ +{ + "type": "shared-common", + "id": "@kbn/securitysolution-exception-list-components", + "owner": "@elastic/security-solution-platform", + "runtimeDeps": [], + "typeDeps": [], +} diff --git a/packages/kbn-securitysolution-exception-list-components/package.json b/packages/kbn-securitysolution-exception-list-components/package.json new file mode 100644 index 0000000000000..263863d725c1e --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-exception-list-components", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "browser": "./target_web/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/packages/kbn-securitysolution-exception-list-components/setup_test.ts b/packages/kbn-securitysolution-exception-list-components/setup_test.ts new file mode 100644 index 0000000000000..bb55d97ec9302 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/setup_test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +// eslint-disable-next-line import/no-extraneous-dependencies +import '@testing-library/jest-dom'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg b/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg new file mode 100644 index 0000000000000..b9a0df1630b20 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/plugins/dashboard/public/services/saved_objects/types.ts b/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts similarity index 70% rename from src/plugins/dashboard/public/services/saved_objects/types.ts rename to packages/kbn-securitysolution-exception-list-components/src/custom.d.ts index d7d06131f32cb..9169166fe7af9 100644 --- a/src/plugins/dashboard/public/services/saved_objects/types.ts +++ b/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ -import type { CoreStart } from '@kbn/core/public'; - -export interface DashboardSavedObjectsService { - client: CoreStart['savedObjects']['client']; +declare module '*.svg' { + const content: string; + // eslint-disable-next-line import/no-default-export + export default content; } diff --git a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx new file mode 100644 index 0000000000000..43943e0e8fb97 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; + +import { EmptyViewerState } from './empty_viewer_state'; +import { ListTypeText, ViewerStatus } from '../types'; + +describe('EmptyViewerState', () => { + it('it should render "error" with the default title and body', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('errorViewerState')).toBeTruthy(); + expect(wrapper.getByTestId('errorTitle')).toHaveTextContent('Unable to load exception items'); + expect(wrapper.getByTestId('errorBody')).toHaveTextContent( + 'There was an error loading the exception items. Contact your administrator for help.' + ); + }); + it('it should render "error" when sending the title and body props', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('errorViewerState')).toBeTruthy(); + expect(wrapper.getByTestId('errorTitle')).toHaveTextContent('Error title'); + expect(wrapper.getByTestId('errorBody')).toHaveTextContent('Error body'); + }); + it('it should render loading', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('loadingViewerState')).toBeTruthy(); + }); + it('it should render empty search with the default title and body', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('emptySearchViewerState')).toBeTruthy(); + expect(wrapper.getByTestId('emptySearchTitle')).toHaveTextContent( + 'No results match your search criteria' + ); + expect(wrapper.getByTestId('emptySearchBody')).toHaveTextContent('Try modifying your search'); + }); + it('it should render empty search when sending title and body props', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('emptySearchViewerState')).toBeTruthy(); + expect(wrapper.getByTestId('emptySearchTitle')).toHaveTextContent('Empty search title'); + expect(wrapper.getByTestId('emptySearchBody')).toHaveTextContent('Empty search body'); + }); + it('it should render no items screen when sending title and body props', () => { + const wrapper = render( + + ); + + const { getByTestId } = wrapper; + expect(getByTestId('emptyBody')).toHaveTextContent('There are no endpoint exceptions.'); + expect(getByTestId('emptyStateButton')).toHaveTextContent('Add endpoint exception'); + expect(getByTestId('emptyViewerState')).toBeTruthy(); + }); + it('it should render no items with default title and body props', () => { + const wrapper = render( + + ); + + const { getByTestId } = wrapper; + expect(getByTestId('emptyViewerState')).toBeTruthy(); + expect(getByTestId('emptyTitle')).toHaveTextContent('Add exceptions to this rule'); + expect(getByTestId('emptyBody')).toHaveTextContent( + 'There is no exception in your rule. Create your first rule exception.' + ); + expect(getByTestId('emptyStateButton')).toHaveTextContent('Create rule exception'); + }); + it('it should render no items screen with default title and body props and listType endPoint', () => { + const wrapper = render( + + ); + + const { getByTestId } = wrapper; + expect(getByTestId('emptyViewerState')).toBeTruthy(); + expect(getByTestId('emptyTitle')).toHaveTextContent('Add exceptions to this rule'); + expect(getByTestId('emptyBody')).toHaveTextContent( + 'There is no exception in your rule. Create your first rule exception.' + ); + expect(getByTestId('emptyStateButton')).toHaveTextContent('Create endpoint exception'); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.tsx b/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.tsx new file mode 100644 index 0000000000000..060d2ecc15061 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { useMemo } from 'react'; +import type { FC } from 'react'; +import { css } from '@emotion/react'; +import { + EuiLoadingContent, + EuiImage, + EuiEmptyPrompt, + EuiButton, + useEuiTheme, + EuiPanel, +} from '@elastic/eui'; +import type { ExpressionColor } from '@elastic/eui/src/components/expression/expression'; +import type { EuiFacetGroupLayout } from '@elastic/eui/src/components/facet/facet_group'; +import { euiThemeVars } from '@kbn/ui-theme'; +import { ListTypeText, ViewerStatus } from '../types'; +import * as i18n from '../translations'; +import illustration from '../assets/images/illustration_product_no_results_magnifying_glass.svg'; + +interface EmptyViewerStateProps { + title?: string; + body?: string; + buttonText?: string; + listType?: ListTypeText; + isReadOnly: boolean; + viewerStatus: ViewerStatus; + onCreateExceptionListItem?: () => void | null; +} + +const panelCss = css` + margin: ${euiThemeVars.euiSizeL} 0; + padding: ${euiThemeVars.euiSizeL} 0; +`; +const EmptyViewerStateComponent: FC = ({ + title, + body, + buttonText, + listType, + isReadOnly, + viewerStatus, + onCreateExceptionListItem, +}) => { + const { euiTheme } = useEuiTheme(); + + const euiEmptyPromptProps = useMemo(() => { + switch (viewerStatus) { + case ViewerStatus.ERROR: { + return { + color: 'danger' as ExpressionColor, + iconType: 'alert', + title: ( +

{title || i18n.EMPTY_VIEWER_STATE_ERROR_TITLE}

+ ), + body:

{body || i18n.EMPTY_VIEWER_STATE_ERROR_BODY}

, + 'data-test-subj': 'errorViewerState', + }; + } + case ViewerStatus.EMPTY: + return { + color: 'subdued' as ExpressionColor, + iconType: 'plusInCircle', + iconColor: euiTheme.colors.darkestShade, + title: ( +

{title || i18n.EMPTY_VIEWER_STATE_EMPTY_TITLE}

+ ), + body:

{body || i18n.EMPTY_VIEWER_STATE_EMPTY_BODY}

, + 'data-test-subj': 'emptyViewerState', + actions: [ + + {buttonText || i18n.EMPTY_VIEWER_STATE_EMPTY_VIEWER_BUTTON(listType || 'rule')} + , + ], + }; + case ViewerStatus.EMPTY_SEARCH: + return { + color: 'plain' as ExpressionColor, + layout: 'horizontal' as EuiFacetGroupLayout, + hasBorder: true, + hasShadow: false, + icon: , + title: ( +

+ {title || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE} +

+ ), + body: ( +

+ {body || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY} +

+ ), + 'data-test-subj': 'emptySearchViewerState', + }; + } + }, [ + viewerStatus, + euiTheme.colors.darkestShade, + title, + body, + onCreateExceptionListItem, + isReadOnly, + buttonText, + listType, + ]); + + if (viewerStatus === ViewerStatus.LOADING || viewerStatus === ViewerStatus.SEARCHING) + return ; + + return ( + + + + ); +}; + +export const EmptyViewerState = React.memo(EmptyViewerStateComponent); + +EmptyViewerState.displayName = 'EmptyViewerState'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx new file mode 100644 index 0000000000000..ca08d10f0a049 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo } from 'react'; +import type { EuiCommentProps } from '@elastic/eui'; +import { EuiAccordion, EuiCommentList, EuiFlexItem, EuiPanel, EuiText } from '@elastic/eui'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import * as i18n from '../translations'; + +const accordionCss = css` + color: ${euiThemeVars.euiColorPrimary}; +`; + +export interface ExceptionItemCardCommentsProps { + comments: EuiCommentProps[]; +} + +export const ExceptionItemCardComments = memo(({ comments }) => { + return ( + + + {i18n.exceptionItemCardCommentsAccordion(comments.length)} + + } + arrowDisplay="none" + data-test-subj="exceptionsViewerCommentAccordion" + > + + + + + + ); +}); + +ExceptionItemCardComments.displayName = 'ExceptionItemCardComments'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts new file mode 100644 index 0000000000000..08514a64feac0 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import * as i18n from '../translations'; + +export const OS_LABELS = Object.freeze({ + linux: i18n.OS_LINUX, + mac: i18n.OS_MAC, + macos: i18n.OS_MAC, + windows: i18n.OS_WINDOWS, +}); + +export const OPERATOR_TYPE_LABELS_INCLUDED = Object.freeze({ + [ListOperatorTypeEnum.NESTED]: i18n.CONDITION_OPERATOR_TYPE_NESTED, + [ListOperatorTypeEnum.MATCH_ANY]: i18n.CONDITION_OPERATOR_TYPE_MATCH_ANY, + [ListOperatorTypeEnum.MATCH]: i18n.CONDITION_OPERATOR_TYPE_MATCH, + [ListOperatorTypeEnum.WILDCARD]: i18n.CONDITION_OPERATOR_TYPE_WILDCARD_MATCHES, + [ListOperatorTypeEnum.EXISTS]: i18n.CONDITION_OPERATOR_TYPE_EXISTS, + [ListOperatorTypeEnum.LIST]: i18n.CONDITION_OPERATOR_TYPE_LIST, +}); + +export const OPERATOR_TYPE_LABELS_EXCLUDED = Object.freeze({ + [ListOperatorTypeEnum.MATCH_ANY]: i18n.CONDITION_OPERATOR_TYPE_NOT_MATCH_ANY, + [ListOperatorTypeEnum.MATCH]: i18n.CONDITION_OPERATOR_TYPE_NOT_MATCH, + [ListOperatorTypeEnum.WILDCARD]: i18n.CONDITION_OPERATOR_TYPE_WILDCARD_DOES_NOT_MATCH, + [ListOperatorTypeEnum.EXISTS]: i18n.CONDITION_OPERATOR_TYPE_DOES_NOT_EXIST, + [ListOperatorTypeEnum.LIST]: i18n.CONDITION_OPERATOR_TYPE_NOT_IN_LIST, +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx new file mode 100644 index 0000000000000..3ad2d7ef21fba --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { cx } from '@emotion/css'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; + +// TODO check font Roboto Mono +export const nestedGroupSpaceCss = css` + margin-left: ${euiThemeVars.euiSizeXL}; + margin-bottom: ${euiThemeVars.euiSizeXS}; + padding-top: ${euiThemeVars.euiSizeXS}; +`; + +export const borderCss = cx( + 'eui-xScroll', + ` + border: 1px; + border-color: #d3dae6; + border-style: solid; +` +); + +export const valueContainerCss = css` + display: flex; + align-items: center; + margin-left: ${euiThemeVars.euiSizeS}; +`; +export const expressionContainerCss = css` + display: flex; + align-items: center; +`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx new file mode 100644 index 0000000000000..ae4b76a4a7dc0 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx @@ -0,0 +1,350 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { render } from '@testing-library/react'; +import React from 'react'; + +import { ExceptionItemCardConditions } from './conditions'; + +interface TestEntry { + field: string; + operator: 'included' | 'excluded'; + type: unknown; + value?: string | string[]; + entries?: TestEntry[]; + list?: { id: string; type: string }; +} +const getEntryKey = ( + entry: TestEntry, + index: string, + list?: { id: string; type: string } | null +) => { + if (list && Object.keys(list)) { + const { field, type, list: entryList } = entry; + const { id } = entryList || {}; + return `${field}${type}${id || ''}${index}`; + } + const { field, type, value } = entry; + return `${field}${type}${value || ''}${index}`; +}; + +describe('ExceptionItemCardConditions', () => { + beforeEach(() => { + jest.clearAllMocks(); + jest.resetAllMocks(); + }); + it('it includes os condition if one exists', () => { + const entries: TestEntry[] = [ + { + field: 'host.name', + operator: 'included', + type: 'match', + value: 'host', + }, + { + field: 'threat.indicator.port', + operator: 'included', + type: 'exists', + }, + { + entries: [ + { + field: 'valid', + operator: 'included', + type: 'match', + value: 'true', + }, + ], + field: 'file.Ext.code_signature', + type: 'nested', + operator: 'included', + }, + ]; + const wrapper = render( + + ); + expect(wrapper.getByTestId('exceptionItemConditionsOs')).toHaveTextContent('OSIS Linux'); + + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[0], '0')}EntryContent`) + ).toHaveTextContent('host.nameIS host'); + + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[1], '1')}EntryContent`) + ).toHaveTextContent('AND threat.indicator.portexists'); + + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[2], '2')}EntryContent`) + ).toHaveTextContent('AND file.Ext.code_signature'); + + if (entries[2] && entries[2].entries) { + expect( + wrapper.getByTestId( + `exceptionItemConditions${getEntryKey(entries[2].entries[0], '0')}EntryContent` + ) + ).toHaveTextContent('validIS true'); + } + }); + + it('it renders item conditions', () => { + const entries: TestEntry[] = [ + { + field: 'host.name', + operator: 'included', + type: 'match', + value: 'host', + }, + { + field: 'host.name', + operator: 'excluded', + type: 'match', + value: 'host', + }, + { + field: 'host.name', + operator: 'included', + type: 'match_any', + value: ['foo', 'bar'], + }, + { + field: 'host.name', + operator: 'excluded', + type: 'match_any', + value: ['foo', 'bar'], + }, + { + field: 'user.name', + operator: 'included', + type: 'wildcard', + value: 'foo*', + }, + { + field: 'user.name', + operator: 'excluded', + type: 'wildcard', + value: 'foo*', + }, + { + field: 'threat.indicator.port', + operator: 'included', + type: 'exists', + }, + { + field: 'threat.indicator.port', + operator: 'excluded', + type: 'exists', + }, + { + entries: [ + { + field: 'valid', + operator: 'included', + type: 'match', + value: 'true', + }, + ], + field: 'file.Ext.code_signature', + type: 'nested', + operator: 'included', + }, + ]; + const wrapper = render( + + ); + expect(wrapper.queryByTestId('exceptionItemConditionsOs')).not.toBeInTheDocument(); + + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[0], '0')}EntryContent`) + ).toHaveTextContent('host.nameIS host'); + // Match; + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[1], '1')}EntryContent`) + ).toHaveTextContent('AND host.nameIS NOT host'); + // MATCH_ANY; + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[2], '2')}EntryContent`) + ).toHaveTextContent('AND host.nameis one of foobar'); + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[3], '3')}EntryContent`) + ).toHaveTextContent('AND host.nameis not one of foobar'); + // WILDCARD; + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[4], '4')}EntryContent`) + ).toHaveTextContent('AND user.nameMATCHES foo*'); + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[5], '5')}EntryContent`) + ).toHaveTextContent('AND user.nameDOES NOT MATCH foo*'); + // EXISTS; + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[6], '6')}EntryContent`) + ).toHaveTextContent('AND threat.indicator.portexists'); + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[7], '7')}EntryContent`) + ).toHaveTextContent('AND threat.indicator.portdoes not exist'); + // NESTED; + expect( + wrapper.getByTestId(`exceptionItemConditions${getEntryKey(entries[8], '8')}EntryContent`) + ).toHaveTextContent('AND file.Ext.code_signature'); + if (entries[8] && entries[8].entries) { + expect( + wrapper.getByTestId( + `exceptionItemConditions${getEntryKey(entries[8].entries[0], '0')}EntryContent` + ) + ).toHaveTextContent('validIS true'); + } + }); + it('it renders list conditions', () => { + const entries: TestEntry[] = [ + { + field: 'host.name', + list: { + id: 'ips.txt', + type: 'keyword', + }, + operator: 'included', + type: 'list', + }, + { + field: 'host.name', + list: { + id: 'ips.txt', + type: 'keyword', + }, + operator: 'excluded', + type: 'list', + }, + ]; + const wrapper = render( + + ); + // /exceptionItemConditionshost.namelist0EntryContent + expect( + wrapper.getByTestId( + `exceptionItemConditions${getEntryKey(entries[0], '0', entries[0].list)}EntryContent` + ) + ).toHaveTextContent('host.nameincluded in ips.txt'); + + expect( + wrapper.getByTestId( + `exceptionItemConditions${getEntryKey(entries[1], '1', entries[1].list)}EntryContent` + ) + ).toHaveTextContent('AND host.nameis not included in ips.txt'); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.tsx new file mode 100644 index 0000000000000..8b85a7343afc1 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.tsx @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo } from 'react'; +import { EuiPanel } from '@elastic/eui'; + +import { borderCss } from './conditions.styles'; +import { EntryContent } from './entry_content/entry_content'; +import { OsCondition } from './os_conditions/os_conditions'; +import type { CriteriaConditionsProps, Entry } from './types'; + +export const ExceptionItemCardConditions = memo( + ({ os, entries, dataTestSubj }) => { + return ( + + {os?.length ? : null} + {entries.map((entry: Entry, index: number) => { + const nestedEntries = 'entries' in entry ? entry.entries : []; + return ( +
+ + {nestedEntries?.length + ? nestedEntries.map((nestedEntry: Entry, nestedIndex: number) => ( + + )) + : null} +
+ ); + })} +
+ ); + } +); +ExceptionItemCardConditions.displayName = 'ExceptionItemCardConditions'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx new file mode 100644 index 0000000000000..6a64bcc810c08 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { EuiExpression, EuiBadge } from '@elastic/eui'; +import type { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { ValueWithSpaceWarning } from '../../../..'; +import { OPERATOR_TYPE_LABELS_EXCLUDED, OPERATOR_TYPE_LABELS_INCLUDED } from '../conditions.config'; +import type { Entry } from '../types'; + +const getEntryValue = (type: string, value?: string | string[]) => { + if (type === 'match_any' && Array.isArray(value)) { + return value.map((currentValue) => {currentValue}); + } + return value ?? ''; +}; + +export const getEntryOperator = (type: ListOperatorTypeEnum, operator: string) => { + if (type === 'nested') return ''; + return operator === 'included' + ? OPERATOR_TYPE_LABELS_INCLUDED[type] ?? type + : OPERATOR_TYPE_LABELS_EXCLUDED[type] ?? type; +}; + +export const getValue = (entry: Entry) => { + if (entry.type === 'list') return entry.list.id; + + return 'value' in entry ? entry.value : ''; +}; + +export const getValueExpression = ( + type: ListOperatorTypeEnum, + operator: string, + value: string | string[] +) => ( + <> + + + +); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.tsx new file mode 100644 index 0000000000000..6c321a6d0ce04 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.tsx @@ -0,0 +1,71 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo } from 'react'; +import { EuiExpression, EuiToken, EuiFlexGroup } from '@elastic/eui'; +import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { + nestedGroupSpaceCss, + valueContainerCss, + expressionContainerCss, +} from '../conditions.styles'; +import type { Entry } from '../types'; +import * as i18n from '../../translations'; +import { getValue, getValueExpression } from './entry_content.helper'; + +export const EntryContent = memo( + ({ + entry, + index, + isNestedEntry = false, + dataTestSubj, + }: { + entry: Entry; + index: number; + isNestedEntry?: boolean; + dataTestSubj?: string; + }) => { + const { field, type } = entry; + const value = getValue(entry); + const operator = 'operator' in entry ? entry.operator : ''; + + const entryKey = `${field}${type}${value}${index}`; + return ( +
+
+ {isNestedEntry ? ( + + + +
+ + {getValueExpression(type as ListOperatorTypeEnum, operator, value)} +
+
+ ) : ( + <> + + + {getValueExpression(type as ListOperatorTypeEnum, operator, value)} + + )} +
+
+ ); + } +); +EntryContent.displayName = 'EntryContent'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.tsx new file mode 100644 index 0000000000000..701529ae6717d --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo, useMemo } from 'react'; +import { EuiExpression } from '@elastic/eui'; + +import { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { OS_LABELS } from '../conditions.config'; +import * as i18n from '../../translations'; + +export interface OsConditionsProps { + dataTestSubj: string; + os: ExceptionListItemSchema['os_types']; +} + +export const OsCondition = memo(({ os, dataTestSubj }) => { + const osLabel = useMemo(() => { + return os.map((osValue) => OS_LABELS[osValue] ?? osValue).join(', '); + }, [os]); + return osLabel ? ( +
+ + + + +
+ ) : null; +}); +OsCondition.displayName = 'OsCondition'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts new file mode 100644 index 0000000000000..09067e84cafc7 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { + EntryExists, + EntryList, + EntryMatch, + EntryMatchAny, + EntryMatchWildcard, + EntryNested, + ExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; + +export type Entry = + | EntryExists + | EntryList + | EntryMatch + | EntryMatchAny + | EntryMatchWildcard + | EntryNested; + +export type Entries = ExceptionListItemSchema['entries']; +export interface CriteriaConditionsProps { + entries: Entries; + dataTestSubj: string; + os?: ExceptionListItemSchema['os_types']; +} diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx new file mode 100644 index 0000000000000..c3705750d015d --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { useMemo, useCallback, FC } from 'react'; +import { EuiPanel, EuiFlexGroup, EuiFlexItem, EuiCommentProps } from '@elastic/eui'; +import type { + CommentsArray, + ExceptionListItemSchema, + ExceptionListTypeEnum, +} from '@kbn/securitysolution-io-ts-list-types'; + +import * as i18n from './translations'; +import { + ExceptionItemCardHeader, + ExceptionItemCardConditions, + ExceptionItemCardMetaInfo, + ExceptionItemCardComments, +} from '.'; + +import type { ExceptionListItemIdentifiers } from '../types'; + +export interface ExceptionItemProps { + dataTestSubj?: string; + disableActions?: boolean; + exceptionItem: ExceptionListItemSchema; + listType: ExceptionListTypeEnum; + ruleReferences: any[]; // rulereferences + editActionLabel?: string; + deleteActionLabel?: string; + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + formattedDateComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + getFormattedComments: (comments: CommentsArray) => EuiCommentProps[]; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + onDeleteException: (arg: ExceptionListItemIdentifiers) => void; + onEditException: (item: ExceptionListItemSchema) => void; +} + +const ExceptionItemCardComponent: FC = ({ + disableActions = false, + exceptionItem, + listType, + ruleReferences, + dataTestSubj, + editActionLabel, + deleteActionLabel, + securityLinkAnchorComponent, + formattedDateComponent, + getFormattedComments, + onDeleteException, + onEditException, +}) => { + const handleDelete = useCallback((): void => { + onDeleteException({ + id: exceptionItem.id, + name: exceptionItem.name, + namespaceType: exceptionItem.namespace_type, + }); + }, [onDeleteException, exceptionItem.id, exceptionItem.name, exceptionItem.namespace_type]); + + const handleEdit = useCallback((): void => { + onEditException(exceptionItem); + }, [onEditException, exceptionItem]); + + const formattedComments = useMemo((): EuiCommentProps[] => { + return getFormattedComments(exceptionItem.comments); + }, [exceptionItem.comments, getFormattedComments]); + + const actions: Array<{ + key: string; + icon: string; + label: string | boolean; + onClick: () => void; + }> = useMemo( + () => [ + { + key: 'edit', + icon: 'controlsHorizontal', + label: editActionLabel || i18n.exceptionItemCardEditButton(listType), + onClick: handleEdit, + }, + { + key: 'delete', + icon: 'trash', + label: deleteActionLabel || listType === i18n.exceptionItemCardDeleteButton(listType), + onClick: handleDelete, + }, + ], + [editActionLabel, listType, deleteActionLabel, handleDelete, handleEdit] + ); + return ( + + + + + + + + + + + + {formattedComments.length > 0 && ( + + )} + + + ); +}; + +ExceptionItemCardComponent.displayName = 'ExceptionItemCardComponent'; + +export const ExceptionItemCard = React.memo(ExceptionItemCardComponent); + +ExceptionItemCard.displayName = 'ExceptionItemCard'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx new file mode 100644 index 0000000000000..78feab598c145 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx @@ -0,0 +1,76 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { getExceptionListItemSchemaMock } from '@kbn/lists-plugin/common/schemas/response/exception_list_item_schema.mock'; + +import * as i18n from '../translations'; +import { ExceptionItemCardHeader } from './header'; +import { fireEvent, render } from '@testing-library/react'; +import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +const handleEdit = jest.fn(); +const handleDelete = jest.fn(); +const actions = [ + { + key: 'edit', + icon: 'pencil', + label: i18n.exceptionItemCardEditButton(ExceptionListTypeEnum.DETECTION), + onClick: handleEdit, + }, + { + key: 'delete', + icon: 'trash', + label: i18n.exceptionItemCardDeleteButton(ExceptionListTypeEnum.DETECTION), + onClick: handleDelete, + }, +]; +describe('ExceptionItemCardHeader', () => { + it('it renders item name', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('exceptionItemHeaderTitle')).toHaveTextContent('some name'); + }); + + it('it displays actions', () => { + const wrapper = render( + + ); + + // click on popover + fireEvent.click(wrapper.getByTestId('exceptionItemHeaderActionButton')); + fireEvent.click(wrapper.getByTestId('exceptionItemHeaderActionItemedit')); + expect(handleEdit).toHaveBeenCalled(); + + fireEvent.click(wrapper.getByTestId('exceptionItemHeaderActionItemdelete')); + expect(handleDelete).toHaveBeenCalled(); + }); + + it('it disables actions if disableActions is true', () => { + const wrapper = render( + + ); + + expect(wrapper.getByTestId('exceptionItemHeaderActionButton')).toBeDisabled(); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx new file mode 100644 index 0000000000000..d58cb8d99b7a1 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.tsx @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo, useMemo, useState } from 'react'; +import type { EuiContextMenuPanelProps } from '@elastic/eui'; +import { + EuiButtonIcon, + EuiContextMenuPanel, + EuiFlexGroup, + EuiFlexItem, + EuiPopover, + EuiTitle, + EuiContextMenuItem, +} from '@elastic/eui'; +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +export interface ExceptionItemCardHeaderProps { + item: ExceptionListItemSchema; + actions: Array<{ key: string; icon: string; label: string | boolean; onClick: () => void }>; + disableActions?: boolean; + dataTestSubj: string; +} + +export const ExceptionItemCardHeader = memo( + ({ item, actions, disableActions = false, dataTestSubj }) => { + const [isPopoverOpen, setIsPopoverOpen] = useState(false); + + const onItemActionsClick = () => setIsPopoverOpen((isOpen) => !isOpen); + const onClosePopover = () => setIsPopoverOpen(false); + + const itemActions = useMemo((): EuiContextMenuPanelProps['items'] => { + return actions.map((action) => ( + { + onClosePopover(); + action.onClick(); + }} + > + {action.label} + + )); + }, [dataTestSubj, actions]); + + return ( + + + +

{item.name}

+
+
+ + + } + panelPaddingSize="none" + isOpen={isPopoverOpen} + closePopover={onClosePopover} + data-test-subj={`${dataTestSubj}Items`} + > + + + +
+ ); + } +); + +ExceptionItemCardHeader.displayName = 'ExceptionItemCardHeader'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.test.tsx new file mode 100644 index 0000000000000..e97b03607bb6a --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { fireEvent, render } from '@testing-library/react'; + +import { ExceptionItemCard } from '.'; +import { getExceptionListItemSchemaMock } from '@kbn/lists-plugin/common/schemas/response/exception_list_item_schema.mock'; +import { getCommentsArrayMock } from '@kbn/lists-plugin/common/schemas/types/comment.mock'; +import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +const ruleReferences: unknown[] = [ + { + exception_lists: [ + { + id: '123', + list_id: 'i_exist', + namespace_type: 'single', + type: 'detection', + }, + { + id: '456', + list_id: 'i_exist_2', + namespace_type: 'single', + type: 'detection', + }, + ], + id: '1a2b3c', + name: 'Simple Rule Query', + rule_id: 'rule-2', + }, +]; +describe('ExceptionItemCard', () => { + it('it renders header, item meta information and conditions', () => { + const exceptionItem = { ...getExceptionListItemSchemaMock(), comments: [] }; + + const wrapper = render( + null} + formattedDateComponent={() => null} + getFormattedComments={() => []} + /> + ); + + expect(wrapper.getByTestId('exceptionItemCardHeaderContainer')).toBeInTheDocument(); + // expect(wrapper.getByTestId('exceptionItemCardMetaInfo')).toBeInTheDocument(); + expect(wrapper.getByTestId('exceptionItemCardConditions')).toBeInTheDocument(); + // expect(wrapper.queryByTestId('exceptionsViewerCommentAccordion')).not.toBeInTheDocument(); + }); + + it('it renders header, item meta information, conditions, and comments if any exist', () => { + const exceptionItem = { ...getExceptionListItemSchemaMock(), comments: getCommentsArrayMock() }; + + const wrapper = render( + null} + formattedDateComponent={() => null} + getFormattedComments={() => []} + /> + ); + + expect(wrapper.getByTestId('exceptionItemCardHeaderContainer')).toBeInTheDocument(); + // expect(wrapper.getByTestId('exceptionItemCardMetaInfo')).toBeInTheDocument(); + expect(wrapper.getByTestId('exceptionItemCardConditions')).toBeInTheDocument(); + // expect(wrapper.getByTestId('exceptionsViewerCommentAccordion')).toBeInTheDocument(); + }); + + it('it does not render edit or delete action buttons when "disableActions" is "true"', () => { + const exceptionItem = getExceptionListItemSchemaMock(); + + const wrapper = render( + null} + formattedDateComponent={() => null} + getFormattedComments={() => []} + /> + ); + expect(wrapper.queryByTestId('itemActionButton')).not.toBeInTheDocument(); + }); + + it('it invokes "onEditException" when edit button clicked', () => { + const mockOnEditException = jest.fn(); + const exceptionItem = getExceptionListItemSchemaMock(); + + const wrapper = render( + null} + formattedDateComponent={() => null} + getFormattedComments={() => []} + /> + ); + + fireEvent.click(wrapper.getByTestId('exceptionItemCardHeaderActionButton')); + fireEvent.click(wrapper.getByTestId('exceptionItemCardHeaderActionItemedit')); + expect(mockOnEditException).toHaveBeenCalledWith(getExceptionListItemSchemaMock()); + }); + + it('it invokes "onDeleteException" when delete button clicked', () => { + const mockOnDeleteException = jest.fn(); + const exceptionItem = getExceptionListItemSchemaMock(); + + const wrapper = render( + null} + formattedDateComponent={() => null} + getFormattedComments={() => []} + /> + ); + fireEvent.click(wrapper.getByTestId('exceptionItemCardHeaderActionButton')); + fireEvent.click(wrapper.getByTestId('exceptionItemCardHeaderActionItemdelete')); + + expect(mockOnDeleteException).toHaveBeenCalledWith({ + id: '1', + name: 'some name', + namespaceType: 'single', + }); + }); + + // TODO Fix this Test + // it('it renders comment accordion closed to begin with', () => { + // const exceptionItem = getExceptionListItemSchemaMock(); + // exceptionItem.comments = getCommentsArrayMock(); + // const wrapper = render( + // + // ); + + // expect(wrapper.queryByTestId('accordion-comment-list')).not.toBeVisible(); + // }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts new file mode 100644 index 0000000000000..c0fd3fafc86d5 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export * from './conditions/conditions'; +export * from './header/header'; +export * from './meta/meta'; +export * from './comments/comments'; +export * from './exception_item_card'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.tsx new file mode 100644 index 0000000000000..3d075f50096d0 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.tsx @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo } from 'react'; +import { EuiBadge, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import * as i18n from '../../translations'; + +interface MetaInfoDetailsProps { + fieldName: string; + label: string; + lastUpdate: JSX.Element | string; + lastUpdateValue: string; + dataTestSubj: string; +} + +const euiBadgeFontFamily = css` + font-family: ${euiThemeVars.euiFontFamily}; +`; +export const MetaInfoDetails = memo( + ({ label, lastUpdate, lastUpdateValue, dataTestSubj }) => { + return ( + + + + {label} + + + + + {lastUpdate} + + + + + {i18n.EXCEPTION_ITEM_CARD_META_BY} + + + + + + + {lastUpdateValue} + + + + + + ); + } +); + +MetaInfoDetails.displayName = 'MetaInfoDetails'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx new file mode 100644 index 0000000000000..14bdef771d6b3 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx @@ -0,0 +1,155 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { getExceptionListItemSchemaMock } from '@kbn/lists-plugin/common/schemas/response/exception_list_item_schema.mock'; + +import { ExceptionItemCardMetaInfo } from './meta'; +import { RuleReference } from '../../types'; + +const ruleReferences = [ + { + exception_lists: [ + { + id: '123', + list_id: 'i_exist', + namespace_type: 'single', + type: 'detection', + }, + { + id: '456', + list_id: 'i_exist_2', + namespace_type: 'single', + type: 'detection', + }, + ], + id: '1a2b3c', + name: 'Simple Rule Query', + rule_id: 'rule-2', + }, +]; +describe('ExceptionItemCardMetaInfo', () => { + it('it should render creation info with sending custom formattedDateComponent', () => { + const wrapper = render( + null} + formattedDateComponent={({ fieldName, value }) => ( + <> +

{new Date(value).toDateString()}

+ + )} + /> + ); + + expect(wrapper.getByTestId('exceptionItemMetaCreatedBylastUpdate')).toHaveTextContent( + 'Mon Apr 20 2020' + ); + expect(wrapper.getByTestId('exceptionItemMetaCreatedBylastUpdateValue')).toHaveTextContent( + 'some user' + ); + }); + + it('it should render udate info with sending custom formattedDateComponent', () => { + const wrapper = render( + null} + formattedDateComponent={({ fieldName, value }) => ( + <> +

{new Date(value).toDateString()}

+ + )} + /> + ); + expect(wrapper.getByTestId('exceptionItemMetaUpdatedBylastUpdate')).toHaveTextContent( + 'Mon Apr 20 2020' + ); + expect(wrapper.getByTestId('exceptionItemMetaUpdatedBylastUpdateValue')).toHaveTextContent( + 'some user' + ); + }); + + it('it should render references info', () => { + const wrapper = render( + null} + formattedDateComponent={() => null} + /> + ); + + expect(wrapper.getByTestId('exceptionItemMetaAffectedRulesButton')).toHaveTextContent( + 'Affects 1 rule' + ); + }); + + it('it renders references info when multiple references exist', () => { + const wrapper = render( + null} + formattedDateComponent={() => null} + /> + ); + + expect(wrapper.getByTestId('exceptionItemMetaAffectedRulesButton')).toHaveTextContent( + 'Affects 2 rules' + ); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx new file mode 100644 index 0000000000000..91e0a9cdd19b8 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.tsx @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { memo, useMemo, useState } from 'react'; +import type { EuiContextMenuPanelProps } from '@elastic/eui'; +import { + EuiContextMenuItem, + EuiContextMenuPanel, + EuiFlexGroup, + EuiFlexItem, + EuiToolTip, + EuiButtonEmpty, + EuiPopover, +} from '@elastic/eui'; +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { css } from '@emotion/react'; +import * as i18n from '../translations'; +import type { RuleReference } from '../../types'; +import { MetaInfoDetails } from './details_info/details_info'; + +const itemCss = css` + border-right: 1px solid #d3dae6; + padding: 4px 12px 4px 0; +`; + +export interface ExceptionItemCardMetaInfoProps { + item: ExceptionListItemSchema; + references: RuleReference[]; + dataTestSubj: string; + formattedDateComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common +} + +export const ExceptionItemCardMetaInfo = memo( + ({ item, references, dataTestSubj, securityLinkAnchorComponent, formattedDateComponent }) => { + const [isPopoverOpen, setIsPopoverOpen] = useState(false); + + const onAffectedRulesClick = () => setIsPopoverOpen((isOpen) => !isOpen); + const onClosePopover = () => setIsPopoverOpen(false); + + const FormattedDateComponent = formattedDateComponent; + const itemActions = useMemo((): EuiContextMenuPanelProps['items'] => { + if (references == null || securityLinkAnchorComponent === null) { + return []; + } + + const SecurityLinkAnchor = securityLinkAnchorComponent; + return references.map((reference) => ( + + + + + + )); + }, [references, securityLinkAnchorComponent, dataTestSubj]); + + return ( + + {FormattedDateComponent !== null && ( + <> + + + } + lastUpdateValue={item.created_by} + dataTestSubj={`${dataTestSubj}CreatedBy`} + /> + + + + + } + lastUpdateValue={item.updated_by} + dataTestSubj={`${dataTestSubj}UpdatedBy`} + /> + + + )} + + + {i18n.AFFECTED_RULES(references.length)} + + } + panelPaddingSize="none" + isOpen={isPopoverOpen} + closePopover={onClosePopover} + data-test-subj={`${dataTestSubj}Items`} + > + + + + + ); + } +); +ExceptionItemCardMetaInfo.displayName = 'ExceptionItemCardMetaInfo'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts new file mode 100644 index 0000000000000..2fa7524291025 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts @@ -0,0 +1,166 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; + +export const exceptionItemCardEditButton = (listType: string) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.editItemButton', { + values: { listType }, + defaultMessage: 'Edit {listType} exception', + }); + +export const exceptionItemCardDeleteButton = (listType: string) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.deleteItemButton', { + values: { listType }, + defaultMessage: 'Delete {listType} exception', + }); + +export const EXCEPTION_ITEM_CARD_CREATED_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.createdLabel', + { + defaultMessage: 'Created', + } +); + +export const EXCEPTION_ITEM_CARD_UPDATED_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.updatedLabel', + { + defaultMessage: 'Updated', + } +); + +export const EXCEPTION_ITEM_CARD_META_BY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.metaDetailsBy', + { + defaultMessage: 'by', + } +); + +export const exceptionItemCardCommentsAccordion = (comments: number) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.showCommentsLabel', { + values: { comments }, + defaultMessage: 'Show {comments, plural, =1 {comment} other {comments}} ({comments})', + }); + +export const CONDITION_OPERATOR_TYPE_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator', + { + defaultMessage: 'IS', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator.not', + { + defaultMessage: 'IS NOT', + } +); + +export const CONDITION_OPERATOR_TYPE_WILDCARD_MATCHES = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardMatchesOperator', + { + defaultMessage: 'MATCHES', + } +); + +export const CONDITION_OPERATOR_TYPE_WILDCARD_DOES_NOT_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardDoesNotMatchOperator', + { + defaultMessage: 'DOES NOT MATCH', + } +); + +export const CONDITION_OPERATOR_TYPE_NESTED = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.nestedOperator', + { + defaultMessage: 'has', + } +); + +export const CONDITION_OPERATOR_TYPE_MATCH_ANY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator', + { + defaultMessage: 'is one of', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_MATCH_ANY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator.not', + { + defaultMessage: 'is not one of', + } +); + +export const CONDITION_OPERATOR_TYPE_EXISTS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator', + { + defaultMessage: 'exists', + } +); + +export const CONDITION_OPERATOR_TYPE_DOES_NOT_EXIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator.not', + { + defaultMessage: 'does not exist', + } +); + +export const CONDITION_OPERATOR_TYPE_LIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator', + { + defaultMessage: 'included in', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_IN_LIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator.not', + { + defaultMessage: 'is not included in', + } +); + +export const CONDITION_AND = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.and', + { + defaultMessage: 'AND', + } +); + +export const CONDITION_OS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.os', + { + defaultMessage: 'OS', + } +); + +export const OS_WINDOWS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.windows', + { + defaultMessage: 'Windows', + } +); + +export const OS_LINUX = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.linux', + { + defaultMessage: 'Linux', + } +); + +export const OS_MAC = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.macos', + { + defaultMessage: 'Mac', + } +); + +export const AFFECTED_RULES = (numRules: number) => + i18n.translate('exceptionList-components.exceptions.card.exceptionItem.affectedRules', { + values: { numRules }, + defaultMessage: 'Affects {numRules} {numRules, plural, =1 {rule} other {rules}}', + }); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx new file mode 100644 index 0000000000000..3fe2d7eb6d0b3 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; + +import { getExceptionListItemSchemaMock } from '@kbn/lists-plugin/common/schemas/response/exception_list_item_schema.mock'; +import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +import { ExceptionItems } from './exception_items'; + +import { ViewerStatus } from '../types'; +import { render } from '@testing-library/react'; + +const onCreateExceptionListItem = jest.fn(); +const onDeleteException = jest.fn(); +const onEditExceptionItem = jest.fn(); +const onPaginationChange = jest.fn(); + +const pagination = { pageIndex: 0, pageSize: 0, totalItemCount: 0 }; + +describe('ExceptionsViewerItems', () => { + describe('Viewing EmptyViewerState', () => { + it('it renders empty prompt if "viewerStatus" is "empty"', () => { + const wrapper = render( + null} + formattedDateComponent={() => null} + exceptionsUtilityComponent={() => null} + getFormattedComments={() => []} + /> + ); + // expect(wrapper).toMatchSnapshot(); + expect(wrapper.getByTestId('emptyViewerState')).toBeInTheDocument(); + expect(wrapper.queryByTestId('exceptionsContainer')).not.toBeInTheDocument(); + }); + + it('it renders no search results found prompt if "viewerStatus" is "empty_search"', () => { + const wrapper = render( + null} + formattedDateComponent={() => null} + exceptionsUtilityComponent={() => null} + getFormattedComments={() => []} + /> + ); + // expect(wrapper).toMatchSnapshot(); + expect(wrapper.getByTestId('emptySearchViewerState')).toBeInTheDocument(); + expect(wrapper.queryByTestId('exceptionsContainer')).not.toBeInTheDocument(); + }); + + it('it renders exceptions if "viewerStatus" and "null"', () => { + const wrapper = render( + null} + formattedDateComponent={() => null} + exceptionsUtilityComponent={() => null} + getFormattedComments={() => []} + /> + ); + // expect(wrapper).toMatchSnapshot(); + expect(wrapper.getByTestId('exceptionsContainer')).toBeTruthy(); + }); + }); + // TODO Add Exception Items and Pagination interactions +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.tsx new file mode 100644 index 0000000000000..80ab3d99f6eb8 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.tsx @@ -0,0 +1,139 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { css } from '@emotion/react'; +import type { FC } from 'react'; +import { EuiCommentProps, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; + +import type { Pagination as PaginationType } from '@elastic/eui'; + +import type { + CommentsArray, + ExceptionListItemSchema, + ExceptionListTypeEnum, +} from '@kbn/securitysolution-io-ts-list-types'; + +import { euiThemeVars } from '@kbn/ui-theme'; +import { EmptyViewerState, ExceptionItemCard, Pagination } from '../..'; + +import type { + RuleReferences, + ExceptionListItemIdentifiers, + ViewerStatus, + GetExceptionItemProps, +} from '../types'; + +const exceptionItemCss = css` + margin: ${euiThemeVars.euiSize} 0; + &div:first-child { + margin: ${euiThemeVars.euiSizeXS} 0 ${euiThemeVars.euiSize}; + } +`; + +interface ExceptionItemsProps { + lastUpdated: string | number | null; + viewerStatus: ViewerStatus; + isReadOnly: boolean; + emptyViewerTitle?: string; + emptyViewerBody?: string; + emptyViewerButtonText?: string; + exceptions: ExceptionListItemSchema[]; + listType: ExceptionListTypeEnum; + ruleReferences: RuleReferences; + pagination: PaginationType; + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + formattedDateComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + exceptionsUtilityComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + getFormattedComments: (comments: CommentsArray) => EuiCommentProps[]; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + onCreateExceptionListItem?: () => void; + onDeleteException: (arg: ExceptionListItemIdentifiers) => void; + onEditExceptionItem: (item: ExceptionListItemSchema) => void; + onPaginationChange: (arg: GetExceptionItemProps) => void; +} + +const ExceptionItemsComponent: FC = ({ + lastUpdated, + viewerStatus, + isReadOnly, + exceptions, + listType, + ruleReferences, + emptyViewerTitle, + emptyViewerBody, + emptyViewerButtonText, + pagination, + securityLinkAnchorComponent, + exceptionsUtilityComponent, + formattedDateComponent, + getFormattedComments, + onPaginationChange, + onDeleteException, + onEditExceptionItem, + onCreateExceptionListItem, +}) => { + const ExceptionsUtility = exceptionsUtilityComponent; + if (!exceptions.length || viewerStatus) + return ( + + ); + return ( + <> + + + + + {exceptions.map((exception) => ( + + + + ))} + + + + + + ); +}; + +ExceptionItemsComponent.displayName = 'ExceptionItemsComponent'; + +export const ExceptionItems = React.memo(ExceptionItemsComponent); + +ExceptionItems.displayName = 'ExceptionsItems'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx new file mode 100644 index 0000000000000..4d97f198aa2b9 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { fireEvent, render } from '@testing-library/react'; +import React from 'react'; + +import { Pagination } from './pagination'; + +describe('Pagination', () => { + it('it invokes "onPaginationChange" when per page item is clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = render( + + ); + + fireEvent.click(wrapper.getByTestId('tablePaginationPopoverButton')); + fireEvent.click(wrapper.getByTestId('tablePagination-50-rows')); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + pagination: { pageIndex: 0, pageSize: 50, totalItemCount: 1 }, + }); + }); + + it('it invokes "onPaginationChange" when next clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = render( + + ); + + fireEvent.click(wrapper.getByTestId('pagination-button-next')); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + pagination: { pageIndex: 1, pageSize: 5, totalItemCount: 160 }, + }); + }); + + it('it invokes "onPaginationChange" when page clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = render( + + ); + + fireEvent.click(wrapper.getByTestId('pagination-button-2')); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + pagination: { pageIndex: 2, pageSize: 50, totalItemCount: 160 }, + }); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx b/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx new file mode 100644 index 0000000000000..30b029480e173 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import type { FC } from 'react'; +import { EuiTablePagination } from '@elastic/eui'; + +import type { PaginationProps } from '../types'; +import { usePagination } from './use_pagination'; + +const PaginationComponent: FC = ({ + dataTestSubj, + ariaLabel, + pagination, + onPaginationChange, +}) => { + const { + pageIndex, + pageCount, + pageSize, + pageSizeOptions, + + handleItemsPerPageChange, + handlePageIndexChange, + } = usePagination({ pagination, onPaginationChange }); + + return ( + + ); +}; + +PaginationComponent.displayName = 'PaginationComponent'; + +export const Pagination = React.memo(PaginationComponent); + +Pagination.displayName = 'Pagination'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts b/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts new file mode 100644 index 0000000000000..d190c88f10617 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { act, renderHook } from '@testing-library/react-hooks'; +import { usePagination } from './use_pagination'; + +const onPaginationChange = jest.fn(); + +describe('usePagination', () => { + test('should return the correct EuiTablePagination props when all the pagination object properties are falsy', () => { + const pagination = { pageIndex: 0, pageSize: 0, totalItemCount: 0 }; + + const { result } = renderHook(() => usePagination({ pagination, onPaginationChange })); + const { pageCount, pageIndex, pageSize, pageSizeOptions } = result.current; + expect(pageCount).toEqual(0); + expect(pageIndex).toEqual(0); + expect(pageSize).toEqual(0); + expect(pageSizeOptions).toEqual(undefined); + }); + test('should return the correct pageCount when pagination properties are invalid', () => { + const pagination = { pageIndex: 0, pageSize: 10, totalItemCount: 0 }; + + const { result } = renderHook(() => usePagination({ pagination, onPaginationChange })); + const { pageCount } = result.current; + expect(pageCount).toEqual(0); + }); + test('should return the correct EuiTablePagination props when all the pagination object properties are turthy', () => { + const pagination = { pageIndex: 0, pageSize: 10, totalItemCount: 100 }; + + const { result } = renderHook(() => usePagination({ pagination, onPaginationChange })); + const { pageCount, pageIndex, pageSize } = result.current; + expect(pageCount).toEqual(10); + expect(pageIndex).toEqual(0); + expect(pageSize).toEqual(10); + }); + test('should call onPaginationChange with correct pageIndex when the Page changes', () => { + const pagination = { pageIndex: 0, pageSize: 10, totalItemCount: 100 }; + + const { result } = renderHook(() => usePagination({ pagination, onPaginationChange })); + const { handlePageIndexChange } = result.current; + + act(() => { + handlePageIndexChange(2); + }); + expect(onPaginationChange).toHaveBeenCalledWith({ + pagination: { pageIndex: 2, pageSize: 10, totalItemCount: 100 }, + }); + }); + test('should call onPaginationChange with correct pageSize when the number of items per change changes', () => { + const pagination = { pageIndex: 0, pageSize: 10, totalItemCount: 100 }; + + const { result } = renderHook(() => usePagination({ pagination, onPaginationChange })); + const { handleItemsPerPageChange } = result.current; + + act(() => { + handleItemsPerPageChange(100); + }); + expect(onPaginationChange).toHaveBeenCalledWith({ + pagination: { pageIndex: 0, pageSize: 100, totalItemCount: 100 }, + }); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts b/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts new file mode 100644 index 0000000000000..d235658263687 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { useCallback, useMemo } from 'react'; +import type { PaginationProps } from '../types'; + +export const usePagination = ({ pagination, onPaginationChange }: PaginationProps) => { + const { pageIndex, totalItemCount, pageSize, pageSizeOptions } = pagination; + + const pageCount = useMemo( + () => (isFinite(totalItemCount / pageSize) ? Math.ceil(totalItemCount / pageSize) : 0), + [pageSize, totalItemCount] + ); + + const handleItemsPerPageChange = useCallback( + (nextPageSize: number) => { + onPaginationChange({ + pagination: { + pageIndex, + pageSize: nextPageSize, + totalItemCount, + }, + }); + }, + [pageIndex, totalItemCount, onPaginationChange] + ); + + const handlePageIndexChange = useCallback( + (nextPageIndex: number) => { + onPaginationChange({ + pagination: { + pageIndex: nextPageIndex, + pageSize, + totalItemCount, + }, + }); + }, + [pageSize, totalItemCount, onPaginationChange] + ); + + return { + pageCount, + pageIndex, + pageSize, + pageSizeOptions, + + handleItemsPerPageChange, + handlePageIndexChange, + }; +}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx new file mode 100644 index 0000000000000..ac82bb3b6e850 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { fireEvent, render } from '@testing-library/react'; + +import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +import { SearchBar } from './search_bar'; + +describe('SearchBar', () => { + it('it does not display add exception button if user is read only', () => { + const wrapper = render( + + ); + + expect(wrapper.queryByTestId('searchBarButton')).not.toBeInTheDocument(); + }); + + it('it invokes "onAddExceptionClick" when user selects to add an exception item', () => { + const mockOnAddExceptionClick = jest.fn(); + const wrapper = render( + + ); + + const searchBtn = wrapper.getByTestId('searchBarButton'); + + fireEvent.click(searchBtn); + expect(searchBtn).toHaveTextContent('Add rule exception'); + expect(mockOnAddExceptionClick).toHaveBeenCalledWith('detection'); + }); + + it('it invokes "onAddExceptionClick" when user selects to add an endpoint exception item', () => { + const mockOnAddExceptionClick = jest.fn(); + const wrapper = render( + + ); + + const searchBtn = wrapper.getByTestId('searchBarButton'); + + fireEvent.click(searchBtn); + expect(searchBtn).toHaveTextContent('Add endpoint exception'); + expect(mockOnAddExceptionClick).toHaveBeenCalledWith('endpoint'); + }); + it('it invokes the "handlOnSearch" when the user add search query', () => { + const mockHandleOnSearch = jest.fn(); + const wrapper = render( + + ); + + const searchInput = wrapper.getByTestId('searchBar'); + fireEvent.change(searchInput, { target: { value: 'query' } }); + expect(mockHandleOnSearch).toBeCalledWith({ search: 'query' }); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.tsx b/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.tsx new file mode 100644 index 0000000000000..bb8dc6ee62559 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.tsx @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { useCallback } from 'react'; +import type { FC } from 'react'; + +import type { SearchFilterConfig } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiButton, EuiSearchBar } from '@elastic/eui'; +import type { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import type { GetExceptionItemProps } from '../types'; + +const ITEMS_SCHEMA = { + strict: true, + fields: { + created_by: { + type: 'string', + }, + description: { + type: 'string', + }, + id: { + type: 'string', + }, + item_id: { + type: 'string', + }, + list_id: { + type: 'string', + }, + name: { + type: 'string', + }, + os_types: { + type: 'string', + }, + tags: { + type: 'string', + }, + }, +}; +interface SearchBarProps { + addExceptionButtonText?: string; + placeholdertext?: string; + canAddException?: boolean; // TODO what is the default value + + // TODO: REFACTOR: not to send the listType and handle it in the Parent + // Exception list type used to determine what type of item is + // being created when "onAddExceptionClick" is invoked + listType: ExceptionListTypeEnum; + isSearching?: boolean; + dataTestSubj?: string; + filters?: SearchFilterConfig[]; // TODO about filters + onSearch: (arg: GetExceptionItemProps) => void; + onAddExceptionClick: (type: ExceptionListTypeEnum) => void; +} +const SearchBarComponent: FC = ({ + addExceptionButtonText, + placeholdertext, + canAddException, + listType, + isSearching, + dataTestSubj, + filters = [], + onSearch, + onAddExceptionClick, +}) => { + const handleOnSearch = useCallback( + ({ queryText }): void => { + onSearch({ search: queryText }); + }, + [onSearch] + ); + + const handleAddException = useCallback(() => { + // TODO: ASK YARA why we need to send the listType + onAddExceptionClick(listType); + }, [onAddExceptionClick, listType]); + + return ( + + + + + {!canAddException && ( + + + {addExceptionButtonText} + + + )} + + ); +}; + +SearchBarComponent.displayName = 'SearchBarComponent'; + +export const SearchBar = React.memo(SearchBarComponent); + +SearchBar.displayName = 'SearchBar'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/translations.ts b/packages/kbn-securitysolution-exception-list-components/src/translations.ts new file mode 100644 index 0000000000000..c919ef423c545 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/translations.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; + +export const EMPTY_VIEWER_STATE_EMPTY_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty.title', + { + defaultMessage: 'Add exceptions to this rule', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty.body', + { + defaultMessage: 'There is no exception in your rule. Create your first rule exception.', + } +); +export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty_search.search.title', + { + defaultMessage: 'No results match your search criteria', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty_search.body', + { + defaultMessage: 'Try modifying your search', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_VIEWER_BUTTON = (exceptionType: string) => + i18n.translate('exceptionList-components.empty.viewer.state.empty.viewer_button', { + values: { exceptionType }, + defaultMessage: 'Create {exceptionType} exception', + }); + +export const EMPTY_VIEWER_STATE_ERROR_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.error_title', + { + defaultMessage: 'Unable to load exception items', + } +); + +export const EMPTY_VIEWER_STATE_ERROR_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.error_body', + { + defaultMessage: + 'There was an error loading the exception items. Contact your administrator for help.', + } +); diff --git a/packages/kbn-securitysolution-exception-list-components/src/types/index.ts b/packages/kbn-securitysolution-exception-list-components/src/types/index.ts new file mode 100644 index 0000000000000..dbb402ca78451 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/types/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ExceptionListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import type { Pagination } from '@elastic/eui'; +import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; + +export interface GetExceptionItemProps { + pagination?: Pagination; + search?: string; + filters?: string; +} + +export interface PaginationProps { + dataTestSubj?: string; + ariaLabel?: string; + pagination: Pagination; + onPaginationChange: (arg: GetExceptionItemProps) => void; +} + +export enum ViewerStatus { + ERROR = 'error', + EMPTY = 'empty', + EMPTY_SEARCH = 'empty_search', + LOADING = 'loading', + SEARCHING = 'searching', + DELETING = 'deleting', +} + +export interface ExceptionListSummaryProps { + pagination: Pagination; + // Corresponds to last time exception items were fetched + lastUpdated: string | number | null; +} + +export type ViewerFlyoutName = 'addException' | 'editException' | null; + +export interface RuleReferences { + [key: string]: any[]; // TODO fix +} + +export interface ExceptionListItemIdentifiers { + id: string; + name: string; + namespaceType: NamespaceType; +} + +export enum ListTypeText { + ENDPOINT = 'endpoint', + DETECTION = 'empty', + RULE_DEFAULT = 'empty_search', +} + +export interface RuleReference { + name: string; + id: string; + ruleId: string; + exceptionLists: ExceptionListSchema[]; +} diff --git a/packages/core/mount-utils/core-mount-utils-browser-internal/src/consts.ts b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts similarity index 83% rename from packages/core/mount-utils/core-mount-utils-browser-internal/src/consts.ts rename to packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts index 8372eafec8147..472a80575f27d 100644 --- a/packages/core/mount-utils/core-mount-utils-browser-internal/src/consts.ts +++ b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts @@ -6,5 +6,4 @@ * Side Public License, v 1. */ -/** @internal */ -export const KBN_LOAD_MARKS = 'kbnLoad'; +export { ValueWithSpaceWarning } from './value_with_space_warning'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts new file mode 100644 index 0000000000000..8f6788d710a19 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { useValueWithSpaceWarning } from './use_value_with_space_warning'; + +describe('useValueWithSpaceWarning', () => { + it('should return true when value is string and contains space', () => { + const { result } = renderHook(() => useValueWithSpaceWarning({ value: ' space before' })); + + const { showSpaceWarningIcon, warningText } = result.current; + expect(showSpaceWarningIcon).toBeTruthy(); + expect(warningText).toBeTruthy(); + }); + it('should return true when value is string and does not contain space', () => { + const { result } = renderHook(() => useValueWithSpaceWarning({ value: 'no space' })); + + const { showSpaceWarningIcon, warningText } = result.current; + expect(showSpaceWarningIcon).toBeFalsy(); + expect(warningText).toBeTruthy(); + }); + it('should return true when value is array and one of the elements contains space', () => { + const { result } = renderHook(() => + useValueWithSpaceWarning({ value: [' space before', 'no space'] }) + ); + + const { showSpaceWarningIcon, warningText } = result.current; + expect(showSpaceWarningIcon).toBeTruthy(); + expect(warningText).toBeTruthy(); + }); + it('should return true when value is array and none contains space', () => { + const { result } = renderHook(() => + useValueWithSpaceWarning({ value: ['no space', 'no space'] }) + ); + + const { showSpaceWarningIcon, warningText } = result.current; + expect(showSpaceWarningIcon).toBeFalsy(); + expect(warningText).toBeTruthy(); + }); + it('should return the tooltipIconText', () => { + const { result } = renderHook(() => + useValueWithSpaceWarning({ value: ' space before', tooltipIconText: 'Warning Text' }) + ); + + const { showSpaceWarningIcon, warningText } = result.current; + expect(showSpaceWarningIcon).toBeTruthy(); + expect(warningText).toEqual('Warning Text'); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts new file mode 100644 index 0000000000000..bf407d2798c78 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { paramContainsSpace, autoCompletei18n } from '@kbn/securitysolution-autocomplete'; + +interface UseValueWithSpaceWarningResult { + showSpaceWarningIcon: boolean; + warningText: string; +} +interface UseValueWithSpaceWarningProps { + value: string | string[]; + tooltipIconText?: string; +} + +export const useValueWithSpaceWarning = ({ + value, + tooltipIconText, +}: UseValueWithSpaceWarningProps): UseValueWithSpaceWarningResult => { + const showSpaceWarningIcon = Array.isArray(value) + ? value.find(paramContainsSpace) + : paramContainsSpace(value); + + return { + showSpaceWarningIcon: !!showSpaceWarningIcon, + warningText: tooltipIconText || autoCompletei18n.FIELD_SPACE_WARNING, + }; +}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx new file mode 100644 index 0000000000000..e19a54be48aa4 --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { fireEvent, render } from '@testing-library/react'; + +import { ValueWithSpaceWarning } from '.'; + +import * as useValueWithSpaceWarningMock from './use_value_with_space_warning'; + +jest.mock('./use_value_with_space_warning'); + +describe('ValueWithSpaceWarning', () => { + beforeEach(() => { + // @ts-ignore + useValueWithSpaceWarningMock.useValueWithSpaceWarning = jest + .fn() + .mockReturnValue({ showSpaceWarningIcon: true, warningText: 'Warning Text' }); + }); + it('should not render if value is falsy', () => { + const container = render(); + expect(container.queryByTestId('valueWithSpaceWarningTooltip')).toBeFalsy(); + }); + it('should not render if showSpaceWarning is falsy', () => { + // @ts-ignore + useValueWithSpaceWarningMock.useValueWithSpaceWarning = jest + .fn() + .mockReturnValue({ showSpaceWarningIcon: false, warningText: '' }); + + const container = render(); + expect(container.queryByTestId('valueWithSpaceWarningTooltip')).toBeFalsy(); + }); + it('should render if showSpaceWarning is truthy', () => { + const container = render(); + expect(container.getByTestId('valueWithSpaceWarningTooltip')).toBeInTheDocument(); + }); + it('should show the tooltip when the icon is clicked', async () => { + const container = render(); + + fireEvent.mouseOver(container.getByTestId('valueWithSpaceWarningTooltip')); + expect(await container.findByText('Warning Text')).toBeInTheDocument(); + }); +}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx new file mode 100644 index 0000000000000..9cff0649efb9e --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import type { FC } from 'react'; +import { css } from '@emotion/css'; +import { euiThemeVars } from '@kbn/ui-theme'; + +import { EuiIcon, EuiToolTip } from '@elastic/eui'; +import { useValueWithSpaceWarning } from './use_value_with_space_warning'; + +interface ValueWithSpaceWarningProps { + value: string[] | string; + tooltipIconType?: string; + tooltipIconText?: string; +} +const containerCss = css` + display: inline; + margin-left: ${euiThemeVars.euiSizeXS}; +`; +export const ValueWithSpaceWarning: FC = ({ + value, + tooltipIconType = 'iInCircle', + tooltipIconText, +}) => { + const { showSpaceWarningIcon, warningText } = useValueWithSpaceWarning({ + value, + tooltipIconText, + }); + if (!showSpaceWarningIcon || !value) return null; + return ( +
+ + + +
+ ); +}; diff --git a/packages/kbn-securitysolution-exception-list-components/tsconfig.json b/packages/kbn-securitysolution-exception-list-components/tsconfig.json new file mode 100644 index 0000000000000..412652e0a8f9d --- /dev/null +++ b/packages/kbn-securitysolution-exception-list-components/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "stripInternal": false, + "types": [ + "jest", + "node", + "react", + "@emotion/react/types/css-prop" + ] + }, + "include": [ + "**/*.ts", + "**/*.tsx", + "**/*.d.ts" + ] +} diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/index.ts index c2e00482cd2d3..75d5352c9f63e 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/index.ts @@ -18,7 +18,6 @@ export * from './src/default_per_page'; export * from './src/default_risk_score_mapping_array'; export * from './src/default_severity_mapping_array'; export * from './src/default_threat_array'; -export * from './src/default_throttle_null'; export * from './src/default_to_string'; export * from './src/default_uuid'; export * from './src/from'; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.test.ts deleted file mode 100644 index b92815d4fe828..0000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { Throttle } from '../throttle'; -import { DefaultThrottleNull } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('default_throttle_null', () => { - test('it should validate a throttle string', () => { - const payload: Throttle = 'some string'; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = 5; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultThreatNull"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default "null" if not provided a value', () => { - const payload = undefined; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(null); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.ts deleted file mode 100644 index e9b9ec27ea418..0000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_throttle_null/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { throttle, ThrottleOrNull } from '../throttle'; - -/** - * Types the DefaultThrottleNull as: - * - If null or undefined, then a null will be set - */ -export const DefaultThrottleNull = new t.Type( - 'DefaultThreatNull', - throttle.is, - (input, context): Either => - input == null ? t.success(null) : throttle.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts index 19e75dcc3be07..d7d636ad0994e 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts @@ -6,13 +6,15 @@ * Side Public License, v 1. */ +import { TimeDuration } from '@kbn/securitysolution-io-ts-types'; import * as t from 'io-ts'; -export const throttle = t.string; +export const throttle = t.union([ + t.literal('no_actions'), + t.literal('rule'), + TimeDuration({ allowedUnits: ['h', 'd'] }), +]); export type Throttle = t.TypeOf; export const throttleOrNull = t.union([throttle, t.null]); export type ThrottleOrNull = t.TypeOf; - -export const throttleOrNullOrUndefined = t.union([throttle, t.null, t.undefined]); -export type ThrottleOrUndefinedOrNull = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts b/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts index 8af5f04bf16e6..dc6b5e61ebbf6 100644 --- a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts @@ -6,100 +6,315 @@ * Side Public License, v 1. */ -import { pipe } from 'fp-ts/lib/pipeable'; import { left } from 'fp-ts/lib/Either'; import { TimeDuration } from '.'; import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -describe('time_unit', () => { - test('it should validate a correctly formed TimeDuration with time unit of seconds', () => { - const payload = '1s'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); +describe('TimeDuration', () => { + describe('with allowedDurations', () => { + test('it should validate a correctly formed TimeDuration with an allowed duration of 1s', () => { + const payload = '1s'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 's'], + [2, 'h'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); - test('it should validate a correctly formed TimeDuration with time unit of minutes', () => { - const payload = '100m'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should validate a correctly formed TimeDuration with an allowed duration of 7d', () => { + const payload = '1s'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 's'], + [2, 'h'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); - test('it should validate a correctly formed TimeDuration with time unit of hours', () => { - const payload = '10000000h'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate a time duration if the allowed durations does not include it', () => { + const payload = '24h'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 's'], + [2, 'h'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "24h" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate a negative TimeDuration', () => { - const payload = '-10s'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate a an allowed duration with a negative number', () => { + const payload = '10s'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 's'], + [-7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-10s" supplied to "TimeDuration"', - ]); - expect(message.schema).toEqual({}); - }); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[[1,"s"],[-7,"d"]]" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate a TimeDuration with some other time unit', () => { - const payload = '10000000w'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate an allowed duration with a fractional number', () => { + const payload = '1.5s'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 's'], + [-7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "10000000w" supplied to "TimeDuration"', - ]); - expect(message.schema).toEqual({}); - }); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1.5s" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate a TimeDuration with a time interval with incorrect format', () => { - const payload = '100ff0000w'; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate a an allowed duration with a duration of 0', () => { + const payload = '10s'; + const decoded = TimeDuration({ + allowedDurations: [ + [0, 's'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "100ff0000w" supplied to "TimeDuration"', - ]); - expect(message.schema).toEqual({}); - }); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[[0,"s"],[7,"d"]]" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate an empty string', () => { - const payload = ''; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate a TimeDuration with an invalid time unit', () => { + const payload = '10000000days'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "TimeDuration"']); - expect(message.schema).toEqual({}); - }); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "10000000days" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a TimeDuration with a time interval with incorrect format', () => { + const payload = '100ff0000w'; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "100ff0000w" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate an number', () => { - const payload = 100; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate an empty string', () => { + const payload = ''; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "100" supplied to "TimeDuration"', - ]); - expect(message.schema).toEqual({}); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate an number', () => { + const payload = 100; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "100" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate an TimeDuration with a valid time unit but unsafe integer', () => { + const payload = `${Math.pow(2, 53)}h`; + const decoded = TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + `Invalid value "${Math.pow(2, 53)}h" supplied to "TimeDuration"`, + ]); + expect(message.schema).toEqual({}); + }); }); + describe('with allowedUnits', () => { + test('it should validate a correctly formed TimeDuration with time unit of seconds', () => { + const payload = '1s'; + const decoded = TimeDuration({ allowedUnits: ['s'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a correctly formed TimeDuration with time unit of minutes', () => { + const payload = '100m'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a correctly formed TimeDuration with time unit of hours', () => { + const payload = '10000000h'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a correctly formed TimeDuration with time unit of days', () => { + const payload = '7d'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should NOT validate a correctly formed TimeDuration with time unit of seconds if it is not an allowed unit', () => { + const payload = '30s'; + const decoded = TimeDuration({ allowedUnits: ['m', 'h', 'd'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "30s" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a negative TimeDuration', () => { + const payload = '-10s'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "-10s" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a fractional number', () => { + const payload = '1.5s'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1.5s" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a TimeDuration with an invalid time unit', () => { + const payload = '10000000days'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "10000000days" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a TimeDuration with a time interval with incorrect format', () => { + const payload = '100ff0000w'; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "100ff0000w" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate an empty string', () => { + const payload = ''; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate an number', () => { + const payload = 100; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h'] }).decode(payload); + const message = foldLeftRight(decoded); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "100" supplied to "TimeDuration"', + ]); + expect(message.schema).toEqual({}); + }); - test('it should NOT validate an TimeDuration with a valid time unit but unsafe integer', () => { - const payload = `${Math.pow(2, 53)}h`; - const decoded = TimeDuration.decode(payload); - const message = pipe(decoded, foldLeftRight); + test('it should NOT validate an TimeDuration with a valid time unit but unsafe integer', () => { + const payload = `${Math.pow(2, 53)}h`; + const decoded = TimeDuration({ allowedUnits: ['s', 'm', 'h'] }).decode(payload); + const message = foldLeftRight(decoded); - expect(getPaths(left(message.errors))).toEqual([ - `Invalid value "${Math.pow(2, 53)}h" supplied to "TimeDuration"`, - ]); - expect(message.schema).toEqual({}); + expect(getPaths(left(message.errors))).toEqual([ + `Invalid value "${Math.pow(2, 53)}h" supplied to "TimeDuration"`, + ]); + expect(message.schema).toEqual({}); + }); }); }); diff --git a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts b/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts index c486e1d171689..0b69c62e0d2f5 100644 --- a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts +++ b/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts @@ -12,34 +12,60 @@ import { Either } from 'fp-ts/lib/Either'; /** * Types the TimeDuration as: * - A string that is not empty, and composed of a positive integer greater than 0 followed by a unit of time - * - in the format {safe_integer}{timeUnit}, e.g. "30s", "1m", "2h" + * - in the format {safe_integer}{timeUnit}, e.g. "30s", "1m", "2h", "7d" */ -export const TimeDuration = new t.Type( - 'TimeDuration', - t.string.is, - (input, context): Either => { - if (typeof input === 'string' && input.trim() !== '') { - try { - const inputLength = input.length; - const time = parseInt(input.trim().substring(0, inputLength - 1), 10); - const unit = input.trim().at(-1); - if ( - time >= 1 && - Number.isSafeInteger(time) && - (unit === 's' || unit === 'm' || unit === 'h') - ) { - return t.success(input); - } else { + +type TimeUnits = 's' | 'm' | 'h' | 'd' | 'w' | 'y'; +interface TimeDurationWithAllowedDurations { + allowedDurations: Array<[number, TimeUnits]>; + allowedUnits?: never; +} +interface TimeDurationWithAllowedUnits { + allowedUnits: TimeUnits[]; + allowedDurations?: never; +} + +type TimeDurationType = TimeDurationWithAllowedDurations | TimeDurationWithAllowedUnits; + +const isTimeSafe = (time: number) => time >= 1 && Number.isSafeInteger(time); + +export const TimeDuration = ({ allowedUnits, allowedDurations }: TimeDurationType) => { + return new t.Type( + 'TimeDuration', + t.string.is, + (input, context): Either => { + if (typeof input === 'string' && input.trim() !== '') { + try { + const inputLength = input.length; + const time = Number(input.trim().substring(0, inputLength - 1)); + const unit = input.trim().at(-1); + if (!isTimeSafe(time)) { + return t.failure(input, context); + } + if (allowedDurations) { + for (const [allowedTime, allowedUnit] of allowedDurations) { + if (!isTimeSafe(allowedTime)) { + return t.failure(allowedDurations, context); + } + if (allowedTime === time && allowedUnit === unit) { + return t.success(input); + } + } + return t.failure(input, context); + } else if (allowedUnits.includes(unit as TimeUnits)) { + return t.success(input); + } else { + return t.failure(input, context); + } + } catch (error) { return t.failure(input, context); } - } catch (error) { + } else { return t.failure(input, context); } - } else { - return t.failure(input, context); - } - }, - t.identity -); + }, + t.identity + ); +}; export type TimeDurationC = typeof TimeDuration; diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts index ce44dd3cc0496..6d5dc75b8d969 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts @@ -260,6 +260,13 @@ export const schema = Joi.object() // definition of apps that work with `common.navigateToApp()` apps: Joi.object().pattern(ID_PATTERN, appUrlPartsSchema()).default(), + // settings for the saved objects svc + esArchiver: Joi.object() + .keys({ + baseDirectory: Joi.string().optional(), + }) + .default(), + // settings for the saved objects svc kbnArchiver: Joi.object() .keys({ diff --git a/renovate.json b/renovate.json index 6eed31366c409..4075b2452bea1 100644 --- a/renovate.json +++ b/renovate.json @@ -125,7 +125,7 @@ ], "reviewers": ["team:kibana-security"], "matchBaseBranches": ["main"], - "labels": ["Team:Security", "release_note:skip", "auto-backport"], + "labels": ["Team:Security", "release_note:skip", "backport:all-open"], "enabled": true }, { diff --git a/scripts/archive_migration_functions.sh b/scripts/archive_migration_functions.sh index a37d52a1417c7..7dcba01175731 100755 --- a/scripts/archive_migration_functions.sh +++ b/scripts/archive_migration_functions.sh @@ -1,27 +1,13 @@ -#!/bin/bash - -# ??? Should we migrate -# x-pack/test/functional/es_archives/logstash/example_pipelines -# !!! No, we've found 0 saved objects that are listed in the standard_list -# !!! It contains the following saved object(s) -# config -# space - standard_list="url,index-pattern,query,graph-workspace,tag,visualization,canvas-element,canvas-workpad,dashboard,search,lens,map,cases,uptime-dynamic-settings,osquery-saved-query,osquery-pack,infrastructure-ui-source,metrics-explorer-view,inventory-view,infrastructure-monitoring-log-view,apm-indices" -orig_archive="x-pack/test/functional/es_archives/spaces/multi_space" -new_archive="x-pack/test/functional/fixtures/kbn_archiver/spaces/multi_space" +orig_archive="x-pack/test/functional/es_archives/banners/multispace" +new_archive="x-pack/test/functional/fixtures/kbn_archiver/banners/multi_space" # newArchives=("x-pack/test/functional/fixtures/kbn_archiver/dashboard/session_in_space") -# newArchives+=("x-pack/test/functional/fixtures/kbn_archiver/dashboard/session_in_another_space") -testFiles=("x-pack/test/functional/apps/discover/preserve_url.ts") -testFiles+=("x-pack/test/functional/apps/visualize/preserve_url.ts") -testFiles+=("x-pack/test/functional/apps/dashboard/group1/preserve_url.ts") +# testFiles=("x-pack/test/functional/apps/discover/preserve_url.ts") -test_config="x-pack/test/functional/apps/dashboard/group1/config.ts" -# test_config="x-pack/test/functional/apps/discover/config.ts" -# test_config="x-pack/test/functional/apps/visualize/config.ts" +test_config="x-pack/test/banners_functional/config.ts" list_stragglers() { diff --git a/src/core/public/index.scss b/src/core/public/index.scss index 4b034af74fa1b..c056b0f851801 100644 --- a/src/core/public/index.scss +++ b/src/core/public/index.scss @@ -1,4 +1,3 @@ @import './variables'; @import './mixins'; -@import './core'; @import './styles/index'; diff --git a/src/core/public/index.ts b/src/core/public/index.ts index ff666e0f3a187..643bc705814a0 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -226,6 +226,6 @@ export type { export type { CoreSetup, CoreStart, StartServicesAccessor } from '@kbn/core-lifecycle-browser'; -export type { CoreSystem } from './core_system'; +export type { CoreSystem } from '@kbn/core-root-browser-internal'; -export { __kbnBootstrap__ } from './kbn_bootstrap'; +export { __kbnBootstrap__ } from '@kbn/core-root-browser-internal'; diff --git a/src/core/server/http_resources/http_resources_service.ts b/src/core/server/http_resources/http_resources_service.ts index 7e95dc9e302d9..5db20bf45e409 100644 --- a/src/core/server/http_resources/http_resources_service.ts +++ b/src/core/server/http_resources/http_resources_service.ts @@ -18,7 +18,7 @@ import type { InternalHttpServiceSetup, InternalHttpServicePreboot, } from '@kbn/core-http-server-internal'; -import { RequestHandlerContext } from '..'; +import type { RequestHandlerContext } from '@kbn/core-http-request-handler-context-server'; import { InternalRenderingServicePreboot, InternalRenderingServiceSetup } from '../rendering'; import { InternalHttpResourcesSetup, diff --git a/src/core/server/http_resources/types.ts b/src/core/server/http_resources/types.ts index 397f03098dd13..246a7394c3ade 100644 --- a/src/core/server/http_resources/types.ts +++ b/src/core/server/http_resources/types.ts @@ -15,7 +15,7 @@ import type { KibanaResponseFactory, RequestHandler, } from '@kbn/core-http-server'; -import type { RequestHandlerContext } from '..'; +import type { RequestHandlerContext } from '@kbn/core-http-request-handler-context-server'; /** * Allows to configure HTTP response parameters diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 6e72b1d2623cf..020975c15fb1b 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -42,7 +42,6 @@ import type { ExecutionContextStart, } from '@kbn/core-execution-context-server'; import type { - RequestHandlerContextBase, IRouter, RequestHandler, KibanaResponseFactory, @@ -69,12 +68,11 @@ import type { CoreUsageDataStart, CoreUsageDataSetup } from '@kbn/core-usage-dat import type { I18nServiceSetup } from '@kbn/core-i18n-server'; import type { StatusServiceSetup } from '@kbn/core-status-server'; import type { UiSettingsServiceSetup, UiSettingsServiceStart } from '@kbn/core-ui-settings-server'; - +import type { RequestHandlerContext } from '@kbn/core-http-request-handler-context-server'; import { HttpResources } from './http_resources'; -import { PluginsServiceSetup, PluginsServiceStart, PluginOpaqueId } from './plugins'; -import type { CoreRequestHandlerContext } from './core_route_handler_context'; -import type { PrebootCoreRequestHandlerContext } from './preboot_core_route_handler_context'; +import { PluginsServiceSetup, PluginsServiceStart } from './plugins'; +export type { PluginOpaqueId } from '@kbn/core-base-common'; export type { CoreUsageStats, CoreUsageData, @@ -462,33 +460,13 @@ export type { AnalyticsServicePreboot, AnalyticsServiceStart, } from '@kbn/core-analytics-server'; - -export type { CoreRequestHandlerContext } from './core_route_handler_context'; - -/** - * Base context passed to a route handler, containing the `core` context part. - * - * @public - */ -export interface RequestHandlerContext extends RequestHandlerContextBase { - core: Promise; -} - -/** - * @internal - */ -export interface PrebootRequestHandlerContext extends RequestHandlerContextBase { - core: Promise; -} - -/** - * Mixin allowing plugins to define their own request handler contexts. - * - * @public - */ -export type CustomRequestHandlerContext = RequestHandlerContext & { - [Key in keyof T]: T[Key] extends Promise ? T[Key] : Promise; -}; +export type { + RequestHandlerContext, + CoreRequestHandlerContext, + CustomRequestHandlerContext, + PrebootRequestHandlerContext, + PrebootCoreRequestHandlerContext, +} from '@kbn/core-http-request-handler-context-server'; /** * Context passed to the `setup` method of `preboot` plugins. @@ -599,7 +577,6 @@ export type { HttpResources, PluginsServiceSetup, PluginsServiceStart, - PluginOpaqueId, }; /** diff --git a/src/core/server/server.ts b/src/core/server/server.ts index aa747a1023b35..e333e8b81a404 100644 --- a/src/core/server/server.ts +++ b/src/core/server/server.ts @@ -58,16 +58,21 @@ import { import { CoreUsageDataService } from '@kbn/core-usage-data-server-internal'; import { StatusService, statusConfig } from '@kbn/core-status-server-internal'; import { UiSettingsService, uiSettingsConfig } from '@kbn/core-ui-settings-server-internal'; +import { + CoreRouteHandlerContext, + PrebootCoreRouteHandlerContext, +} from '@kbn/core-http-request-handler-context-server-internal'; +import type { + RequestHandlerContext, + PrebootRequestHandlerContext, +} from '@kbn/core-http-request-handler-context-server'; import { CoreApp } from './core_app'; import { HttpResourcesService } from './http_resources'; import { RenderingService } from './rendering'; import { PluginsService, config as pluginsConfig } from './plugins'; import { InternalCorePreboot, InternalCoreSetup, InternalCoreStart } from './internal_types'; -import { CoreRouteHandlerContext } from './core_route_handler_context'; -import { PrebootCoreRouteHandlerContext } from './preboot_core_route_handler_context'; import { DiscoveredPlugins } from './plugins'; -import type { RequestHandlerContext, PrebootRequestHandlerContext } from '.'; const coreId = Symbol('core'); const rootConfigPath = ''; diff --git a/src/dev/build/tasks/bin/scripts/kibana b/src/dev/build/tasks/bin/scripts/kibana index a4fc5385500b5..f96fac236b55c 100755 --- a/src/dev/build/tasks/bin/scripts/kibana +++ b/src/dev/build/tasks/bin/scripts/kibana @@ -26,4 +26,4 @@ if [ -f "${CONFIG_DIR}/node.options" ]; then KBN_NODE_OPTS="$(grep -v ^# < ${CONFIG_DIR}/node.options | xargs)" fi -NODE_OPTIONS="--no-warnings --max-http-header-size=65536 $KBN_NODE_OPTS $NODE_OPTIONS" NODE_ENV=production exec "${NODE}" "${DIR}/src/cli/dist" ${@} +NODE_OPTIONS="--no-warnings --max-http-header-size=65536 $KBN_NODE_OPTS $NODE_OPTIONS" NODE_ENV=production exec "${NODE}" "${DIR}/src/cli/dist" "${@}" diff --git a/src/dev/build/tasks/bundle_fleet_packages.ts b/src/dev/build/tasks/bundle_fleet_packages.ts index 4ba5e79d29928..30cfc1d22b0e6 100644 --- a/src/dev/build/tasks/bundle_fleet_packages.ts +++ b/src/dev/build/tasks/bundle_fleet_packages.ts @@ -15,6 +15,10 @@ import { Task, read, downloadToDisk, unzipBuffer, createZipFile } from '../lib'; const BUNDLED_PACKAGES_DIR = 'x-pack/plugins/fleet/target/bundled_packages'; +// APM needs to directly request its versions from Package Storage v2 - this should +// be removed when Package Storage v2 is in production +const PACKAGE_STORAGE_V2_URL = 'https://epr-v2.ea-web.elastic.dev'; + interface FleetPackage { name: string; version: string; @@ -64,7 +68,12 @@ export const BundleFleetPackages: Task = { } const archivePath = `${fleetPackage.name}-${versionToWrite}.zip`; - const archiveUrl = `${eprUrl}/epr/${fleetPackage.name}/${fleetPackage.name}-${fleetPackage.version}.zip`; + let archiveUrl = `${eprUrl}/epr/${fleetPackage.name}/${fleetPackage.name}-${fleetPackage.version}.zip`; + + // Point APM to package storage v2 + if (fleetPackage.name === 'apm') { + archiveUrl = `${PACKAGE_STORAGE_V2_URL}/epr/${fleetPackage.name}/${fleetPackage.name}-${fleetPackage.version}.zip`; + } const destination = build.resolvePath(BUNDLED_PACKAGES_DIR, archivePath); diff --git a/src/dev/storybook/aliases.ts b/src/dev/storybook/aliases.ts index 1705c9ac2ec9c..b4224e154def5 100644 --- a/src/dev/storybook/aliases.ts +++ b/src/dev/storybook/aliases.ts @@ -43,6 +43,7 @@ export const storybookAliases = { security_solution: 'x-pack/plugins/security_solution/.storybook', shared_ux: 'packages/shared-ux/storybook/config', threat_intelligence: 'x-pack/plugins/threat_intelligence/.storybook', + triggers_actions_ui: 'x-pack/plugins/triggers_actions_ui/.storybook', ui_actions_enhanced: 'src/plugins/ui_actions_enhanced/.storybook', unified_search: 'src/plugins/unified_search/.storybook', }; diff --git a/src/plugins/chart_expressions/expression_metric/public/__mocks__/theme_service.ts b/src/plugins/chart_expressions/expression_metric/public/__mocks__/theme_service.ts index 9690bd4a2d486..b00ec8a6ee569 100644 --- a/src/plugins/chart_expressions/expression_metric/public/__mocks__/theme_service.ts +++ b/src/plugins/chart_expressions/expression_metric/public/__mocks__/theme_service.ts @@ -9,5 +9,6 @@ export const getThemeService = () => { return { useChartsTheme: () => ({}), + useChartsBaseTheme: () => ({ metric: { minHeight: 64 } }), }; }; diff --git a/src/plugins/chart_expressions/expression_metric/public/components/metric_vis.tsx b/src/plugins/chart_expressions/expression_metric/public/components/metric_vis.tsx index 539b41950a23c..f3e7a2864ec86 100644 --- a/src/plugins/chart_expressions/expression_metric/public/components/metric_vis.tsx +++ b/src/plugins/chart_expressions/expression_metric/public/components/metric_vis.tsx @@ -311,15 +311,18 @@ export const MetricVis = ({ const scrollContainerRef = useRef(null); const scrollDimensions = useResizeObserver(scrollContainerRef.current); + const { + metric: { minHeight }, + } = getThemeService().useChartsBaseTheme(); + useEffect(() => { - const minTileHeight = 64; // TODO - magic number from the @elastic/charts side. would be nice to deduplicate - const minimumRequiredVerticalSpace = minTileHeight * grid.length; + const minimumRequiredVerticalSpace = minHeight * grid.length; setScrollChildHeight( (scrollDimensions.height ?? -Infinity) > minimumRequiredVerticalSpace ? '100%' : `${minimumRequiredVerticalSpace}px` ); - }, [grid.length, scrollDimensions.height]); + }, [grid.length, minHeight, scrollDimensions.height]); return (
({ visConfig, syncColors: handlers?.isSyncColorsEnabled?.() ?? false, visType: args.isDonut ? ChartTypes.DONUT : ChartTypes.PIE, + canNavigateToLens: Boolean(handlers?.variables?.canNavigateToLens), params: { listenOnChange: true, }, diff --git a/src/plugins/chart_expressions/expression_partition_vis/common/types/expression_renderers.ts b/src/plugins/chart_expressions/expression_partition_vis/common/types/expression_renderers.ts index 2f436de90e138..6a8fd2935ba54 100644 --- a/src/plugins/chart_expressions/expression_partition_vis/common/types/expression_renderers.ts +++ b/src/plugins/chart_expressions/expression_partition_vis/common/types/expression_renderers.ts @@ -108,6 +108,7 @@ export interface RenderValue { visType: ChartTypes; visConfig: PartitionVisParams; syncColors: boolean; + canNavigateToLens?: boolean; } export enum LabelPositions { diff --git a/src/plugins/chart_expressions/expression_partition_vis/public/expression_renderers/partition_vis_renderer.tsx b/src/plugins/chart_expressions/expression_partition_vis/public/expression_renderers/partition_vis_renderer.tsx index 546b70d98c6eb..4b6fe45e4df92 100644 --- a/src/plugins/chart_expressions/expression_partition_vis/public/expression_renderers/partition_vis_renderer.tsx +++ b/src/plugins/chart_expressions/expression_partition_vis/public/expression_renderers/partition_vis_renderer.tsx @@ -49,7 +49,11 @@ export const getPartitionVisRenderer: ( displayName: strings.getDisplayName(), help: strings.getHelpDescription(), reuseDomNode: true, - render: async (domNode, { visConfig, visData, visType, syncColors }, handlers) => { + render: async ( + domNode, + { visConfig, visData, visType, syncColors, canNavigateToLens }, + handlers + ) => { const { core, plugins } = getStartDeps(); handlers.onDestroy(() => { @@ -62,9 +66,12 @@ export const getPartitionVisRenderer: ( const visualizationType = extractVisualizationType(executionContext); if (containerType && visualizationType) { - plugins.usageCollection?.reportUiCounter(containerType, METRIC_TYPE.COUNT, [ + const events = [ `render_${visualizationType}_${visType}`, - ]); + canNavigateToLens ? `render_${visualizationType}_${visType}_convertable` : undefined, + ].filter((event): event is string => Boolean(event)); + + plugins.usageCollection?.reportUiCounter(containerType, METRIC_TYPE.COUNT, events); } handlers.done(); }; diff --git a/src/plugins/console/public/application/components/console_menu.tsx b/src/plugins/console/public/application/components/console_menu.tsx index 3f5113b3ac44f..b22fd7db9baab 100644 --- a/src/plugins/console/public/application/components/console_menu.tsx +++ b/src/plugins/console/public/application/components/console_menu.tsx @@ -128,6 +128,7 @@ export class ConsoleMenu extends Component { const items = [ { @@ -174,7 +175,7 @@ export class ConsoleMenu extends Component { panelPaddingSize="none" anchorPosition="downLeft" > - + ); diff --git a/src/plugins/controls/public/services/plugin_services.stub.ts b/src/plugins/controls/public/services/plugin_services.stub.ts index 485891ff6ef94..08be260ce052c 100644 --- a/src/plugins/controls/public/services/plugin_services.stub.ts +++ b/src/plugins/controls/public/services/plugin_services.stub.ts @@ -27,16 +27,15 @@ import { themeServiceFactory } from './theme/theme.story'; import { registry as stubRegistry } from './plugin_services.story'; export const providers: PluginServiceProviders = { - http: new PluginServiceProvider(httpServiceFactory), + controls: new PluginServiceProvider(controlsServiceFactory), data: new PluginServiceProvider(dataServiceFactory), - overlays: new PluginServiceProvider(overlaysServiceFactory), dataViews: new PluginServiceProvider(dataViewsServiceFactory), + http: new PluginServiceProvider(httpServiceFactory), + optionsList: new PluginServiceProvider(optionsListServiceFactory), + overlays: new PluginServiceProvider(overlaysServiceFactory), settings: new PluginServiceProvider(settingsServiceFactory), - unifiedSearch: new PluginServiceProvider(unifiedSearchServiceFactory), theme: new PluginServiceProvider(themeServiceFactory), - - controls: new PluginServiceProvider(controlsServiceFactory), - optionsList: new PluginServiceProvider(optionsListServiceFactory), + unifiedSearch: new PluginServiceProvider(unifiedSearchServiceFactory), }; export const pluginServices = new PluginServices(); diff --git a/src/plugins/controls/public/services/plugin_services.ts b/src/plugins/controls/public/services/plugin_services.ts index 4debd0e8c9eba..f1811063e39a5 100644 --- a/src/plugins/controls/public/services/plugin_services.ts +++ b/src/plugins/controls/public/services/plugin_services.ts @@ -30,16 +30,15 @@ export const providers: PluginServiceProviders< ControlsServices, KibanaPluginServiceParams > = { - http: new PluginServiceProvider(httpServiceFactory), + controls: new PluginServiceProvider(controlsServiceFactory), data: new PluginServiceProvider(dataServiceFactory), - unifiedSearch: new PluginServiceProvider(unifiedSearchServiceFactory), - overlays: new PluginServiceProvider(overlaysServiceFactory), dataViews: new PluginServiceProvider(dataViewsServiceFactory), + http: new PluginServiceProvider(httpServiceFactory), + optionsList: new PluginServiceProvider(optionsListServiceFactory, ['data', 'http']), + overlays: new PluginServiceProvider(overlaysServiceFactory), settings: new PluginServiceProvider(settingsServiceFactory), theme: new PluginServiceProvider(themeServiceFactory), - - optionsList: new PluginServiceProvider(optionsListServiceFactory, ['data', 'http']), - controls: new PluginServiceProvider(controlsServiceFactory), + unifiedSearch: new PluginServiceProvider(unifiedSearchServiceFactory), }; export const pluginServices = new PluginServices(); diff --git a/src/plugins/custom_integrations/common/index.ts b/src/plugins/custom_integrations/common/index.ts index a3ab30a526ca6..e52a5deac59e5 100755 --- a/src/plugins/custom_integrations/common/index.ts +++ b/src/plugins/custom_integrations/common/index.ts @@ -23,6 +23,7 @@ export const INTEGRATION_CATEGORY_DISPLAY = { datastore: 'Datastore', elastic_stack: 'Elastic Stack', google_cloud: 'Google Cloud', + infrastructure: 'Infrastructure', kubernetes: 'Kubernetes', languages: 'Languages', message_queue: 'Message queue', diff --git a/src/plugins/custom_integrations/common/language_integrations.ts b/src/plugins/custom_integrations/common/language_integrations.ts index c9821281f2854..9ba914c02fd0d 100644 --- a/src/plugins/custom_integrations/common/language_integrations.ts +++ b/src/plugins/custom_integrations/common/language_integrations.ts @@ -145,4 +145,18 @@ export const languageIntegrations: LanguageIntegration[] = [ integrationsAppUrl: `/app/integrations/language_clients/java/overview`, exportLanguageUiComponent: false, }, + // Uncomment to show the sample language client card + README UI + // { + // id: 'sample', + // title: i18n.translate('customIntegrations.languageclients.SampleTitle', { + // defaultMessage: 'Sample Language Client', + // }), + // icon: 'es.svg', + // description: i18n.translate('customIntegrations.languageclients.SampleDescription', { + // defaultMessage: 'Sample language client', + // }), + // docUrlTemplate: '', + // integrationsAppUrl: `/app/integrations/language_clients/sample/overview`, + // exportLanguageUiComponent: true, + // }, ]; diff --git a/src/plugins/custom_integrations/public/components/fleet_integration/overview_component.tsx b/src/plugins/custom_integrations/public/components/fleet_integration/overview_component.tsx deleted file mode 100644 index c5b8584e1e4a9..0000000000000 --- a/src/plugins/custom_integrations/public/components/fleet_integration/overview_component.tsx +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import React from 'react'; -import { EuiTitle } from '@elastic/eui'; - -/* -Example of Overview component to be shown inside Integrations app -*/ -export interface ReadmeProps { - packageName: string; -} -export const OverviewComponent: React.FC = ({ packageName }) => { - return ( - -

{packageName} client - Overview

-
- ); -}; diff --git a/src/plugins/custom_integrations/public/components/fleet_integration/sample/sample_client_readme.tsx b/src/plugins/custom_integrations/public/components/fleet_integration/sample/sample_client_readme.tsx new file mode 100644 index 0000000000000..c2ca0d62da689 --- /dev/null +++ b/src/plugins/custom_integrations/public/components/fleet_integration/sample/sample_client_readme.tsx @@ -0,0 +1,200 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React, { useState } from 'react'; + +// eslint-disable-next-line @kbn/eslint/module_migration +import styled from 'styled-components'; +import cuid from 'cuid'; + +import { + EuiButton, + EuiCode, + EuiCodeBlock, + EuiFlexGroup, + EuiFlexItem, + EuiPage, + EuiPageBody, + EuiPageHeader, + EuiPageSection, + EuiSpacer, + EuiText, + EuiTitle, + EuiPanel, + EuiImage, +} from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import icon from '../../../assets/language_clients/es.svg'; + +const CenterColumn = styled(EuiFlexItem)` + max-width: 740px; +`; + +const FixedHeader = styled.div` + width: 100%; + height: 196px; + border-bottom: 1px solid ${euiThemeVars.euiColorLightShade}; +`; + +const IconPanel = styled(EuiPanel)` + padding: ${(props) => props.theme.eui.euiSizeXL}; + width: ${(props) => + parseFloat(props.theme.eui.euiSize) * 6 + parseFloat(props.theme.eui.euiSizeXL) * 2}px; + svg, + img { + height: ${(props) => parseFloat(props.theme.eui.euiSize) * 6}px; + width: ${(props) => parseFloat(props.theme.eui.euiSize) * 6}px; + } + .euiFlexItem { + height: ${(props) => parseFloat(props.theme.eui.euiSize) * 6}px; + justify-content: center; + } +`; + +const TopFlexGroup = styled(EuiFlexGroup)` + max-width: 1150px; + margin-left: auto; + margin-right: auto; + padding: calc(${euiThemeVars.euiSizeXL} * 2) ${euiThemeVars.euiSizeM} 0 ${euiThemeVars.euiSizeM}; +`; + +export const SampleClientReadme = () => { + const [apiKey, setApiKey] = useState(null); + + return ( + <> + + + + + + + + + +

+ +

+
+
+
+
+ + + + + + + + + + } + /> + + + + +

+ +

+
+ + + + + {`# Grab the sample language client from NPM and install it in your project \n`} + {`$ npm install @elastic/elasticsearch-sample`} + +
+ + + +

+ +

+
+ + + + + + + + + + setApiKey(cuid())} disabled={!!apiKey}> + Generate API key + + + + {apiKey && ( + + + {apiKey} + + + )} + +
+ + + +

+ +

+
+ + + elastic.config.json, + }} + /> + + + + + + {` +{ + "apiKey": "${apiKey || 'YOUR_API_KEY'} +} + + `} + +
+
+
+
+
+ + ); +}; diff --git a/src/plugins/custom_integrations/public/mocks.tsx b/src/plugins/custom_integrations/public/mocks.tsx index 038fdb1780458..2503008ea90ec 100644 --- a/src/plugins/custom_integrations/public/mocks.tsx +++ b/src/plugins/custom_integrations/public/mocks.tsx @@ -24,7 +24,7 @@ function createCustomIntegrationsStart(): jest.Mocked { const services = servicesFactory({ startPlugins: {}, coreStart: coreMock.createStart() }); return { - languageClientsUiComponents: new Map(), + languageClientsUiComponents: {}, ContextProvider: jest.fn(({ children }) => ( {children} diff --git a/src/plugins/custom_integrations/public/plugin.tsx b/src/plugins/custom_integrations/public/plugin.tsx index 90a796955a595..827d31ce3749d 100755 --- a/src/plugins/custom_integrations/public/plugin.tsx +++ b/src/plugins/custom_integrations/public/plugin.tsx @@ -19,12 +19,10 @@ import { ROUTES_APPEND_CUSTOM_INTEGRATIONS, ROUTES_REPLACEMENT_CUSTOM_INTEGRATIONS, } from '../common'; -import { languageIntegrations } from '../common/language_integrations'; - -import { OverviewComponent } from './components/fleet_integration/overview_component'; import { CustomIntegrationsServicesProvider } from './services'; import { servicesFactory } from './services/kibana'; +import { SampleClientReadme } from './components/fleet_integration/sample/sample_client_readme'; export class CustomIntegrationsPlugin implements Plugin @@ -48,16 +46,7 @@ export class CustomIntegrationsPlugin ): CustomIntegrationsStart { const services = servicesFactory({ coreStart, startPlugins }); - const languageClientsUiComponents = new Map(); - - // Set the language clients components to render in Fleet plugin under Integrations app - // Export component only if the integration has exportLanguageUiComponent = true - languageIntegrations - .filter((int) => int.exportLanguageUiComponent) - .map((int) => { - const ReadmeComponent = () => ; - languageClientsUiComponents.set(`language_client.${int.id}`, ReadmeComponent); - }); + const languageClientsUiComponents = { sample: SampleClientReadme }; const ContextProvider: React.FC = ({ children }) => ( diff --git a/src/plugins/custom_integrations/public/types.ts b/src/plugins/custom_integrations/public/types.ts index db8acc3e2e07e..60b8aefe23dd1 100755 --- a/src/plugins/custom_integrations/public/types.ts +++ b/src/plugins/custom_integrations/public/types.ts @@ -15,7 +15,7 @@ export interface CustomIntegrationsSetup { export interface CustomIntegrationsStart { ContextProvider: React.FC; - languageClientsUiComponents: Map; + languageClientsUiComponents: Record; } // eslint-disable-next-line @typescript-eslint/no-empty-interface diff --git a/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts b/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts deleted file mode 100644 index 3a6475b60251c..0000000000000 --- a/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { - ExtractDeps, - extractPanelsReferences, - InjectDeps, - injectPanelsReferences, -} from './embeddable_references'; -import { createEmbeddablePersistableStateServiceMock } from '@kbn/embeddable-plugin/common/mocks'; -import { SavedDashboardPanel } from '../types'; -import { EmbeddableStateWithType } from '@kbn/embeddable-plugin/common'; - -const embeddablePersistableStateService = createEmbeddablePersistableStateServiceMock(); -const deps: InjectDeps & ExtractDeps = { - embeddablePersistableStateService, -}; - -test('inject/extract panel references', () => { - embeddablePersistableStateService.extract.mockImplementationOnce((state) => { - const { HARDCODED_ID, ...restOfState } = state as unknown as Record; - return { - state: restOfState as EmbeddableStateWithType, - references: [{ id: HARDCODED_ID as string, name: 'refName', type: 'type' }], - }; - }); - - embeddablePersistableStateService.inject.mockImplementationOnce((state, references) => { - const ref = references.find((r) => r.name === 'refName'); - return { - ...state, - HARDCODED_ID: ref!.id, - }; - }); - - const savedDashboardPanel: SavedDashboardPanel = { - type: 'search', - embeddableConfig: { - HARDCODED_ID: 'IMPORTANT_HARDCODED_ID', - }, - id: 'savedObjectId', - panelIndex: '123', - gridData: { - x: 0, - y: 0, - h: 15, - w: 15, - i: '123', - }, - version: '7.0.0', - }; - - const [{ panel: extractedPanel, references }] = extractPanelsReferences( - [savedDashboardPanel], - deps - ); - expect(extractedPanel.embeddableConfig).toEqual({}); - expect(references).toMatchInlineSnapshot(` - Array [ - Object { - "id": "IMPORTANT_HARDCODED_ID", - "name": "refName", - "type": "type", - }, - ] - `); - - const [injectedPanel] = injectPanelsReferences([extractedPanel], references, deps); - - expect(injectedPanel).toEqual(savedDashboardPanel); -}); diff --git a/src/plugins/dashboard/common/embeddable/embeddable_references.ts b/src/plugins/dashboard/common/embeddable/embeddable_references.ts deleted file mode 100644 index 6664f70d3392a..0000000000000 --- a/src/plugins/dashboard/common/embeddable/embeddable_references.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { omit } from 'lodash'; -import { SavedObjectReference } from '@kbn/core/types'; -import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common/types'; -import { - convertSavedDashboardPanelToPanelState, - convertPanelStateToSavedDashboardPanel, -} from './embeddable_saved_object_converters'; -import { SavedDashboardPanel } from '../types'; - -export interface InjectDeps { - embeddablePersistableStateService: EmbeddablePersistableStateService; -} - -export function injectPanelsReferences( - panels: SavedDashboardPanel[], - references: SavedObjectReference[], - deps: InjectDeps -): SavedDashboardPanel[] { - const result: SavedDashboardPanel[] = []; - for (const panel of panels) { - const embeddableState = convertSavedDashboardPanelToPanelState(panel); - embeddableState.explicitInput = omit( - deps.embeddablePersistableStateService.inject( - { ...embeddableState.explicitInput, type: panel.type }, - references - ), - 'type' - ); - result.push(convertPanelStateToSavedDashboardPanel(embeddableState, panel.version)); - } - return result; -} - -export interface ExtractDeps { - embeddablePersistableStateService: EmbeddablePersistableStateService; -} - -export function extractPanelsReferences( - panels: SavedDashboardPanel[], - deps: ExtractDeps -): Array<{ panel: SavedDashboardPanel; references: SavedObjectReference[] }> { - const result: Array<{ panel: SavedDashboardPanel; references: SavedObjectReference[] }> = []; - - for (const panel of panels) { - const embeddable = convertSavedDashboardPanelToPanelState(panel); - const { state: embeddableInputWithExtractedReferences, references } = - deps.embeddablePersistableStateService.extract({ - ...embeddable.explicitInput, - type: embeddable.type, - }); - embeddable.explicitInput = omit(embeddableInputWithExtractedReferences, 'type'); - - const newPanel = convertPanelStateToSavedDashboardPanel(embeddable, panel.version); - result.push({ - panel: newPanel, - references, - }); - } - - return result; -} diff --git a/src/plugins/dashboard/common/index.ts b/src/plugins/dashboard/common/index.ts index 73e01693977d9..81833f8a8f18e 100644 --- a/src/plugins/dashboard/common/index.ts +++ b/src/plugins/dashboard/common/index.ts @@ -6,24 +6,28 @@ * Side Public License, v 1. */ -export type { GridData } from './embeddable/types'; -export type { - RawSavedDashboardPanel730ToLatest, - DashboardDoc730ToLatest, - DashboardDoc700To720, - DashboardDocPre700, -} from './bwc/types'; export type { + GridData, + DashboardPanelMap, + SavedDashboardPanel, + DashboardAttributes, + DashboardPanelState, DashboardContainerStateWithType, - SavedDashboardPanelTo60, - SavedDashboardPanel610, - SavedDashboardPanel620, - SavedDashboardPanel630, - SavedDashboardPanel640To720, - SavedDashboardPanel730ToLatest, } from './types'; -export { migratePanelsTo730 } from './migrate_to_730_panels'; +export { + injectReferences, + extractReferences, +} from './persistable_state/dashboard_saved_object_references'; + +export { createInject, createExtract } from './persistable_state/dashboard_container_references'; + +export { + convertPanelStateToSavedDashboardPanel, + convertSavedDashboardPanelToPanelState, + convertSavedPanelsToPanelMap, + convertPanelMapToSavedPanels, +} from './lib/dashboard_panel_converters'; export const UI_SETTINGS = { ENABLE_LABS_UI: 'labs:dashboard:enable_ui', diff --git a/src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.test.ts b/src/plugins/dashboard/common/lib/dashboard_panel_converters.test.ts similarity index 98% rename from src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.test.ts rename to src/plugins/dashboard/common/lib/dashboard_panel_converters.test.ts index 9ec93fa85fc54..2ebca116f3f12 100644 --- a/src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.test.ts +++ b/src/plugins/dashboard/common/lib/dashboard_panel_converters.test.ts @@ -9,7 +9,7 @@ import { convertSavedDashboardPanelToPanelState, convertPanelStateToSavedDashboardPanel, -} from './embeddable_saved_object_converters'; +} from './dashboard_panel_converters'; import { SavedDashboardPanel, DashboardPanelState } from '../types'; import { EmbeddableInput } from '@kbn/embeddable-plugin/common/types'; diff --git a/src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.ts b/src/plugins/dashboard/common/lib/dashboard_panel_converters.ts similarity index 75% rename from src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.ts rename to src/plugins/dashboard/common/lib/dashboard_panel_converters.ts index aa9519a5a48b9..2652c7f9a40a7 100644 --- a/src/plugins/dashboard/common/embeddable/embeddable_saved_object_converters.ts +++ b/src/plugins/dashboard/common/lib/dashboard_panel_converters.ts @@ -8,7 +8,7 @@ import { omit } from 'lodash'; import { EmbeddableInput, SavedObjectEmbeddableInput } from '@kbn/embeddable-plugin/common'; -import { DashboardPanelState, SavedDashboardPanel } from '../types'; +import { DashboardPanelMap, DashboardPanelState, SavedDashboardPanel } from '../types'; export function convertSavedDashboardPanelToPanelState< TEmbeddableInput extends EmbeddableInput | SavedObjectEmbeddableInput = SavedObjectEmbeddableInput @@ -42,3 +42,17 @@ export function convertPanelStateToSavedDashboardPanel( ...(panelState.panelRefName !== undefined && { panelRefName: panelState.panelRefName }), }; } + +export const convertSavedPanelsToPanelMap = (panels?: SavedDashboardPanel[]): DashboardPanelMap => { + const panelsMap: DashboardPanelMap = {}; + panels?.forEach((panel, idx) => { + panelsMap![panel.panelIndex ?? String(idx)] = convertSavedDashboardPanelToPanelState(panel); + }); + return panelsMap; +}; + +export const convertPanelMapToSavedPanels = (panels: DashboardPanelMap, version: string) => { + return Object.values(panels).map((panel) => + convertPanelStateToSavedDashboardPanel(panel, version) + ); +}; diff --git a/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts b/src/plugins/dashboard/common/persistable_state/dashboard_container_references.test.ts similarity index 99% rename from src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts rename to src/plugins/dashboard/common/persistable_state/dashboard_container_references.test.ts index ee13926486f8b..47215e5e32008 100644 --- a/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts +++ b/src/plugins/dashboard/common/persistable_state/dashboard_container_references.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { createExtract, createInject } from './dashboard_container_persistable_state'; +import { createExtract, createInject } from './dashboard_container_references'; import { createEmbeddablePersistableStateServiceMock } from '@kbn/embeddable-plugin/common/mocks'; import { DashboardContainerStateWithType } from '../types'; diff --git a/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.ts b/src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts similarity index 100% rename from src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.ts rename to src/plugins/dashboard/common/persistable_state/dashboard_container_references.ts diff --git a/src/plugins/dashboard/common/saved_dashboard_references.test.ts b/src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.test.ts similarity index 98% rename from src/plugins/dashboard/common/saved_dashboard_references.test.ts rename to src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.test.ts index 84bfe6ea48d3a..e28a429d6d004 100644 --- a/src/plugins/dashboard/common/saved_dashboard_references.test.ts +++ b/src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.test.ts @@ -11,9 +11,9 @@ import { injectReferences, InjectDeps, ExtractDeps, -} from './saved_dashboard_references'; +} from './dashboard_saved_object_references'; -import { createExtract, createInject } from './embeddable/dashboard_container_persistable_state'; +import { createExtract, createInject } from './dashboard_container_references'; import { createEmbeddablePersistableStateServiceMock } from '@kbn/embeddable-plugin/common/mocks'; const embeddablePersistableStateServiceMock = createEmbeddablePersistableStateServiceMock(); diff --git a/src/plugins/dashboard/common/saved_dashboard_references.ts b/src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts similarity index 96% rename from src/plugins/dashboard/common/saved_dashboard_references.ts rename to src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts index e3a3193dd85a1..a3126a381d944 100644 --- a/src/plugins/dashboard/common/saved_dashboard_references.ts +++ b/src/plugins/dashboard/common/persistable_state/dashboard_saved_object_references.ts @@ -6,23 +6,33 @@ * Side Public License, v 1. */ import semverGt from 'semver/functions/gt'; -import { SavedObjectAttributes, SavedObjectReference } from '@kbn/core/types'; -import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common/types'; + import { - PersistableControlGroupInput, RawControlGroupAttributes, + PersistableControlGroupInput, } from '@kbn/controls-plugin/common'; -import { DashboardContainerStateWithType, DashboardPanelState } from './types'; +import { SavedObjectAttributes, SavedObjectReference } from '@kbn/core/types'; +import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common/types'; + +import { + SavedDashboardPanel, + DashboardPanelState, + DashboardContainerStateWithType, +} from '../types'; import { convertPanelStateToSavedDashboardPanel, convertSavedDashboardPanelToPanelState, -} from './embeddable/embeddable_saved_object_converters'; -import { SavedDashboardPanel } from './types'; +} from '../lib/dashboard_panel_converters'; export interface ExtractDeps { embeddablePersistableStateService: EmbeddablePersistableStateService; } -export interface SavedObjectAttributesAndReferences { + +export interface InjectDeps { + embeddablePersistableStateService: EmbeddablePersistableStateService; +} + +interface SavedObjectAttributesAndReferences { attributes: SavedObjectAttributes; references: SavedObjectReference[]; } @@ -79,7 +89,7 @@ function panelStatesToPanels( let originalPanel = originalPanels.find((p) => p.panelIndex === id); if (!originalPanel) { - // Maybe original panel doesn't have a panel index and it's just straight up based on it's index + // Maybe original panel doesn't have a panel index and it's just straight up based on its index const numericId = parseInt(id, 10); originalPanel = isNaN(numericId) ? originalPanel : originalPanels[numericId]; } @@ -91,6 +101,45 @@ function panelStatesToPanels( }); } +export function injectReferences( + { attributes, references = [] }: SavedObjectAttributesAndReferences, + deps: InjectDeps +): SavedObjectAttributes { + // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when + // importing objects without panelsJSON. At development time of this, there is no guarantee each saved + // object has panelsJSON in all previous versions of kibana. + if (typeof attributes.panelsJSON !== 'string') { + return attributes; + } + const parsedPanels = JSON.parse(attributes.panelsJSON); + // Same here, prevent failing saved object import if ever panels aren't an array. + if (!Array.isArray(parsedPanels)) { + return attributes; + } + + const { panels, state } = dashboardAttributesToState(attributes); + + const injectedState = deps.embeddablePersistableStateService.inject( + state, + references + ) as DashboardContainerStateWithType; + const injectedPanels = panelStatesToPanels(injectedState.panels, panels); + + const newAttributes = { + ...attributes, + panelsJSON: JSON.stringify(injectedPanels), + } as SavedObjectAttributes; + + if (injectedState.controlGroupInput) { + newAttributes.controlGroupInput = { + ...(attributes.controlGroupInput as SavedObjectAttributes), + panelsJSON: JSON.stringify(injectedState.controlGroupInput.panels), + }; + } + + return newAttributes; +} + export function extractReferences( { attributes, references = [] }: SavedObjectAttributesAndReferences, deps: ExtractDeps @@ -137,49 +186,6 @@ export function extractReferences( }; } -export interface InjectDeps { - embeddablePersistableStateService: EmbeddablePersistableStateService; -} - -export function injectReferences( - { attributes, references = [] }: SavedObjectAttributesAndReferences, - deps: InjectDeps -): SavedObjectAttributes { - // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when - // importing objects without panelsJSON. At development time of this, there is no guarantee each saved - // object has panelsJSON in all previous versions of kibana. - if (typeof attributes.panelsJSON !== 'string') { - return attributes; - } - const parsedPanels = JSON.parse(attributes.panelsJSON); - // Same here, prevent failing saved object import if ever panels aren't an array. - if (!Array.isArray(parsedPanels)) { - return attributes; - } - - const { panels, state } = dashboardAttributesToState(attributes); - - const injectedState = deps.embeddablePersistableStateService.inject( - state, - references - ) as DashboardContainerStateWithType; - const injectedPanels = panelStatesToPanels(injectedState.panels, panels); - - const newAttributes = { - ...attributes, - panelsJSON: JSON.stringify(injectedPanels), - } as SavedObjectAttributes; - - if (injectedState.controlGroupInput) { - newAttributes.controlGroupInput = { - ...(attributes.controlGroupInput as SavedObjectAttributes), - panelsJSON: JSON.stringify(injectedState.controlGroupInput.panels), - }; - } - - return newAttributes; -} - function pre730ExtractReferences( { attributes, references = [] }: SavedObjectAttributesAndReferences, deps: ExtractDeps diff --git a/src/plugins/dashboard/common/types.ts b/src/plugins/dashboard/common/types.ts index 941f9437e54e6..ff5a1cbc17552 100644 --- a/src/plugins/dashboard/common/types.ts +++ b/src/plugins/dashboard/common/types.ts @@ -11,28 +11,13 @@ import { EmbeddableStateWithType, PanelState, } from '@kbn/embeddable-plugin/common/types'; -import { SavedObjectEmbeddableInput } from '@kbn/embeddable-plugin/common/lib/saved_object_embeddable'; -import { PersistableControlGroupInput } from '@kbn/controls-plugin/common'; +import { Serializable } from '@kbn/utility-types'; import { - RawSavedDashboardPanelTo60, - RawSavedDashboardPanel610, - RawSavedDashboardPanel620, - RawSavedDashboardPanel630, - RawSavedDashboardPanel640To720, - RawSavedDashboardPanel730ToLatest, -} from './bwc/types'; - -import { GridData } from './embeddable/types'; - -export type PanelId = string; -export type SavedObjectId = string; - -export interface DashboardPanelState< - TEmbeddableInput extends EmbeddableInput | SavedObjectEmbeddableInput = SavedObjectEmbeddableInput -> extends PanelState { - readonly gridData: GridData; - panelRefName?: string; -} + PersistableControlGroupInput, + RawControlGroupAttributes, +} from '@kbn/controls-plugin/common'; +import { RefreshInterval } from '@kbn/data-plugin/common'; +import { SavedObjectEmbeddableInput } from '@kbn/embeddable-plugin/common/lib/saved_object_embeddable'; export interface DashboardCapabilities { showWriteControls: boolean; @@ -43,62 +28,77 @@ export interface DashboardCapabilities { } /** - * This should always represent the latest dashboard panel shape, after all possible migrations. + * The attributes of the dashboard saved object. This interface should be the + * source of truth for the latest dashboard attributes shape after all migrations. */ -export type SavedDashboardPanel = SavedDashboardPanel730ToLatest; - -export type SavedDashboardPanel640To720 = Pick< - RawSavedDashboardPanel640To720, - Exclude -> & { - readonly id: string; - readonly type: string; -}; +export interface DashboardAttributes { + controlGroupInput?: RawControlGroupAttributes; + refreshInterval?: RefreshInterval; + timeRestore: boolean; + optionsJSON?: string; + useMargins?: boolean; + description: string; + panelsJSON: string; + timeFrom?: string; + version: number; + timeTo?: string; + title: string; + kibanaSavedObjectMeta: { + searchSourceJSON: string; + }; +} -export type SavedDashboardPanel630 = Pick< - RawSavedDashboardPanel630, - Exclude -> & { - readonly id: string; - readonly type: string; -}; +/** -------------------------------------------------------------------- + * Dashboard panel types + -----------------------------------------------------------------------*/ -export type SavedDashboardPanel620 = Pick< - RawSavedDashboardPanel620, - Exclude -> & { - readonly id: string; - readonly type: string; -}; +/** + * The dashboard panel format expected by the embeddable container. + */ +export interface DashboardPanelState< + TEmbeddableInput extends EmbeddableInput | SavedObjectEmbeddableInput = SavedObjectEmbeddableInput +> extends PanelState { + readonly gridData: GridData; + panelRefName?: string; +} -export type SavedDashboardPanel610 = Pick< - RawSavedDashboardPanel610, - Exclude -> & { - readonly id: string; - readonly type: string; -}; +/** + * A saved dashboard panel parsed directly from the Dashboard Attributes panels JSON + */ +export interface SavedDashboardPanel { + embeddableConfig: { [key: string]: Serializable }; // parsed into the panel's explicitInput + id?: string; // the saved object id for by reference panels + type: string; // the embeddable type + panelRefName?: string; + gridData: GridData; + panelIndex: string; + version: string; + title?: string; +} -export type SavedDashboardPanelTo60 = Pick< - RawSavedDashboardPanelTo60, - Exclude -> & { - readonly id: string; - readonly type: string; -}; +/** + * Grid type for React Grid Layout + */ +export interface GridData { + w: number; + h: number; + x: number; + y: number; + i: string; +} -// id becomes optional starting in 7.3.0 -export type SavedDashboardPanel730ToLatest = Pick< - RawSavedDashboardPanel730ToLatest, - Exclude -> & { - readonly id?: string; - readonly type: string; -}; +export interface DashboardPanelMap { + [key: string]: DashboardPanelState; +} -// Making this interface because so much of the Container type from embeddable is tied up in public -// Once that is all available from common, we should be able to move the dashboard_container type to our common as well +/** -------------------------------------------------------------------- + * Dashboard container types + -----------------------------------------------------------------------*/ +/** + * Types below this line are copied here because so many important types are tied up in public. These types should be + * moved from public into common. + */ export interface DashboardContainerStateWithType extends EmbeddableStateWithType { panels: { [panelId: string]: DashboardPanelState; diff --git a/src/plugins/dashboard/public/application/actions/add_to_library_action.test.tsx b/src/plugins/dashboard/public/application/actions/add_to_library_action.test.tsx index ac467e35729f8..aa3419e37890c 100644 --- a/src/plugins/dashboard/public/application/actions/add_to_library_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/add_to_library_action.test.tsx @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { AddToLibraryAction } from '.'; import { DashboardContainer } from '../embeddable/dashboard_container'; import { getSampleDashboardInput } from '../test_helpers'; import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; @@ -27,6 +26,7 @@ import { CONTACT_CARD_EMBEDDABLE, } from '@kbn/embeddable-plugin/public/lib/test_samples/embeddables'; import { pluginServices } from '../../services/plugin_services'; +import { AddToLibraryAction } from './add_to_library_action'; const embeddableFactory = new ContactCardEmbeddableFactory((() => null) as any, {} as any); pluginServices.getServices().embeddable.getEmbeddableFactory = jest diff --git a/src/plugins/dashboard/public/application/actions/add_to_library_action.tsx b/src/plugins/dashboard/public/application/actions/add_to_library_action.tsx index 8c6577012161d..0510d35519ff2 100644 --- a/src/plugins/dashboard/public/application/actions/add_to_library_action.tsx +++ b/src/plugins/dashboard/public/application/actions/add_to_library_action.tsx @@ -18,8 +18,9 @@ import { import { Action, IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; import { dashboardAddToLibraryAction } from '../../dashboard_strings'; -import { type DashboardPanelState, DASHBOARD_CONTAINER_TYPE, type DashboardContainer } from '..'; +import { type DashboardPanelState, type DashboardContainer } from '..'; import { pluginServices } from '../../services/plugin_services'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; export const ACTION_ADD_TO_LIBRARY = 'saveToLibrary'; diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx index 5bb331e58fe38..0fb63049ebe32 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx @@ -12,7 +12,7 @@ import { getSampleDashboardInput, getSampleDashboardPanel } from '../test_helper import { coreMock } from '@kbn/core/public/mocks'; import { CoreStart } from '@kbn/core/public'; -import { ClonePanelAction } from '.'; +import { ClonePanelAction } from './clone_panel_action'; import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; import { ContactCardEmbeddable, diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx index 02862e7c75e86..11a96733337f0 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx @@ -27,9 +27,10 @@ import { placePanelBeside, IPanelPlacementBesideArgs, } from '../embeddable/panel/dashboard_panel_placement'; -import { dashboardClonePanelAction } from '../../dashboard_strings'; -import { type DashboardPanelState, DASHBOARD_CONTAINER_TYPE, type DashboardContainer } from '..'; import { pluginServices } from '../../services/plugin_services'; +import { dashboardClonePanelAction } from '../../dashboard_strings'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; +import { type DashboardPanelState, type DashboardContainer } from '..'; export const ACTION_CLONE_PANEL = 'clonePanel'; diff --git a/src/plugins/dashboard/public/application/actions/copy_to_dashboard_action.tsx b/src/plugins/dashboard/public/application/actions/copy_to_dashboard_action.tsx index 8f602db5e4529..cdd8d726e9fa6 100644 --- a/src/plugins/dashboard/public/application/actions/copy_to_dashboard_action.tsx +++ b/src/plugins/dashboard/public/application/actions/copy_to_dashboard_action.tsx @@ -14,9 +14,10 @@ import type { IEmbeddable } from '@kbn/embeddable-plugin/public'; import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public'; import { dashboardCopyToDashboardAction } from '../../dashboard_strings'; -import { DASHBOARD_CONTAINER_TYPE, DashboardContainer } from '../embeddable'; +import { DashboardContainer } from '../embeddable'; import { CopyToDashboardModal } from './copy_to_dashboard_modal'; import { pluginServices } from '../../services/plugin_services'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; export const ACTION_COPY_TO_DASHBOARD = 'copyToDashboard'; diff --git a/src/plugins/dashboard/public/application/actions/copy_to_dashboard_modal.tsx b/src/plugins/dashboard/public/application/actions/copy_to_dashboard_modal.tsx index 7f9a99ed27231..af91631d20b39 100644 --- a/src/plugins/dashboard/public/application/actions/copy_to_dashboard_modal.tsx +++ b/src/plugins/dashboard/public/application/actions/copy_to_dashboard_modal.tsx @@ -25,8 +25,8 @@ import { import { IEmbeddable, PanelNotFoundError } from '@kbn/embeddable-plugin/public'; import { LazyDashboardPicker, withSuspense } from '@kbn/presentation-util-plugin/public'; import { dashboardCopyToDashboardAction } from '../../dashboard_strings'; -import { createDashboardEditUrl, DashboardConstants, DashboardContainer } from '../..'; -import { DashboardPanelState } from '..'; +import { createDashboardEditUrl, DashboardConstants } from '../..'; +import { type DashboardContainer, DashboardPanelState } from '..'; import { pluginServices } from '../../services/plugin_services'; interface CopyToDashboardModalProps { diff --git a/src/plugins/dashboard/public/application/actions/expand_panel_action.tsx b/src/plugins/dashboard/public/application/actions/expand_panel_action.tsx index c5da566b90a6a..79ab109ddce51 100644 --- a/src/plugins/dashboard/public/application/actions/expand_panel_action.tsx +++ b/src/plugins/dashboard/public/application/actions/expand_panel_action.tsx @@ -9,9 +9,9 @@ import type { IEmbeddable } from '@kbn/embeddable-plugin/public'; import { Action, IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; -import type { DashboardContainerInput } from '../..'; +import { DashboardContainerInput, DASHBOARD_CONTAINER_TYPE } from '../..'; import { dashboardExpandPanelAction } from '../../dashboard_strings'; -import { DASHBOARD_CONTAINER_TYPE, type DashboardContainer } from '../embeddable'; +import { type DashboardContainer } from '../embeddable'; export const ACTION_EXPAND_PANEL = 'togglePanel'; diff --git a/src/plugins/dashboard/public/application/actions/filters_notification_badge.test.tsx b/src/plugins/dashboard/public/application/actions/filters_notification_badge.test.tsx index 275a5625e5e0b..3b3fb5dde0497 100644 --- a/src/plugins/dashboard/public/application/actions/filters_notification_badge.test.tsx +++ b/src/plugins/dashboard/public/application/actions/filters_notification_badge.test.tsx @@ -6,27 +6,26 @@ * Side Public License, v 1. */ -import { getSampleDashboardInput } from '../test_helpers'; -import { DashboardContainer } from '../embeddable/dashboard_container'; - -import { FiltersNotificationBadge } from '.'; -import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; -import { type Query, type AggregateQuery, Filter } from '@kbn/es-query'; import { - ErrorEmbeddable, - FilterableEmbeddable, IContainer, + ErrorEmbeddable, isErrorEmbeddable, + FilterableEmbeddable, } from '@kbn/embeddable-plugin/public'; - import { ContactCardEmbeddable, - ContactCardEmbeddableFactory, + CONTACT_CARD_EMBEDDABLE, ContactCardEmbeddableInput, ContactCardEmbeddableOutput, - CONTACT_CARD_EMBEDDABLE, + ContactCardEmbeddableFactory, } from '@kbn/embeddable-plugin/public/lib/test_samples/embeddables'; +import { type Query, type AggregateQuery, Filter } from '@kbn/es-query'; +import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; + +import { getSampleDashboardInput } from '../test_helpers'; import { pluginServices } from '../../services/plugin_services'; +import { DashboardContainer } from '../embeddable/dashboard_container'; +import { FiltersNotificationBadge } from './filters_notification_badge'; const mockEmbeddableFactory = new ContactCardEmbeddableFactory((() => null) as any, {} as any); pluginServices.getServices().embeddable.getEmbeddableFactory = jest diff --git a/src/plugins/dashboard/public/application/actions/index.ts b/src/plugins/dashboard/public/application/actions/index.ts index 5c95e3c42cccd..a238ce05e1017 100644 --- a/src/plugins/dashboard/public/application/actions/index.ts +++ b/src/plugins/dashboard/public/application/actions/index.ts @@ -6,23 +6,76 @@ * Side Public License, v 1. */ -export type { ExpandPanelActionContext } from './expand_panel_action'; -export { ExpandPanelAction, ACTION_EXPAND_PANEL } from './expand_panel_action'; -export type { ReplacePanelActionContext } from './replace_panel_action'; -export { ReplacePanelAction, ACTION_REPLACE_PANEL } from './replace_panel_action'; -export type { ClonePanelActionContext } from './clone_panel_action'; -export { ClonePanelAction, ACTION_CLONE_PANEL } from './clone_panel_action'; -export type { AddToLibraryActionContext } from './add_to_library_action'; -export { AddToLibraryAction, ACTION_ADD_TO_LIBRARY } from './add_to_library_action'; -export type { UnlinkFromLibraryActionContext } from './unlink_from_library_action'; -export { UnlinkFromLibraryAction, ACTION_UNLINK_FROM_LIBRARY } from './unlink_from_library_action'; -export type { CopyToDashboardActionContext } from './copy_to_dashboard_action'; -export { CopyToDashboardAction, ACTION_COPY_TO_DASHBOARD } from './copy_to_dashboard_action'; -export type { LibraryNotificationActionContext } from './library_notification_action'; -export { - LibraryNotificationAction, - ACTION_LIBRARY_NOTIFICATION, -} from './library_notification_action'; -export { FiltersNotificationBadge, BADGE_FILTERS_NOTIFICATION } from './filters_notification_badge'; -export type { ExportContext } from './export_csv_action'; -export { ExportCSVAction, ACTION_EXPORT_CSV } from './export_csv_action'; +import { + CONTEXT_MENU_TRIGGER, + PANEL_BADGE_TRIGGER, + PANEL_NOTIFICATION_TRIGGER, +} from '@kbn/embeddable-plugin/public'; +import { CoreStart } from '@kbn/core/public'; +import { getSavedObjectFinder } from '@kbn/saved-objects-plugin/public'; + +import { ExportCSVAction } from './export_csv_action'; +import { ClonePanelAction } from './clone_panel_action'; +import { DashboardStartDependencies } from '../../plugin'; +import { ExpandPanelAction } from './expand_panel_action'; +import { ReplacePanelAction } from './replace_panel_action'; +import { AddToLibraryAction } from './add_to_library_action'; +import { CopyToDashboardAction } from './copy_to_dashboard_action'; +import { UnlinkFromLibraryAction } from './unlink_from_library_action'; +import { FiltersNotificationBadge } from './filters_notification_badge'; +import { LibraryNotificationAction } from './library_notification_action'; + +interface BuildAllDashboardActionsProps { + core: CoreStart; + allowByValueEmbeddables?: boolean; + plugins: DashboardStartDependencies; +} + +export const buildAllDashboardActions = async ({ + core, + plugins, + allowByValueEmbeddables, +}: BuildAllDashboardActionsProps) => { + const { uiSettings } = core; + const { uiActions, share, presentationUtil } = plugins; + + const clonePanelAction = new ClonePanelAction(core.savedObjects); + uiActions.registerAction(clonePanelAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, clonePanelAction.id); + + const SavedObjectFinder = getSavedObjectFinder(core.savedObjects, uiSettings); + const changeViewAction = new ReplacePanelAction(SavedObjectFinder); + uiActions.registerAction(changeViewAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, changeViewAction.id); + + const panelLevelFiltersNotification = new FiltersNotificationBadge(); + uiActions.registerAction(panelLevelFiltersNotification); + uiActions.attachAction(PANEL_BADGE_TRIGGER, panelLevelFiltersNotification.id); + + const expandPanelAction = new ExpandPanelAction(); + uiActions.registerAction(expandPanelAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, expandPanelAction.id); + + if (share) { + const ExportCSVPlugin = new ExportCSVAction(); + uiActions.addTriggerAction(CONTEXT_MENU_TRIGGER, ExportCSVPlugin); + } + + if (allowByValueEmbeddables) { + const addToLibraryAction = new AddToLibraryAction(); + uiActions.registerAction(addToLibraryAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, addToLibraryAction.id); + + const unlinkFromLibraryAction = new UnlinkFromLibraryAction(); + uiActions.registerAction(unlinkFromLibraryAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, unlinkFromLibraryAction.id); + + const libraryNotificationAction = new LibraryNotificationAction(unlinkFromLibraryAction); + uiActions.registerAction(libraryNotificationAction); + uiActions.attachAction(PANEL_NOTIFICATION_TRIGGER, libraryNotificationAction.id); + + const copyToDashboardAction = new CopyToDashboardAction(presentationUtil.ContextProvider); + uiActions.registerAction(copyToDashboardAction); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, copyToDashboardAction.id); + } +}; diff --git a/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx b/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx index f1202de4ac1b6..f30cba538b8d1 100644 --- a/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx @@ -6,11 +6,6 @@ * Side Public License, v 1. */ -import { getSampleDashboardInput } from '../test_helpers'; -import { DashboardContainer } from '../embeddable/dashboard_container'; - -import { LibraryNotificationAction, UnlinkFromLibraryAction } from '.'; -import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; import { ErrorEmbeddable, IContainer, @@ -25,7 +20,13 @@ import { ContactCardEmbeddableOutput, CONTACT_CARD_EMBEDDABLE, } from '@kbn/embeddable-plugin/public/lib/test_samples/embeddables'; +import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks'; + +import { getSampleDashboardInput } from '../test_helpers'; import { pluginServices } from '../../services/plugin_services'; +import { DashboardContainer } from '../embeddable/dashboard_container'; +import { UnlinkFromLibraryAction } from './unlink_from_library_action'; +import { LibraryNotificationAction } from './library_notification_action'; const mockEmbeddableFactory = new ContactCardEmbeddableFactory((() => null) as any, {} as any); pluginServices.getServices().embeddable.getEmbeddableFactory = jest diff --git a/src/plugins/dashboard/public/application/actions/library_notification_action.tsx b/src/plugins/dashboard/public/application/actions/library_notification_action.tsx index a5abe8161e9ad..a05b78994b31d 100644 --- a/src/plugins/dashboard/public/application/actions/library_notification_action.tsx +++ b/src/plugins/dashboard/public/application/actions/library_notification_action.tsx @@ -17,10 +17,10 @@ import { import { KibanaThemeProvider, reactToUiComponent } from '@kbn/kibana-react-plugin/public'; import { Action, IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; -import { UnlinkFromLibraryAction } from '.'; -import { LibraryNotificationPopover } from './library_notification_popover'; -import { dashboardLibraryNotification } from '../../dashboard_strings'; import { pluginServices } from '../../services/plugin_services'; +import { UnlinkFromLibraryAction } from './unlink_from_library_action'; +import { dashboardLibraryNotification } from '../../dashboard_strings'; +import { LibraryNotificationPopover } from './library_notification_popover'; export const ACTION_LIBRARY_NOTIFICATION = 'ACTION_LIBRARY_NOTIFICATION'; diff --git a/src/plugins/dashboard/public/application/actions/library_notification_popover.tsx b/src/plugins/dashboard/public/application/actions/library_notification_popover.tsx index 81d2f2a0557ec..38c8452eadde5 100644 --- a/src/plugins/dashboard/public/application/actions/library_notification_popover.tsx +++ b/src/plugins/dashboard/public/application/actions/library_notification_popover.tsx @@ -17,8 +17,10 @@ import { EuiPopoverTitle, EuiText, } from '@elastic/eui'; -import { LibraryNotificationActionContext, UnlinkFromLibraryAction } from '.'; + import { dashboardLibraryNotification } from '../../dashboard_strings'; +import { UnlinkFromLibraryAction } from './unlink_from_library_action'; +import { LibraryNotificationActionContext } from './library_notification_action'; export interface LibraryNotificationProps { context: LibraryNotificationActionContext; diff --git a/src/plugins/dashboard/public/application/actions/replace_panel_action.tsx b/src/plugins/dashboard/public/application/actions/replace_panel_action.tsx index f39988842e3fc..52f6a345a181e 100644 --- a/src/plugins/dashboard/public/application/actions/replace_panel_action.tsx +++ b/src/plugins/dashboard/public/application/actions/replace_panel_action.tsx @@ -8,9 +8,10 @@ import { type IEmbeddable, ViewMode } from '@kbn/embeddable-plugin/public'; import { Action, IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; -import { DASHBOARD_CONTAINER_TYPE, type DashboardContainer } from '../embeddable'; +import type { DashboardContainer } from '../embeddable'; import { openReplacePanelFlyout } from './open_replace_panel_flyout'; import { dashboardReplacePanelAction } from '../../dashboard_strings'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; export const ACTION_REPLACE_PANEL = 'replacePanel'; diff --git a/src/plugins/dashboard/public/application/actions/unlink_from_library_action.test.tsx b/src/plugins/dashboard/public/application/actions/unlink_from_library_action.test.tsx index 854383edd4e14..080c358a86fdf 100644 --- a/src/plugins/dashboard/public/application/actions/unlink_from_library_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/unlink_from_library_action.test.tsx @@ -23,10 +23,10 @@ import { CONTACT_CARD_EMBEDDABLE, } from '@kbn/embeddable-plugin/public/lib/test_samples/embeddables'; -import { UnlinkFromLibraryAction } from '.'; import { getSampleDashboardInput } from '../test_helpers'; -import { DashboardContainer } from '../embeddable/dashboard_container'; import { pluginServices } from '../../services/plugin_services'; +import { UnlinkFromLibraryAction } from './unlink_from_library_action'; +import { DashboardContainer } from '../embeddable/dashboard_container'; let container: DashboardContainer; let embeddable: ContactCardEmbeddable & ReferenceOrValueEmbeddable; diff --git a/src/plugins/dashboard/public/application/actions/unlink_from_library_action.tsx b/src/plugins/dashboard/public/application/actions/unlink_from_library_action.tsx index e399411e77fee..b7c53a78becc2 100644 --- a/src/plugins/dashboard/public/application/actions/unlink_from_library_action.tsx +++ b/src/plugins/dashboard/public/application/actions/unlink_from_library_action.tsx @@ -17,8 +17,9 @@ import { } from '@kbn/embeddable-plugin/public'; import { Action, IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; import { dashboardUnlinkFromLibraryAction } from '../../dashboard_strings'; -import { type DashboardPanelState, DASHBOARD_CONTAINER_TYPE, type DashboardContainer } from '..'; +import { type DashboardPanelState, type DashboardContainer } from '..'; import { pluginServices } from '../../services/plugin_services'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; export const ACTION_UNLINK_FROM_LIBRARY = 'unlinkFromLibrary'; diff --git a/src/plugins/dashboard/public/application/dashboard_app.tsx b/src/plugins/dashboard/public/application/dashboard_app.tsx index 302cb43794229..b05944c99292b 100644 --- a/src/plugins/dashboard/public/application/dashboard_app.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app.tsx @@ -9,24 +9,23 @@ import { History } from 'history'; import React, { useEffect, useMemo, useRef, useState } from 'react'; -import { EmbeddableRenderer, ViewMode } from '@kbn/embeddable-plugin/public'; import { useExecutionContext } from '@kbn/kibana-react-plugin/public'; +import { EmbeddableRenderer, ViewMode } from '@kbn/embeddable-plugin/public'; import { createKbnUrlStateStorage, withNotifyOnErrors } from '@kbn/kibana-utils-plugin/public'; -import { useDashboardSelector } from './state'; -import { useDashboardAppState } from './hooks'; import { dashboardFeatureCatalog, getDashboardBreadcrumb, getDashboardTitle, leaveConfirmStrings, } from '../dashboard_strings'; -import { createDashboardEditUrl } from '../dashboard_constants'; -import { DashboardTopNav, isCompleteDashboardAppState } from './top_nav/dashboard_top_nav'; -import { DashboardEmbedSettings, DashboardRedirect } from '../types'; -import { DashboardAppNoDataPage } from './dashboard_app_no_data'; +import { useDashboardAppState } from './hooks'; +import { useDashboardSelector } from './state'; import { pluginServices } from '../services/plugin_services'; +import { DashboardAppNoDataPage } from './dashboard_app_no_data'; +import { DashboardEmbedSettings, DashboardRedirect } from '../types'; import { useDashboardMountContext } from './hooks/dashboard_mount_context'; +import { DashboardTopNav, isCompleteDashboardAppState } from './top_nav/dashboard_top_nav'; export interface DashboardAppProps { history: History; savedDashboardId?: string; @@ -43,13 +42,12 @@ export function DashboardApp({ const { onAppLeave } = useDashboardMountContext(); const { chrome: { setBreadcrumbs, setIsVisible }, + screenshotMode: { isScreenshotMode }, coreContext: { executionContext }, - data: { search }, embeddable: { getStateTransfer }, notifications: { toasts }, - screenshotMode: { isScreenshotMode }, settings: { uiSettings }, - spaces: { getLegacyUrlConflict }, + data: { search }, } = pluginServices.getServices(); const [showNoDataPage, setShowNoDataPage] = useState(false); @@ -160,17 +158,7 @@ export function DashboardApp({ dashboardAppState={dashboardAppState} /> - {dashboardAppState.savedDashboard.outcome === 'conflict' && - dashboardAppState.savedDashboard.id && - dashboardAppState.savedDashboard.aliasId - ? getLegacyUrlConflict?.({ - currentObjectId: dashboardAppState.savedDashboard.id, - otherObjectId: dashboardAppState.savedDashboard.aliasId, - otherObjectPath: `#${createDashboardEditUrl( - dashboardAppState.savedDashboard.aliasId - )}${history.location.search}`, - }) - : null} + {dashboardAppState.createConflictWarning?.()}
createKbnUrlStateStorage({ history, @@ -172,51 +162,48 @@ export async function mountApp({ core, element, appUnMounted, mountContext }: Da }); const app = ( - // TODO: Remove KibanaContextProvider as part of https://github.com/elastic/kibana/pull/138774 - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + ); diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx index 4f7483cf06f35..036c77fc6257c 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx @@ -32,7 +32,7 @@ import type { Query } from '@kbn/es-query'; import type { RefreshInterval } from '@kbn/data-plugin/public'; import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; -import { DASHBOARD_CONTAINER_TYPE } from './dashboard_constants'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; import { createPanelState } from './panel'; import { DashboardPanelState } from './types'; import { DashboardViewport } from './viewport/dashboard_viewport'; diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx index 27670ee104367..58a2c63492c09 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx @@ -7,16 +7,14 @@ */ import { i18n } from '@kbn/i18n'; -import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common'; - import { identity, pickBy } from 'lodash'; + import { ControlGroupContainer, ControlGroupInput, ControlGroupOutput, CONTROL_GROUP_TYPE, } from '@kbn/controls-plugin/public'; -import { getDefaultControlGroupInput } from '@kbn/controls-plugin/common'; import { Container, ErrorEmbeddable, @@ -25,14 +23,13 @@ import { EmbeddableFactoryDefinition, } from '@kbn/embeddable-plugin/public'; +import { getDefaultControlGroupInput } from '@kbn/controls-plugin/common'; +import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common'; + import { DashboardContainerInput } from '../..'; -import { DASHBOARD_CONTAINER_TYPE } from './dashboard_constants'; +import { createExtract, createInject } from '../../../common'; import type { DashboardContainer } from './dashboard_container'; -import { - createExtract, - createInject, -} from '../../../common/embeddable/dashboard_container_persistable_state'; -import { pluginServices } from '../../services/plugin_services'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; export type DashboardContainerFactory = EmbeddableFactory< DashboardContainerInput, @@ -80,6 +77,7 @@ export class DashboardContainerFactoryDefinition initialInput: DashboardContainerInput, parent?: Container ): Promise => { + const { pluginServices } = await import('../../services/plugin_services'); const { embeddable: { getEmbeddableFactory }, } = pluginServices.getServices(); diff --git a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx index 64afdcdb2e609..7fda6eb1a3f35 100644 --- a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx +++ b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx @@ -22,9 +22,9 @@ import { DashboardContainer, DashboardLoadedInfo } from '../dashboard_container' import { GridData } from '../../../../common'; import { DashboardGridItem } from './dashboard_grid_item'; import { DashboardLoadedEventStatus, DashboardPanelState } from '../types'; -import { DASHBOARD_GRID_COLUMN_COUNT, DASHBOARD_GRID_HEIGHT } from '../dashboard_constants'; +import { DASHBOARD_GRID_COLUMN_COUNT, DASHBOARD_GRID_HEIGHT } from '../../../dashboard_constants'; import { pluginServices } from '../../../services/plugin_services'; -import { dashboardLoadingErrorStrings } from '../../../dashboard_strings'; +import { dashboardSavedObjectErrorStrings } from '../../../dashboard_strings'; let lastValidGridSize = 0; @@ -153,7 +153,7 @@ class DashboardGridUi extends React.Component { } catch (error) { console.error(error); // eslint-disable-line no-console isLayoutInvalid = true; - toasts.addDanger(dashboardLoadingErrorStrings.getDashboardGridError(error.message)); + toasts.addDanger(dashboardSavedObjectErrorStrings.getDashboardGridError(error.message)); } this.setState({ layout, diff --git a/src/plugins/dashboard/public/application/embeddable/index.ts b/src/plugins/dashboard/public/application/embeddable/index.ts index ce8bb5b7169ac..1979ae5ad7bf6 100644 --- a/src/plugins/dashboard/public/application/embeddable/index.ts +++ b/src/plugins/dashboard/public/application/embeddable/index.ts @@ -13,11 +13,4 @@ export { createPanelState } from './panel'; export * from './types'; -export { - DASHBOARD_GRID_COLUMN_COUNT, - DEFAULT_PANEL_HEIGHT, - DEFAULT_PANEL_WIDTH, - DASHBOARD_CONTAINER_TYPE, -} from './dashboard_constants'; - export { createDashboardContainerByValueRenderer } from './dashboard_container_by_value_renderer'; diff --git a/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.test.ts b/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.test.ts index 10c3044ea912a..4c926675e1e94 100644 --- a/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.test.ts +++ b/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.test.ts @@ -8,7 +8,7 @@ import { EmbeddableInput } from '@kbn/embeddable-plugin/public'; import { CONTACT_CARD_EMBEDDABLE } from '@kbn/embeddable-plugin/public/lib/test_samples'; -import { DEFAULT_PANEL_HEIGHT, DEFAULT_PANEL_WIDTH } from '../dashboard_constants'; +import { DEFAULT_PANEL_HEIGHT, DEFAULT_PANEL_WIDTH } from '../../../dashboard_constants'; import { DashboardPanelState } from '../types'; import { createPanelState } from './create_panel_state'; diff --git a/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.ts b/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.ts index 5aa9066ea1eba..e5d4f69c914ce 100644 --- a/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.ts +++ b/src/plugins/dashboard/public/application/embeddable/panel/create_panel_state.ts @@ -7,7 +7,7 @@ */ import { PanelState, EmbeddableInput } from '@kbn/embeddable-plugin/public'; -import { DEFAULT_PANEL_HEIGHT, DEFAULT_PANEL_WIDTH } from '../dashboard_constants'; +import { DEFAULT_PANEL_HEIGHT, DEFAULT_PANEL_WIDTH } from '../../../dashboard_constants'; import { DashboardPanelState } from '../types'; import { IPanelPlacementArgs, diff --git a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts index 9d90b711a6843..77b51874319ba 100644 --- a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts +++ b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts @@ -8,8 +8,8 @@ import _ from 'lodash'; import { PanelNotFoundError } from '@kbn/embeddable-plugin/public'; -import { GridData } from '../../../../common'; -import { DashboardPanelState, DASHBOARD_GRID_COLUMN_COUNT } from '..'; +import { DashboardPanelState, GridData } from '../../../../common'; +import { DASHBOARD_GRID_COLUMN_COUNT } from '../../../dashboard_constants'; export type PanelPlacementMethod = ( args: PlacementArgs diff --git a/src/plugins/dashboard/public/application/embeddable/placeholder/index.ts b/src/plugins/dashboard/public/application/embeddable/placeholder/index.ts index af4327f0fcd98..1d1aba84e7c3a 100644 --- a/src/plugins/dashboard/public/application/embeddable/placeholder/index.ts +++ b/src/plugins/dashboard/public/application/embeddable/placeholder/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export * from './placeholder_embeddable'; -export * from './placeholder_embeddable_factory'; +export { PlaceholderEmbeddableFactory } from './placeholder_embeddable_factory'; + +export const PLACEHOLDER_EMBEDDABLE = 'placeholder'; diff --git a/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable.tsx b/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable.tsx index a7fa1e793ebf0..de468d86c89fe 100644 --- a/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable.tsx +++ b/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable.tsx @@ -13,9 +13,9 @@ import classNames from 'classnames'; import { EuiLoadingChart } from '@elastic/eui'; import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; import { Embeddable, type EmbeddableInput, type IContainer } from '@kbn/embeddable-plugin/public'; -import { pluginServices } from '../../../services/plugin_services'; -export const PLACEHOLDER_EMBEDDABLE = 'placeholder'; +import { PLACEHOLDER_EMBEDDABLE } from '.'; +import { pluginServices } from '../../../services/plugin_services'; export class PlaceholderEmbeddable extends Embeddable { public readonly type = PLACEHOLDER_EMBEDDABLE; diff --git a/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable_factory.ts b/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable_factory.ts index 74ce8bf96edbd..26cdddbf17d85 100644 --- a/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable_factory.ts +++ b/src/plugins/dashboard/public/application/embeddable/placeholder/placeholder_embeddable_factory.ts @@ -13,7 +13,7 @@ import { EmbeddableInput, IContainer, } from '@kbn/embeddable-plugin/public'; -import { PlaceholderEmbeddable, PLACEHOLDER_EMBEDDABLE } from './placeholder_embeddable'; +import { PLACEHOLDER_EMBEDDABLE } from '.'; export class PlaceholderEmbeddableFactory implements EmbeddableFactoryDefinition { public readonly type = PLACEHOLDER_EMBEDDABLE; @@ -29,6 +29,7 @@ export class PlaceholderEmbeddableFactory implements EmbeddableFactoryDefinition } public async create(initialInput: EmbeddableInput, parent?: IContainer) { + const { PlaceholderEmbeddable } = await import('./placeholder_embeddable'); return new PlaceholderEmbeddable(initialInput, parent); } diff --git a/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.test.tsx b/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.test.tsx index c462df50ef27f..76a3ae7a053a4 100644 --- a/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.test.tsx +++ b/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.test.tsx @@ -9,27 +9,20 @@ import React from 'react'; import { Provider } from 'react-redux'; import { createBrowserHistory } from 'history'; + +import type { Filter } from '@kbn/es-query'; +import { DataView } from '@kbn/data-views-plugin/public'; +import { EmbeddableFactory, ViewMode } from '@kbn/embeddable-plugin/public'; import { renderHook, act, RenderHookResult } from '@testing-library/react-hooks'; import { createKbnUrlStateStorage, defer } from '@kbn/kibana-utils-plugin/public'; -import { DataView } from '@kbn/data-views-plugin/public'; +import { DashboardAppState } from '../../types'; +import { getSampleDashboardInput } from '../test_helpers'; import { DashboardConstants } from '../../dashboard_constants'; -import { SavedObjectLoader } from '../../services/saved_object_loader'; -import { DashboardAppServices, DashboardAppState } from '../../types'; +import { pluginServices } from '../../services/plugin_services'; import { DashboardContainer } from '../embeddable/dashboard_container'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { dashboardStateStore, setDescription, setViewMode } from '../state'; import { useDashboardAppState, UseDashboardStateProps } from './use_dashboard_app_state'; -import { - getSampleDashboardInput, - getSavedDashboardMock, - makeDefaultServices, -} from '../test_helpers'; - -import type { Filter } from '@kbn/es-query'; -import { pluginServices } from '../../services/plugin_services'; -import { EmbeddableFactory, ViewMode } from '@kbn/embeddable-plugin/public'; -import { DashboardServices } from '../../services/types'; interface SetupEmbeddableFactoryReturn { finalizeEmbeddableCreation: () => void; @@ -40,7 +33,6 @@ interface SetupEmbeddableFactoryReturn { interface RenderDashboardStateHookReturn { embeddableFactoryResult: SetupEmbeddableFactoryReturn; renderHookResult: RenderHookResult, DashboardAppState>; - services: DashboardAppServices; props: UseDashboardStateProps; } @@ -55,28 +47,7 @@ const createDashboardAppStateProps = (): UseDashboardStateProps => ({ setShowNoDataPage: () => {}, }); -const createDashboardAppStateServices = () => { - const defaults = makeDefaultServices(); - - const defaultDataView = { id: 'foo', fields: [{ name: 'bar' }] } as DataView; - - (pluginServices.getServices().data.dataViews.getDefaultDataView as jest.Mock).mockResolvedValue( - defaultDataView - ); - (pluginServices.getServices().data.dataViews.getDefaultId as jest.Mock).mockResolvedValue( - defaultDataView.id - ); - (pluginServices.getServices().data.query.filterManager.getFilters as jest.Mock).mockReturnValue( - [] - ); - - return defaults; -}; - -const setupEmbeddableFactory = ( - services: DashboardAppServices, - id: string -): SetupEmbeddableFactoryReturn => { +const setupEmbeddableFactory = (id: string): SetupEmbeddableFactoryReturn => { const dashboardContainer = new DashboardContainer({ ...getSampleDashboardInput(), id }); const deferEmbeddableCreate = defer(); pluginServices.getServices().embeddable.getEmbeddableFactory = jest.fn().mockImplementation( @@ -100,15 +71,22 @@ const setupEmbeddableFactory = ( const renderDashboardAppStateHook = ({ partialProps, - partialServices, }: { partialProps?: Partial; - partialServices?: Partial; }): RenderDashboardStateHookReturn => { + const defaultDataView = { id: 'foo', fields: [{ name: 'bar' }] } as DataView; + (pluginServices.getServices().data.dataViews.getDefaultDataView as jest.Mock).mockResolvedValue( + defaultDataView + ); + (pluginServices.getServices().data.dataViews.getDefaultId as jest.Mock).mockResolvedValue( + defaultDataView.id + ); + (pluginServices.getServices().data.query.filterManager.getFilters as jest.Mock).mockReturnValue( + [] + ); + const props = { ...createDashboardAppStateProps(), ...(partialProps ?? {}) }; - const services = { ...createDashboardAppStateServices(), ...(partialServices ?? {}) }; - const embeddableFactoryResult = setupEmbeddableFactory(services, originalDashboardEmbeddableId); - const DashboardServicesProvider = pluginServices.getContextProvider(); + const embeddableFactoryResult = setupEmbeddableFactory(originalDashboardEmbeddableId); const renderHookResult = renderHook( (replaceProps: Partial) => { @@ -116,18 +94,11 @@ const renderDashboardAppStateHook = ({ }, { wrapper: ({ children }) => { - return ( - - {/* Can't get rid of KibanaContextProvider here yet because of saved dashboard tests below */} - - {children} - - - ); + return {children}; }, } ); - return { embeddableFactoryResult, renderHookResult, services, props }; + return { embeddableFactoryResult, renderHookResult, props }; }; describe('Dashboard container lifecycle', () => { @@ -146,7 +117,7 @@ describe('Dashboard container lifecycle', () => { }); test('Old dashboard container is destroyed when new dashboardId is given', async () => { - const { renderHookResult, embeddableFactoryResult, services } = renderDashboardAppStateHook({}); + const { renderHookResult, embeddableFactoryResult } = renderDashboardAppStateHook({}); const getResult = () => renderHookResult.result.current; // on initial render dashboard container is undefined @@ -158,7 +129,7 @@ describe('Dashboard container lifecycle', () => { expect(embeddableFactoryResult.dashboardDestroySpy).not.toBeCalled(); const newDashboardId = 'wow_a_new_dashboard_id'; - const embeddableFactoryNew = setupEmbeddableFactory(services, newDashboardId); + const embeddableFactoryNew = setupEmbeddableFactory(newDashboardId); renderHookResult.rerender({ savedDashboardId: newDashboardId }); embeddableFactoryNew.finalizeEmbeddableCreation(); @@ -170,7 +141,7 @@ describe('Dashboard container lifecycle', () => { }); test('Dashboard container is destroyed if dashboard id is changed before container is resolved', async () => { - const { renderHookResult, embeddableFactoryResult, services } = renderDashboardAppStateHook({}); + const { renderHookResult, embeddableFactoryResult } = renderDashboardAppStateHook({}); const getResult = () => renderHookResult.result.current; // on initial render dashboard container is undefined @@ -178,7 +149,7 @@ describe('Dashboard container lifecycle', () => { await act(() => Promise.resolve()); // wait for the original savedDashboard to be loaded... const newDashboardId = 'wow_a_new_dashboard_id'; - const embeddableFactoryNew = setupEmbeddableFactory(services, newDashboardId); + const embeddableFactoryNew = setupEmbeddableFactory(newDashboardId); renderHookResult.rerender({ savedDashboardId: newDashboardId }); await act(() => Promise.resolve()); // wait for the new savedDashboard to be loaded... @@ -199,38 +170,33 @@ describe('Dashboard container lifecycle', () => { // FLAKY: https://github.com/elastic/kibana/issues/105018 describe.skip('Dashboard initial state', () => { it('Extracts state from Dashboard Saved Object', async () => { + const savedTitle = 'testDash1'; + ( + pluginServices.getServices().dashboardSavedObject + .loadDashboardStateFromSavedObject as jest.Mock + ).mockResolvedValue({ title: savedTitle }); + const { renderHookResult, embeddableFactoryResult } = renderDashboardAppStateHook({}); const getResult = () => renderHookResult.result.current; - // saved dashboard isn't applied until after the dashboard embeddable has been created. - expect(getResult().savedDashboard).toBeUndefined(); - embeddableFactoryResult.finalizeEmbeddableCreation(); await renderHookResult.waitForNextUpdate(); - expect(getResult().savedDashboard).toBeDefined(); - expect(getResult().savedDashboard?.title).toEqual( - getResult().getLatestDashboardState?.().title - ); + expect(savedTitle).toEqual(getResult().getLatestDashboardState?.().title); }); it('Sets initial time range and filters from saved dashboard', async () => { - const savedDashboards = {} as SavedObjectLoader; - savedDashboards.get = jest.fn().mockImplementation((id?: string) => - Promise.resolve( - getSavedDashboardMock({ - getFilters: () => [{ meta: { test: 'filterMeTimbers' } } as unknown as Filter], - timeRestore: true, - timeFrom: 'now-13d', - timeTo: 'now', - id, - }) - ) - ); - const partialServices: Partial = { savedDashboards }; - const { renderHookResult, embeddableFactoryResult, services } = renderDashboardAppStateHook({ - partialServices, + ( + pluginServices.getServices().dashboardSavedObject + .loadDashboardStateFromSavedObject as jest.Mock + ).mockResolvedValue({ + filters: [{ meta: { test: 'filterMeTimbers' } } as unknown as Filter], + timeRestore: true, + timeFrom: 'now-13d', + timeTo: 'now', }); + + const { renderHookResult, embeddableFactoryResult } = renderDashboardAppStateHook({}); const getResult = () => renderHookResult.result.current; embeddableFactoryResult.finalizeEmbeddableCreation(); @@ -238,15 +204,13 @@ describe.skip('Dashboard initial state', () => { expect(getResult().getLatestDashboardState?.().timeRestore).toEqual(true); expect( - (services as DashboardAppServices & { data: DashboardServices['data'] }).data.query.timefilter - .timefilter.setTime + pluginServices.getServices().data.query.timefilter.timefilter.setTime ).toHaveBeenCalledWith({ from: 'now-13d', to: 'now', }); expect( - (services as DashboardAppServices & { data: DashboardServices['data'] }).data.query - .filterManager.setAppFilters + pluginServices.getServices().data.query.filterManager.setAppFilters ).toHaveBeenCalledWith([{ meta: { test: 'filterMeTimbers' } } as unknown as Filter]); }); diff --git a/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.ts b/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.ts index 932bfdd016b38..850c6f575904c 100644 --- a/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.ts +++ b/src/plugins/dashboard/public/application/hooks/use_dashboard_app_state.ts @@ -6,50 +6,45 @@ * Side Public License, v 1. */ +import { omit } from 'lodash'; import { History } from 'history'; import { debounceTime, switchMap } from 'rxjs/operators'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { BehaviorSubject, combineLatest, Observable, Subject } from 'rxjs'; import { ViewMode } from '@kbn/embeddable-plugin/public'; -import { useKibana } from '@kbn/kibana-react-plugin/public'; import type { IKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; -import { DashboardConstants } from '../..'; -import { getNewDashboardTitle } from '../../dashboard_strings'; -import { setDashboardState, useDashboardDispatch, useDashboardSelector } from '../state'; -import type { - DashboardBuildContext, - DashboardAppServices, - DashboardAppState, - DashboardState, -} from '../../types'; -import { DashboardAppLocatorParams } from '../../locator'; import { - loadDashboardHistoryLocationState, - tryDestroyDashboardContainer, - syncDashboardContainerInput, - savedObjectToDashboardState, + diffDashboardState, + syncDashboardUrlState, syncDashboardDataViews, - syncDashboardFilterState, - loadSavedDashboardState, buildDashboardContainer, - syncDashboardUrlState, - diffDashboardState, - areTimeRangesEqual, - areRefreshIntervalsEqual, + syncDashboardFilterState, + syncDashboardContainerInput, + tryDestroyDashboardContainer, + loadDashboardHistoryLocationState, } from '../lib'; -import { isDashboardAppInNoDataState } from '../dashboard_app_no_data'; +import { + dashboardStateLoadWasSuccessful, + LoadDashboardFromSavedObjectReturn, +} from '../../services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object'; +import { DashboardConstants } from '../..'; +import { DashboardAppLocatorParams } from '../../locator'; +import { dashboardSavedObjectErrorStrings, getNewDashboardTitle } from '../../dashboard_strings'; import { pluginServices } from '../../services/plugin_services'; import { useDashboardMountContext } from './dashboard_mount_context'; +import { isDashboardAppInNoDataState } from '../dashboard_app_no_data'; +import { setDashboardState, useDashboardDispatch, useDashboardSelector } from '../state'; +import type { DashboardBuildContext, DashboardAppState, DashboardState } from '../../types'; export interface UseDashboardStateProps { history: History; showNoDataPage: boolean; savedDashboardId?: string; isEmbeddedExternally: boolean; - setShowNoDataPage: (showNoData: boolean) => void; kbnUrlStateStorage: IKbnUrlStateStorage; + setShowNoDataPage: (showNoData: boolean) => void; } export const useDashboardAppState = ({ @@ -79,25 +74,23 @@ export const useDashboardAppState = ({ const [lastSavedState, setLastSavedState] = useState(); const $onLastSavedStateChange = useMemo(() => new Subject(), []); - const { - services: { savedDashboards }, - } = useKibana(); - /** * Unpack services and context */ const { scopedHistory } = useDashboardMountContext(); const { + embeddable, + notifications: { toasts }, chrome: { docTitle }, dashboardCapabilities, dashboardSessionStorage, + spaces: { redirectLegacyUrl }, data: { query, search, dataViews }, - embeddable, initializerContext: { kibanaVersion }, screenshotMode: { isScreenshotMode, getScreenshotContext }, - spaces: { redirectLegacyUrl }, - notifications, + dashboardSavedObject: { loadDashboardStateFromSavedObject }, } = pluginServices.getServices(); + const { getStateTransfer } = embeddable; /** @@ -120,7 +113,6 @@ export const useDashboardAppState = ({ */ const dashboardBuildContext: DashboardBuildContext = { history, - savedDashboards, kbnUrlStateStorage, isEmbeddedExternally, dispatchDashboardStateChange, @@ -149,33 +141,25 @@ export const useDashboardAppState = ({ /** * Load and unpack state from dashboard saved object. */ - const loadSavedDashboardResult = await loadSavedDashboardState({ - ...dashboardBuildContext, - savedDashboardId, - }); - if (canceled || !loadSavedDashboardResult) return; - const { savedDashboard, savedDashboardState } = loadSavedDashboardResult; - - // If the saved dashboard is an alias match, then we will redirect - if (savedDashboard.outcome === 'aliasMatch' && savedDashboard.id && savedDashboard.aliasId) { - // We want to keep the "query" params on our redirect. - // But, these aren't true query params, they are technically part of the hash - // So, to get the new path, we will just replace the current id in the hash - // with the alias id - const path = scopedHistory().location.hash.replace( - savedDashboard.id, - savedDashboard.aliasId - ); - const aliasPurpose = savedDashboard.aliasPurpose; - if (isScreenshotMode()) { - scopedHistory().replace(path); - } else { - await redirectLegacyUrl?.({ path, aliasPurpose }); - } - // Return so we don't run any more of the hook and let it rerun after the redirect that just happened + let loadSavedDashboardResult: LoadDashboardFromSavedObjectReturn; + try { + loadSavedDashboardResult = await loadDashboardStateFromSavedObject({ + getScopedHistory: scopedHistory, + id: savedDashboardId, + }); + } catch (error) { + // redirect back to landing page if dashboard could not be loaded. + toasts.addDanger(dashboardSavedObjectErrorStrings.getDashboardLoadError(error.message)); + history.push(DashboardConstants.LANDING_PAGE_PATH); + return; + } + if (canceled || !dashboardStateLoadWasSuccessful(loadSavedDashboardResult)) { return; } + const { dashboardState: savedDashboardState, createConflictWarning } = + loadSavedDashboardResult; + /** * Combine initial state from the saved object, session storage, and URL, then dispatch it to Redux. */ @@ -187,12 +171,11 @@ export const useDashboardAppState = ({ const { initialDashboardStateFromUrl, stopWatchingAppStateInUrl } = syncDashboardUrlState({ ...dashboardBuildContext, - savedDashboard, }); const printLayoutDetected = isScreenshotMode() && getScreenshotContext('layout') === 'print'; - const initialDashboardState = { + const initialDashboardState: DashboardState = { ...savedDashboardState, ...dashboardSessionStorageState, ...initialDashboardStateFromUrl, @@ -208,10 +191,9 @@ export const useDashboardAppState = ({ /** * Start syncing dashboard state with the Query, Filters and Timepicker from the Query Service. */ - const { applyFilters, stopSyncingDashboardFilterState } = syncDashboardFilterState({ + const { stopSyncingDashboardFilterState } = syncDashboardFilterState({ ...dashboardBuildContext, initialDashboardState, - savedDashboard, }); /** @@ -222,10 +204,9 @@ export const useDashboardAppState = ({ ...dashboardBuildContext, initialDashboardState, incomingEmbeddable, - savedDashboard, executionContext: { type: 'dashboard', - description: savedDashboard.title, + description: initialDashboardState.title, }, }); @@ -256,15 +237,13 @@ export const useDashboardAppState = ({ const stopSyncingContainerInput = syncDashboardContainerInput({ ...dashboardBuildContext, dashboardContainer, - savedDashboard, - applyFilters, }); /** * Any time the redux state, or the last saved state changes, compare them, set the unsaved * changes state, and and push the unsaved changes to session storage. */ - const { timefilter } = query.timefilter; + const lastSavedSubscription = combineLatest([ $onLastSavedStateChange, dashboardAppState.$onDashboardStateChange, @@ -281,31 +260,24 @@ export const useDashboardAppState = ({ newState: current, }).then((unsavedChanges) => { if (observer.closed) return; - const savedTimeChanged = - lastSaved.timeRestore && - (!areTimeRangesEqual( - { - from: savedDashboard?.timeFrom, - to: savedDashboard?.timeTo, - }, - timefilter.getTime() - ) || - !areRefreshIntervalsEqual( - savedDashboard?.refreshInterval, - timefilter.getRefreshInterval() - )); - /** * changes to the dashboard should only be considered 'unsaved changes' when * editing the dashboard */ const hasUnsavedChanges = - current.viewMode === ViewMode.EDIT && - (Object.keys(unsavedChanges).length > 0 || savedTimeChanged); + current.viewMode === ViewMode.EDIT && Object.keys(unsavedChanges).length > 0; setDashboardAppState((s) => ({ ...s, hasUnsavedChanges })); unsavedChanges.viewMode = current.viewMode; // always push view mode into session store. - dashboardSessionStorage.setState(savedDashboardId, unsavedChanges); + + /** + * Current behaviour expects time range not to be backed up. + * TODO: Revisit this. It seems like we should treat all state the same. + */ + dashboardSessionStorage.setState( + savedDashboardId, + omit(unsavedChanges, ['timeRange', 'refreshInterval']) + ); }); }); }) @@ -319,11 +291,7 @@ export const useDashboardAppState = ({ setLastSavedState(savedDashboardState); dashboardBuildContext.$checkForUnsavedChanges.next(undefined); const updateLastSavedState = () => { - setLastSavedState( - savedObjectToDashboardState({ - savedDashboard, - }) - ); + setLastSavedState(dashboardBuildContext.getLatestDashboardState()); }; /** @@ -332,10 +300,9 @@ export const useDashboardAppState = ({ docTitle.change(savedDashboardState.title || getNewDashboardTitle()); setDashboardAppState((s) => ({ ...s, - applyFilters, - savedDashboard, dashboardContainer, updateLastSavedState, + createConflictWarning, getLatestDashboardState: dashboardBuildContext.getLatestDashboardState, })); @@ -359,47 +326,43 @@ export const useDashboardAppState = ({ }, [ dashboardAppState.$triggerDashboardRefresh, dashboardAppState.$onDashboardStateChange, + loadDashboardStateFromSavedObject, dispatchDashboardStateChange, $onLastSavedStateChange, dashboardSessionStorage, dashboardCapabilities, isEmbeddedExternally, + getScreenshotContext, kbnUrlStateStorage, + setShowNoDataPage, + redirectLegacyUrl, savedDashboardId, + isScreenshotMode, getStateTransfer, - savedDashboards, + showNoDataPage, scopedHistory, - notifications, - dataViews, kibanaVersion, + dataViews, embeddable, docTitle, history, + toasts, search, query, - showNoDataPage, - setShowNoDataPage, - redirectLegacyUrl, - getScreenshotContext, - isScreenshotMode, ]); /** * rebuild reset to last saved state callback whenever last saved state changes */ const resetToLastSavedState = useCallback(() => { - if ( - !lastSavedState || - !dashboardAppState.savedDashboard || - !dashboardAppState.getLatestDashboardState - ) { + if (!lastSavedState || !dashboardAppState.getLatestDashboardState) { return; } if (dashboardAppState.getLatestDashboardState().timeRestore) { const { timefilter } = query.timefilter; - const { timeFrom: from, timeTo: to, refreshInterval } = dashboardAppState.savedDashboard; - if (from && to) timefilter.setTime({ from, to }); + const { timeRange, refreshInterval } = lastSavedState; + if (timeRange) timefilter.setTime(timeRange); if (refreshInterval) timefilter.setRefreshInterval(refreshInterval); } dispatchDashboardStateChange( diff --git a/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts b/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts index 8ad2b7ddc52e2..2d5304e002d54 100644 --- a/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts +++ b/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts @@ -16,8 +16,7 @@ import { isErrorEmbeddable, } from '@kbn/embeddable-plugin/public'; -import { DashboardSavedObject } from '../../saved_dashboards'; -import { DashboardContainer, DASHBOARD_CONTAINER_TYPE } from '../embeddable'; +import { DashboardContainer } from '../embeddable'; import { DashboardBuildContext, DashboardState, DashboardContainerInput } from '../../types'; import { enableDashboardSearchSessions, @@ -25,9 +24,9 @@ import { stateToDashboardContainerInput, } from '.'; import { pluginServices } from '../../services/plugin_services'; +import { DASHBOARD_CONTAINER_TYPE } from '../../dashboard_constants'; type BuildDashboardContainerProps = DashboardBuildContext & { - savedDashboard: DashboardSavedObject; initialDashboardState: DashboardState; incomingEmbeddable?: EmbeddablePackageState; executionContext?: KibanaExecutionContext; @@ -41,7 +40,6 @@ export const buildDashboardContainer = async ({ initialDashboardState, isEmbeddedExternally, incomingEmbeddable, - savedDashboard, history, executionContext, }: BuildDashboardContainerProps) => { @@ -55,7 +53,6 @@ export const buildDashboardContainer = async ({ // set up search session enableDashboardSearchSessions({ - savedDashboard, initialDashboardState, getLatestDashboardState, canStoreSearchSession, @@ -95,7 +92,6 @@ export const buildDashboardContainer = async ({ dashboardState: initialDashboardState, incomingEmbeddable, searchSessionId, - savedDashboard, executionContext, }); diff --git a/src/plugins/dashboard/public/application/lib/convert_dashboard_panels.ts b/src/plugins/dashboard/public/application/lib/convert_dashboard_panels.ts deleted file mode 100644 index 8e74245137f8e..0000000000000 --- a/src/plugins/dashboard/public/application/lib/convert_dashboard_panels.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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { - convertSavedDashboardPanelToPanelState, - convertPanelStateToSavedDashboardPanel, -} from '../../../common/embeddable/embeddable_saved_object_converters'; -import { pluginServices } from '../../services/plugin_services'; -import type { SavedDashboardPanel, DashboardPanelMap } from '../../types'; - -export const convertSavedPanelsToPanelMap = (panels?: SavedDashboardPanel[]): DashboardPanelMap => { - const panelsMap: DashboardPanelMap = {}; - panels?.forEach((panel, idx) => { - panelsMap![panel.panelIndex ?? String(idx)] = convertSavedDashboardPanelToPanelState(panel); - }); - return panelsMap; -}; - -export const convertPanelMapToSavedPanels = (panels: DashboardPanelMap) => { - const { - initializerContext: { kibanaVersion }, - } = pluginServices.getServices(); - - return Object.values(panels).map((panel) => - convertPanelStateToSavedDashboardPanel(panel, kibanaVersion) - ); -}; diff --git a/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts b/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts index c9e954a081ca2..14e0f4ac4c171 100644 --- a/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts +++ b/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts @@ -6,37 +6,21 @@ * Side Public License, v 1. */ -import _ from 'lodash'; +import { cloneDeep, omit } from 'lodash'; import type { KibanaExecutionContext } from '@kbn/core/public'; -import type { ControlGroupInput } from '@kbn/controls-plugin/public'; -import { type EmbeddablePackageState, ViewMode } from '@kbn/embeddable-plugin/public'; -import { - compareFilters, - COMPARE_ALL_OPTIONS, - Filter, - isFilterPinned, - TimeRange, -} from '@kbn/es-query'; import { mapAndFlattenFilters } from '@kbn/data-plugin/public'; +import { type EmbeddablePackageState } from '@kbn/embeddable-plugin/public'; +import { Filter, isFilterPinned, compareFilters, COMPARE_ALL_OPTIONS } from '@kbn/es-query'; -import type { DashboardSavedObject } from '../../saved_dashboards'; -import { getTagsFromSavedDashboard, migrateAppState } from '.'; -import { convertPanelStateToSavedDashboardPanel } from '../../../common/embeddable/embeddable_saved_object_converters'; -import type { DashboardState, RawDashboardState, DashboardContainerInput } from '../../types'; -import { convertSavedPanelsToPanelMap } from './convert_dashboard_panels'; -import { deserializeControlGroupFromDashboardSavedObject } from './dashboard_control_group'; import { pluginServices } from '../../services/plugin_services'; - -interface SavedObjectToDashboardStateProps { - savedDashboard: DashboardSavedObject; -} +import { convertPanelStateToSavedDashboardPanel } from '../../../common'; +import type { DashboardState, RawDashboardState, DashboardContainerInput } from '../../types'; interface StateToDashboardContainerInputProps { searchSessionId?: string; isEmbeddedExternally?: boolean; dashboardState: DashboardState; - savedDashboard: DashboardSavedObject; incomingEmbeddable?: EmbeddablePackageState; executionContext?: KibanaExecutionContext; } @@ -44,40 +28,6 @@ interface StateToDashboardContainerInputProps { interface StateToRawDashboardStateProps { state: DashboardState; } -/** - * Converts a dashboard saved object to a dashboard state by extracting raw state from the given Dashboard - * Saved Object migrating the panel states to the latest version, then converting each panel from a saved - * dashboard panel to a panel state. - */ -export const savedObjectToDashboardState = ({ - savedDashboard, -}: SavedObjectToDashboardStateProps): DashboardState => { - const { - dashboardCapabilities: { showWriteControls }, - } = pluginServices.getServices(); - - const rawState = migrateAppState({ - fullScreenMode: false, - title: savedDashboard.title, - query: savedDashboard.getQuery(), - filters: savedDashboard.getFilters(), - timeRestore: savedDashboard.timeRestore, - description: savedDashboard.description || '', - tags: getTagsFromSavedDashboard(savedDashboard), - panels: savedDashboard.panelsJSON ? JSON.parse(savedDashboard.panelsJSON) : [], - viewMode: savedDashboard.id || showWriteControls ? ViewMode.EDIT : ViewMode.VIEW, - options: savedDashboard.optionsJSON ? JSON.parse(savedDashboard.optionsJSON) : {}, - }); - - if (rawState.timeRestore) { - rawState.timeRange = { from: savedDashboard.timeFrom, to: savedDashboard.timeTo } as TimeRange; - } - - rawState.controlGroupInput = deserializeControlGroupFromDashboardSavedObject( - savedDashboard - ) as ControlGroupInput; - return { ...rawState, panels: convertSavedPanelsToPanelMap(rawState.panels) }; -}; /** * Converts a dashboard state object to dashboard container input @@ -85,7 +35,6 @@ export const savedObjectToDashboardState = ({ export const stateToDashboardContainerInput = ({ isEmbeddedExternally, searchSessionId, - savedDashboard, dashboardState, executionContext, }: StateToDashboardContainerInputProps): DashboardContainerInput => { @@ -111,7 +60,7 @@ export const stateToDashboardContainerInput = ({ filters: dashboardFilters, } = dashboardState; - const migratedDashboardFilters = mapAndFlattenFilters(_.cloneDeep(dashboardFilters)); + const migratedDashboardFilters = mapAndFlattenFilters(cloneDeep(dashboardFilters)); return { refreshConfig: timefilter.getRefreshInterval(), filters: filterManager @@ -124,7 +73,7 @@ export const stateToDashboardContainerInput = ({ ) ), isFullScreenMode: fullScreenMode, - id: savedDashboard.id || '', + id: dashboardState.savedObjectId ?? '', isEmbeddedExternally, ...(options || {}), controlGroupInput, @@ -136,7 +85,7 @@ export const stateToDashboardContainerInput = ({ query, title, timeRange: { - ..._.cloneDeep(timefilter.getTime()), + ...cloneDeep(timefilter.getTime()), }, timeslice, timeRestore, @@ -161,5 +110,5 @@ export const stateToRawDashboardState = ({ const savedDashboardPanels = Object.values(state.panels).map((panel) => convertPanelStateToSavedDashboardPanel(panel, kibanaVersion) ); - return { ..._.omit(state, 'panels'), panels: savedDashboardPanels }; + return { ...omit(state, 'panels'), panels: savedDashboardPanels }; }; diff --git a/src/plugins/dashboard/public/application/lib/dashboard_control_group.ts b/src/plugins/dashboard/public/application/lib/dashboard_control_group.ts index a9f474ed85dd0..4f44d0cf250d1 100644 --- a/src/plugins/dashboard/public/application/lib/dashboard_control_group.ts +++ b/src/plugins/dashboard/public/application/lib/dashboard_control_group.ts @@ -14,16 +14,15 @@ import { debounceTime, distinctUntilChanged, distinctUntilKeyChanged } from 'rxj import { ControlGroupInput, - controlGroupInputToRawControlGroupAttributes, getDefaultControlGroupInput, persistableControlGroupInputIsEqual, - rawControlGroupAttributesToControlGroupInput, + controlGroupInputToRawControlGroupAttributes, } from '@kbn/controls-plugin/common'; import { ControlGroupContainer } from '@kbn/controls-plugin/public'; import { DashboardContainer } from '..'; import { DashboardState } from '../../types'; -import { DashboardContainerInput, DashboardSavedObject } from '../..'; +import { DashboardContainerInput } from '../..'; interface DiffChecks { [key: string]: (a?: unknown, b?: unknown) => boolean; @@ -169,32 +168,17 @@ export const syncDashboardControlGroup = async ({ }; }; -export const serializeControlGroupToDashboardSavedObject = ( - dashboardSavedObject: DashboardSavedObject, - dashboardState: DashboardState +export const serializeControlGroupInput = ( + controlGroupInput: DashboardState['controlGroupInput'] ) => { // only save to saved object if control group is not default if ( - persistableControlGroupInputIsEqual( - dashboardState.controlGroupInput, - getDefaultControlGroupInput() - ) + !controlGroupInput || + persistableControlGroupInputIsEqual(controlGroupInput, getDefaultControlGroupInput()) ) { - dashboardSavedObject.controlGroupInput = undefined; - return; + return undefined; } - if (dashboardState.controlGroupInput) { - dashboardSavedObject.controlGroupInput = controlGroupInputToRawControlGroupAttributes( - dashboardState.controlGroupInput - ); - } -}; - -export const deserializeControlGroupFromDashboardSavedObject = ( - dashboardSavedObject: DashboardSavedObject -): Omit | undefined => { - if (!dashboardSavedObject.controlGroupInput) return; - return rawControlGroupAttributesToControlGroupInput(dashboardSavedObject.controlGroupInput); + return controlGroupInputToRawControlGroupAttributes(controlGroupInput); }; export const combineDashboardFiltersWithControlGroupFilters = ( diff --git a/src/plugins/dashboard/public/application/lib/session_restoration.test.ts b/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.test.ts similarity index 89% rename from src/plugins/dashboard/public/application/lib/session_restoration.test.ts rename to src/plugins/dashboard/public/application/lib/dashboard_session_restoration.test.ts index aeb83dd8a6e4c..56ee2ac55f445 100644 --- a/src/plugins/dashboard/public/application/lib/session_restoration.test.ts +++ b/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.test.ts @@ -6,16 +6,13 @@ * Side Public License, v 1. */ -import { getSavedDashboardMock } from '../test_helpers'; -import { createSessionRestorationDataProvider, savedObjectToDashboardState } from '.'; +import { DashboardState } from '../../types'; +import { createSessionRestorationDataProvider } from '.'; import { pluginServices } from '../../services/plugin_services'; describe('createSessionRestorationDataProvider', () => { const searchSessionInfoProvider = createSessionRestorationDataProvider({ - getAppState: () => - savedObjectToDashboardState({ - savedDashboard: getSavedDashboardMock(), - }), + getAppState: () => ({ panels: {} } as unknown as DashboardState), getDashboardTitle: () => 'Dashboard', getDashboardId: () => 'Id', }); diff --git a/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.ts b/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.ts index b2cedeee4ee04..113c39d0717ba 100644 --- a/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.ts +++ b/src/plugins/dashboard/public/application/lib/dashboard_session_restoration.ts @@ -17,12 +17,11 @@ import { import { getQueryParams } from '@kbn/kibana-utils-plugin/public'; import type { DashboardState } from '../../types'; -import type { DashboardSavedObject } from '../../saved_dashboards'; -import { DashboardAppLocatorParams, DashboardConstants } from '../..'; -import { getDashboardTitle } from '../../dashboard_strings'; -import { stateToRawDashboardState } from './convert_dashboard_state'; import { DASHBOARD_APP_LOCATOR } from '../../locator'; +import { getDashboardTitle } from '../../dashboard_strings'; import { pluginServices } from '../../services/plugin_services'; +import { DashboardAppLocatorParams, DashboardConstants } from '../..'; +import { stateToRawDashboardState } from './convert_dashboard_state'; export const getSearchSessionIdFromURL = (history: History): string | undefined => getQueryParams(history.location)[DashboardConstants.SEARCH_SESSION_ID] as string | undefined; @@ -52,10 +51,8 @@ export function enableDashboardSearchSessions({ canStoreSearchSession, initialDashboardState, getLatestDashboardState, - savedDashboard, }: { canStoreSearchSession: boolean; - savedDashboard: DashboardSavedObject; initialDashboardState: DashboardState; getLatestDashboardState: () => DashboardState; }) { @@ -63,13 +60,13 @@ export function enableDashboardSearchSessions({ const dashboardTitle = getDashboardTitle( initialDashboardState.title, initialDashboardState.viewMode, - !savedDashboard.id + !getLatestDashboardState().savedObjectId ); data.search.session.enableStorage( createSessionRestorationDataProvider({ getDashboardTitle: () => dashboardTitle, - getDashboardId: () => savedDashboard?.id || '', + getDashboardId: () => getLatestDashboardState().savedObjectId ?? '', getAppState: getLatestDashboardState, }), { @@ -106,7 +103,7 @@ function getLocatorParams({ return { timeRange: shouldRestoreSearchSession ? timefilter.getAbsoluteTime() : timefilter.getTime(), searchSessionId: shouldRestoreSearchSession ? data.search.session.getSessionId() : undefined, - panels: getDashboardId() ? undefined : appState.panels, + panels: getDashboardId() ? undefined : (appState.panels as DashboardAppLocatorParams['panels']), query: queryString.formatQuery(appState.query) as Query, filters: filterManager.getFilters(), savedQuery: appState.savedQuery, diff --git a/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts b/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts deleted file mode 100644 index 0a8ec17aeb2f1..0000000000000 --- a/src/plugins/dashboard/public/application/lib/dashboard_tagging.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import type { TagDecoratedSavedObject } from '@kbn/saved-objects-tagging-oss-plugin/public'; -import type { SavedObject } from '@kbn/saved-objects-plugin/public'; - -import { DashboardSavedObject } from '../..'; -import { pluginServices } from '../../services/plugin_services'; - -// TS is picky with type guards, we can't just inline `() => false` -function defaultTaggingGuard(_obj: SavedObject): _obj is TagDecoratedSavedObject { - return false; -} - -export const getTagsFromSavedDashboard = (savedDashboard: DashboardSavedObject) => { - const hasTaggingCapabilities = getHasTaggingCapabilitiesGuard(); - return hasTaggingCapabilities(savedDashboard) ? savedDashboard.getTags() : []; -}; - -export const getHasTaggingCapabilitiesGuard = () => { - const { - savedObjectsTagging: { hasTagDecoration }, - } = pluginServices.getServices(); - - return hasTagDecoration || defaultTaggingGuard; -}; diff --git a/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts b/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts index ca913199a3ba2..1c57d1bd2afa9 100644 --- a/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts +++ b/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts @@ -6,14 +6,25 @@ * Side Public License, v 1. */ -import { xor, omit, isEmpty } from 'lodash'; import fastIsEqual from 'fast-deep-equal'; -import { compareFilters, COMPARE_ALL_OPTIONS, type Filter, isFilterPinned } from '@kbn/es-query'; +import { xor, omit, isEmpty, pick } from 'lodash'; + +import { + compareFilters, + COMPARE_ALL_OPTIONS, + type Filter, + isFilterPinned, + TimeRange, +} from '@kbn/es-query'; +import { RefreshInterval } from '@kbn/data-plugin/common'; import { IEmbeddable } from '@kbn/embeddable-plugin/public'; - import { persistableControlGroupInputIsEqual } from '@kbn/controls-plugin/common'; + import { DashboardContainerInput } from '../..'; -import { DashboardOptions, DashboardPanelMap, DashboardState } from '../../types'; +import { areTimesEqual } from './filter_utils'; +import { DashboardPanelMap } from '../embeddable'; +import { DashboardOptions, DashboardState } from '../../types'; +import { pluginServices } from '../../services/plugin_services'; const stateKeystoIgnore = [ 'expandedPanelId', @@ -96,15 +107,67 @@ export const diffDashboardState = async ({ newState.controlGroupInput ); + const timeStatediff = getTimeSettingsAreEqual({ + currentTimeRestore: newState.timeRestore, + lastSaved: { ...pick(originalState, ['timeRange', 'timeRestore', 'refreshInterval']) }, + }) + ? {} + : pick(newState, ['timeRange', 'timeRestore', 'refreshInterval']); + return { ...commonStateDiff, ...(panelsAreEqual ? {} : { panels: newState.panels }), ...(filtersAreEqual ? {} : { filters: newState.filters }), ...(optionsAreEqual ? {} : { options: newState.options }), ...(controlGroupIsEqual ? {} : { controlGroupInput: newState.controlGroupInput }), + ...timeStatediff, }; }; +interface TimeStateDiffArg { + timeRange?: TimeRange; + timeRestore?: boolean; + refreshInterval?: RefreshInterval; +} + +export const getTimeSettingsAreEqual = ({ + lastSaved, + currentTimeRestore, +}: { + lastSaved?: TimeStateDiffArg; + currentTimeRestore?: boolean; +}) => { + const { + data: { + query: { + timefilter: { timefilter }, + }, + }, + } = pluginServices.getServices(); + + if (currentTimeRestore !== lastSaved?.timeRestore) return false; + if (!currentTimeRestore) return true; + + const currentRange = timefilter.getTime(); + const lastRange = lastSaved?.timeRange ?? timefilter.getTimeDefaults(); + if ( + !areTimesEqual(currentRange.from, lastRange.from) || + !areTimesEqual(currentRange.to, lastRange.to) + ) { + return false; + } + + const currentInterval = timefilter.getRefreshInterval(); + const lastInterval = lastSaved?.refreshInterval ?? timefilter.getRefreshIntervalDefaults(); + if ( + currentInterval.pause !== lastInterval.pause || + currentInterval.value !== lastInterval.value + ) { + return false; + } + return true; +}; + const getFiltersAreEqual = ( filtersA: Filter[], filtersB: Filter[], diff --git a/src/plugins/dashboard/public/application/lib/filter_utils.ts b/src/plugins/dashboard/public/application/lib/filter_utils.ts index 9b9a1270fd3ba..fb2762c7dc587 100644 --- a/src/plugins/dashboard/public/application/lib/filter_utils.ts +++ b/src/plugins/dashboard/public/application/lib/filter_utils.ts @@ -8,12 +8,7 @@ import _ from 'lodash'; import moment, { Moment } from 'moment'; -import type { Optional } from '@kbn/utility-types'; -import type { RefreshInterval } from '@kbn/data-plugin/public'; -import type { Filter, TimeRange } from '@kbn/es-query'; - -type TimeRangeCompare = Optional; -type RefreshIntervalCompare = Optional; +import type { Filter } from '@kbn/es-query'; /** * Converts the time to a utc formatted string. If the time is not valid (e.g. it might be in a relative format like @@ -32,22 +27,6 @@ export const convertTimeToUTCString = (time?: string | Moment): undefined | stri } }; -export const areTimeRangesEqual = (rangeA: TimeRangeCompare, rangeB: TimeRangeCompare): boolean => - areTimesEqual(rangeA.from, rangeB.from) && areTimesEqual(rangeA.to, rangeB.to); - -export const areRefreshIntervalsEqual = ( - refreshA?: RefreshIntervalCompare, - refreshB?: RefreshIntervalCompare -): boolean => refreshA?.pause === refreshB?.pause && refreshA?.value === refreshB?.value; - -/** - * Compares the two times, making sure they are in both compared in string format. Absolute times - * are sometimes stored as moment objects, but converted to strings when reloaded. Relative times are - * strings that are not convertible to moment objects. - * @param timeA {string|Moment} - * @param timeB {string|Moment} - * @returns {boolean} - */ export const areTimesEqual = (timeA?: string | Moment, timeB?: string | Moment) => { return convertTimeToUTCString(timeA) === convertTimeToUTCString(timeB); }; diff --git a/src/plugins/dashboard/public/application/lib/index.ts b/src/plugins/dashboard/public/application/lib/index.ts index 1b4ab12d2bc1b..0f364a31061d3 100644 --- a/src/plugins/dashboard/public/application/lib/index.ts +++ b/src/plugins/dashboard/public/application/lib/index.ts @@ -6,28 +6,24 @@ * Side Public License, v 1. */ -export * from './filter_utils'; -export { getDashboardIdFromUrl } from './url'; -export { saveDashboard } from './save_dashboard'; -export { migrateAppState } from './migrate_app_state'; -export { addHelpMenuToAppChrome } from './help_menu_util'; -export { diffDashboardState } from './diff_dashboard_state'; -export { getTagsFromSavedDashboard } from './dashboard_tagging'; -export { syncDashboardUrlState } from './sync_dashboard_url_state'; -export { loadSavedDashboardState } from './load_saved_dashboard_state'; -export { attemptLoadDashboardByTitle } from './load_dashboard_by_title'; -export { syncDashboardFilterState } from './sync_dashboard_filter_state'; -export { syncDashboardDataViews } from './sync_dashboard_data_views'; -export { syncDashboardContainerInput } from './sync_dashboard_container_input'; -export { loadDashboardHistoryLocationState } from './load_dashboard_history_location_state'; -export { buildDashboardContainer, tryDestroyDashboardContainer } from './build_dashboard_container'; export { - stateToDashboardContainerInput, - savedObjectToDashboardState, -} from './convert_dashboard_state'; + areTimesEqual, + convertTimeToUTCString, + cleanFiltersForSerialize, + cleanFiltersForComparison, +} from './filter_utils'; export { createSessionRestorationDataProvider, enableDashboardSearchSessions, getSearchSessionIdFromURL, getSessionURLObservable, } from './dashboard_session_restoration'; +export { addHelpMenuToAppChrome } from './help_menu_util'; +export { diffDashboardState } from './diff_dashboard_state'; +export { syncDashboardUrlState } from './sync_dashboard_url_state'; +export { syncDashboardDataViews } from './sync_dashboard_data_views'; +export { syncDashboardFilterState } from './sync_dashboard_filter_state'; +export { stateToDashboardContainerInput } from './convert_dashboard_state'; +export { syncDashboardContainerInput } from './sync_dashboard_container_input'; +export { loadDashboardHistoryLocationState } from './load_dashboard_history_location_state'; +export { buildDashboardContainer, tryDestroyDashboardContainer } from './build_dashboard_container'; diff --git a/src/plugins/dashboard/public/application/lib/load_dashboard_by_title.ts b/src/plugins/dashboard/public/application/lib/load_dashboard_by_title.ts deleted file mode 100644 index bff9f8600c0ed..0000000000000 --- a/src/plugins/dashboard/public/application/lib/load_dashboard_by_title.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { DashboardSavedObject } from '../..'; -import { pluginServices } from '../../services/plugin_services'; - -export async function attemptLoadDashboardByTitle( - title: string -): Promise<{ id: string } | undefined> { - const { - savedObjects: { client }, - } = pluginServices.getServices(); - - const results = await client.find({ - search: `"${title}"`, - searchFields: ['title'], - type: 'dashboard', - }); - // The search isn't an exact match, lets see if we can find a single exact match to use - const matchingDashboards = results.savedObjects.filter( - (dashboard) => dashboard.attributes.title.toLowerCase() === title.toLowerCase() - ); - if (matchingDashboards.length === 1) { - return { id: matchingDashboards[0].id }; - } -} diff --git a/src/plugins/dashboard/public/application/lib/load_dashboard_history_location_state.ts b/src/plugins/dashboard/public/application/lib/load_dashboard_history_location_state.ts index ce06ef443d69f..9a7d1791c6c94 100644 --- a/src/plugins/dashboard/public/application/lib/load_dashboard_history_location_state.ts +++ b/src/plugins/dashboard/public/application/lib/load_dashboard_history_location_state.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -import { ForwardedDashboardState } from '../../locator'; import { DashboardState } from '../../types'; -import { convertSavedPanelsToPanelMap } from './convert_dashboard_panels'; +import { ForwardedDashboardState } from '../../locator'; +import { convertSavedPanelsToPanelMap } from '../../../common'; export const loadDashboardHistoryLocationState = ( state?: ForwardedDashboardState diff --git a/src/plugins/dashboard/public/application/lib/load_saved_dashboard_state.ts b/src/plugins/dashboard/public/application/lib/load_saved_dashboard_state.ts deleted file mode 100644 index 6a7eba0884abe..0000000000000 --- a/src/plugins/dashboard/public/application/lib/load_saved_dashboard_state.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { ViewMode } from '@kbn/embeddable-plugin/public'; -import { getDashboard60Warning, dashboardLoadingErrorStrings } from '../../dashboard_strings'; -import { savedObjectToDashboardState } from './convert_dashboard_state'; -import { DashboardState, DashboardBuildContext } from '../../types'; -import { DashboardConstants, DashboardSavedObject } from '../..'; -import { migrateLegacyQuery } from './migrate_legacy_query'; -import { cleanFiltersForSerialize } from './filter_utils'; -import { pluginServices } from '../../services/plugin_services'; - -interface LoadSavedDashboardStateReturn { - savedDashboardState: DashboardState; - savedDashboard: DashboardSavedObject; -} - -/** - * Loads, migrates, and returns state from a dashboard saved object. - */ -export const loadSavedDashboardState = async ({ - history, - savedDashboards, - savedDashboardId, -}: DashboardBuildContext & { savedDashboardId?: string }): Promise< - LoadSavedDashboardStateReturn | undefined -> => { - const { - dashboardCapabilities: { showWriteControls }, - data: { - query: { queryString }, - }, - notifications: { toasts }, - } = pluginServices.getServices(); - - // BWC - remove for 8.0 - if (savedDashboardId === 'create') { - history.replace({ - ...history.location, // preserve query, - pathname: DashboardConstants.CREATE_NEW_DASHBOARD_URL, - }); - - toasts.addWarning(getDashboard60Warning()); - return; - } - try { - const savedDashboard = (await savedDashboards.get({ - id: savedDashboardId, - useResolve: true, - })) as DashboardSavedObject; - const savedDashboardState = savedObjectToDashboardState({ - savedDashboard, - }); - - const isViewMode = !showWriteControls || Boolean(savedDashboard.id); - savedDashboardState.viewMode = isViewMode ? ViewMode.VIEW : ViewMode.EDIT; - savedDashboardState.filters = cleanFiltersForSerialize(savedDashboardState.filters); - savedDashboardState.query = migrateLegacyQuery( - savedDashboardState.query || queryString.getDefaultQuery() - ); - - return { savedDashboardState, savedDashboard }; - } catch (error) { - // E.g. a corrupt or deleted dashboard - toasts.addDanger(dashboardLoadingErrorStrings.getDashboardLoadError(error.message)); - history.push(DashboardConstants.LANDING_PAGE_PATH); - return; - } -}; diff --git a/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts b/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts deleted file mode 100644 index 578439070e970..0000000000000 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { pluginServices } from '../../services/plugin_services'; -import { SavedDashboardPanel } from '../../types'; -import { migrateAppState } from './migrate_app_state'; - -pluginServices.getServices().initializerContext.kibanaVersion = '8.0'; - -test('migrate app state from 6.0', async () => { - const appState = { - uiState: { - 'P-1': { vis: { defaultColors: { '0+-+100': 'rgb(0,104,55)' } } }, - }, - panels: [ - { - col: 1, - id: 'Visualization-MetricChart', - panelIndex: 1, - row: 1, - size_x: 6, - size_y: 3, - type: 'visualization', - }, - ], - }; - migrateAppState(appState as any); - expect(appState.uiState).toBeUndefined(); - - const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; - - expect(newPanel.gridData.w).toBe(24); - expect(newPanel.gridData.h).toBe(15); - expect(newPanel.gridData.x).toBe(0); - expect(newPanel.gridData.y).toBe(0); - - expect((newPanel.embeddableConfig as any).vis.defaultColors['0+-+100']).toBe('rgb(0,104,55)'); -}); - -test('migrate sort from 6.1', async () => { - const appState = { - uiState: { - 'P-1': { vis: { defaultColors: { '0+-+100': 'rgb(0,104,55)' } } }, - }, - panels: [ - { - col: 1, - id: 'Visualization-MetricChart', - panelIndex: 1, - row: 1, - size_x: 6, - size_y: 3, - type: 'visualization', - sort: 'sort', - }, - ], - useMargins: false, - }; - migrateAppState(appState as any); - expect(appState.uiState).toBeUndefined(); - - const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; - expect(newPanel.gridData.w).toBe(24); - expect(newPanel.gridData.h).toBe(15); - expect((newPanel as any).sort).toBeUndefined(); - - expect((newPanel.embeddableConfig as any).sort).toBe('sort'); - expect((newPanel.embeddableConfig as any).vis.defaultColors['0+-+100']).toBe('rgb(0,104,55)'); -}); - -test('migrates 6.0 even when uiState does not exist', async () => { - const appState = { - panels: [ - { - col: 1, - id: 'Visualization-MetricChart', - panelIndex: 1, - row: 1, - size_x: 6, - size_y: 3, - type: 'visualization', - sort: 'sort', - }, - ], - }; - migrateAppState(appState as any); - expect((appState as any).uiState).toBeUndefined(); - - const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; - expect(newPanel.gridData.w).toBe(24); - expect(newPanel.gridData.h).toBe(15); - expect((newPanel as any).sort).toBeUndefined(); - - expect((newPanel.embeddableConfig as any).sort).toBe('sort'); -}); - -test('6.2 migration adjusts w & h without margins', async () => { - const appState = { - panels: [ - { - id: 'Visualization-MetricChart', - panelIndex: 1, - gridData: { - h: 3, - w: 7, - x: 2, - y: 5, - }, - type: 'visualization', - sort: 'sort', - version: '6.2.0', - }, - ], - useMargins: false, - }; - migrateAppState(appState as any); - expect((appState as any).uiState).toBeUndefined(); - - const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; - expect(newPanel.gridData.w).toBe(28); - expect(newPanel.gridData.h).toBe(15); - expect(newPanel.gridData.x).toBe(8); - expect(newPanel.gridData.y).toBe(25); - expect((newPanel as any).sort).toBeUndefined(); - - expect((newPanel.embeddableConfig as any).sort).toBe('sort'); -}); - -test('6.2 migration adjusts w & h with margins', async () => { - const appState = { - panels: [ - { - id: 'Visualization-MetricChart', - panelIndex: 1, - gridData: { - h: 3, - w: 7, - x: 2, - y: 5, - }, - type: 'visualization', - sort: 'sort', - version: '6.2.0', - }, - ], - useMargins: true, - }; - migrateAppState(appState as any); - expect((appState as any).uiState).toBeUndefined(); - - const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; - expect(newPanel.gridData.w).toBe(28); - expect(newPanel.gridData.h).toBe(12); - expect(newPanel.gridData.x).toBe(8); - expect(newPanel.gridData.y).toBe(20); - expect((newPanel as any).sort).toBeUndefined(); - - expect((newPanel.embeddableConfig as any).sort).toBe('sort'); -}); diff --git a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts deleted file mode 100644 index e077aab89ea8b..0000000000000 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import semverSatisfies from 'semver/functions/satisfies'; - -import { i18n } from '@kbn/i18n'; -import { METRIC_TYPE } from '@kbn/analytics'; -import type { SerializableRecord } from '@kbn/utility-types'; - -import { RawDashboardState, SavedDashboardPanel } from '../../types'; -import type { - SavedDashboardPanelTo60, - SavedDashboardPanel730ToLatest, - SavedDashboardPanel610, - SavedDashboardPanel630, - SavedDashboardPanel640To720, - SavedDashboardPanel620, -} from '../../../common'; -import { migratePanelsTo730 } from '../../../common'; -import { pluginServices } from '../../services/plugin_services'; - -/** - * Attempts to migrate the state stored in the URL into the latest version of it. - * - * Once we hit a major version, we can remove support for older style URLs and get rid of this logic. - */ -export function migrateAppState( - appState: { [key: string]: any } & RawDashboardState -): RawDashboardState { - if (!appState.panels) { - throw new Error( - i18n.translate('dashboard.panel.invalidData', { - defaultMessage: 'Invalid data in url', - }) - ); - } - - const { - usageCollection: { reportUiCounter }, - initializerContext: { kibanaVersion }, - } = pluginServices.getServices(); - - const panelNeedsMigration = ( - appState.panels as Array< - | SavedDashboardPanelTo60 - | SavedDashboardPanel610 - | SavedDashboardPanel620 - | SavedDashboardPanel630 - | SavedDashboardPanel640To720 - | SavedDashboardPanel730ToLatest - > - ).some((panel) => { - if ((panel as { version?: string }).version === undefined) return true; - - const version = (panel as SavedDashboardPanel730ToLatest).version; - - if (reportUiCounter) { - // This will help us figure out when to remove support for older style URLs. - reportUiCounter('DashboardPanelVersionInUrl', METRIC_TYPE.LOADED, `${version}`); - } - - return semverSatisfies(version, '<7.3'); - }); - - if (panelNeedsMigration) { - appState.panels = migratePanelsTo730( - appState.panels as Array< - | SavedDashboardPanelTo60 - | SavedDashboardPanel610 - | SavedDashboardPanel620 - | SavedDashboardPanel630 - | SavedDashboardPanel640To720 - >, - kibanaVersion, - appState.useMargins as boolean, - appState.uiState as { [key: string]: SerializableRecord } - ) as SavedDashboardPanel[]; - delete appState.uiState; - } - - return appState; -} diff --git a/src/plugins/dashboard/public/application/lib/save_dashboard.ts b/src/plugins/dashboard/public/application/lib/save_dashboard.ts deleted file mode 100644 index f3347ca3f2041..0000000000000 --- a/src/plugins/dashboard/public/application/lib/save_dashboard.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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import _ from 'lodash'; - -import { isFilterPinned } from '@kbn/es-query'; -import type { RefreshInterval } from '@kbn/data-plugin/public'; -import type { SavedObjectSaveOpts } from '@kbn/saved-objects-plugin/public'; - -import { convertTimeToUTCString } from '.'; -import type { DashboardSavedObject } from '../../saved_dashboards'; -import { dashboardSaveToastStrings } from '../../dashboard_strings'; -import { getHasTaggingCapabilitiesGuard } from './dashboard_tagging'; -import type { DashboardRedirect, DashboardState } from '../../types'; -import { serializeControlGroupToDashboardSavedObject } from './dashboard_control_group'; -import { convertPanelStateToSavedDashboardPanel } from '../../../common/embeddable/embeddable_saved_object_converters'; -import { pluginServices } from '../../services/plugin_services'; - -export type SavedDashboardSaveOpts = SavedObjectSaveOpts & { stayInEditMode?: boolean }; - -interface SaveDashboardProps { - redirectTo: DashboardRedirect; - currentState: DashboardState; - saveOptions: SavedDashboardSaveOpts; - savedDashboard: DashboardSavedObject; -} - -export const saveDashboard = async ({ - redirectTo, - saveOptions, - currentState, - savedDashboard, -}: SaveDashboardProps): Promise<{ id?: string; redirected?: boolean; error?: any }> => { - const { - data: { - query: { - timefilter: { timefilter }, - }, - }, - dashboardSessionStorage, - initializerContext: { kibanaVersion }, - notifications, - } = pluginServices.getServices(); - - const lastDashboardId = savedDashboard.id; - const hasTaggingCapabilities = getHasTaggingCapabilitiesGuard(); - - const { panels, title, tags, description, timeRestore, options } = currentState; - - const savedDashboardPanels = Object.values(panels).map((panel) => - convertPanelStateToSavedDashboardPanel(panel, kibanaVersion) - ); - - savedDashboard.title = title; - savedDashboard.description = description; - savedDashboard.timeRestore = timeRestore; - savedDashboard.optionsJSON = JSON.stringify(options); - savedDashboard.panelsJSON = JSON.stringify(savedDashboardPanels); - - // control group input - serializeControlGroupToDashboardSavedObject(savedDashboard, currentState); - - if (hasTaggingCapabilities(savedDashboard)) { - savedDashboard.setTags(tags); - } - - const { from, to } = timefilter.getTime(); - savedDashboard.timeFrom = savedDashboard.timeRestore ? convertTimeToUTCString(from) : undefined; - savedDashboard.timeTo = savedDashboard.timeRestore ? convertTimeToUTCString(to) : undefined; - - const timeRestoreObj: RefreshInterval = _.pick(timefilter.getRefreshInterval(), [ - 'display', - 'pause', - 'section', - 'value', - ]) as RefreshInterval; - savedDashboard.refreshInterval = savedDashboard.timeRestore ? timeRestoreObj : undefined; - - // only save unpinned filters - const unpinnedFilters = savedDashboard.getFilters().filter((filter) => !isFilterPinned(filter)); - savedDashboard.searchSource.setField('filter', unpinnedFilters); - - try { - const newId = await savedDashboard.save(saveOptions); - if (newId) { - notifications.toasts.addSuccess({ - title: dashboardSaveToastStrings.getSuccessString(currentState.title), - 'data-test-subj': 'saveDashboardSuccess', - }); - - /** - * If the dashboard id has been changed, redirect to the new ID to keep the url param in sync. - */ - if (newId !== lastDashboardId) { - dashboardSessionStorage.clearState(lastDashboardId); - redirectTo({ - id: newId, - editMode: true, - useReplace: true, - destination: 'dashboard', - }); - return { redirected: true, id: newId }; - } - } - return { id: newId }; - } catch (error) { - notifications.toasts.addDanger( - dashboardSaveToastStrings.getFailureString(currentState.title, error.message), - { - 'data-test-subj': 'saveDashboardFailure', - } - ); - return { error }; - } -}; diff --git a/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts b/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts index 67e098186f9e9..9e97beaad276f 100644 --- a/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts +++ b/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts @@ -10,12 +10,11 @@ import _ from 'lodash'; import { Subscription } from 'rxjs'; import { debounceTime, tap } from 'rxjs/operators'; -import { compareFilters, COMPARE_ALL_OPTIONS, type Filter } from '@kbn/es-query'; +import { compareFilters, COMPARE_ALL_OPTIONS } from '@kbn/es-query'; import { replaceUrlHashQuery } from '@kbn/kibana-utils-plugin/public'; -import type { Query } from '@kbn/es-query'; import type { DashboardContainer } from '../embeddable'; -import { DashboardConstants, type DashboardSavedObject } from '../..'; +import { DashboardConstants } from '../..'; import { setControlGroupState, setExpandedPanelId, @@ -36,16 +35,13 @@ import { pluginServices } from '../../services/plugin_services'; type SyncDashboardContainerCommon = DashboardBuildContext & { dashboardContainer: DashboardContainer; - savedDashboard: DashboardSavedObject; }; type ApplyStateChangesToContainerProps = SyncDashboardContainerCommon & { force: boolean; }; -type ApplyContainerChangesToStateProps = SyncDashboardContainerCommon & { - applyFilters: (query: Query, filters: Filter[]) => void; -}; +type ApplyContainerChangesToStateProps = SyncDashboardContainerCommon; type SyncDashboardContainerProps = SyncDashboardContainerCommon & ApplyContainerChangesToStateProps; @@ -94,7 +90,6 @@ export const syncDashboardContainerInput = ( }; export const applyContainerChangesToState = ({ - applyFilters, dashboardContainer, getLatestDashboardState, dispatchDashboardStateChange, @@ -112,7 +107,6 @@ export const applyContainerChangesToState = ({ if (!compareFilters(input.filters, filterManager.getFilters(), COMPARE_ALL_OPTIONS)) { // Add filters modifies the object passed to it, hence the clone deep. filterManager.addFilters(_.cloneDeep(input.filters)); - applyFilters(latestState.query, input.filters); } if (!_.isEqual(input.panels, latestState.panels)) { @@ -144,7 +138,6 @@ export const applyContainerChangesToState = ({ export const applyStateChangesToContainer = ({ force, history, - savedDashboard, dashboardContainer, kbnUrlStateStorage, isEmbeddedExternally, @@ -161,7 +154,6 @@ export const applyStateChangesToContainer = ({ const currentDashboardStateAsInput = stateToDashboardContainerInput({ dashboardState: latestState, isEmbeddedExternally, - savedDashboard, }); const differences = diffDashboardContainerInput( dashboardContainer.getInput(), diff --git a/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts b/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts index d02e674936aef..0bce899e22fcd 100644 --- a/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts +++ b/src/plugins/dashboard/public/application/lib/sync_dashboard_filter_state.ts @@ -8,25 +8,22 @@ import _ from 'lodash'; import { merge } from 'rxjs'; -import { debounceTime, finalize, map, switchMap, tap } from 'rxjs/operators'; +import { finalize, map, switchMap, tap } from 'rxjs/operators'; import { connectToQueryState, GlobalQueryStateFromUrl, - syncQueryStateWithUrl, + syncGlobalQueryStateWithUrl, waitUntilNextSessionCompletes$, } from '@kbn/data-plugin/public'; import type { Filter, Query } from '@kbn/es-query'; import { cleanFiltersForSerialize } from '.'; -import { setQuery } from '../state'; import type { DashboardBuildContext, DashboardState } from '../../types'; -import type { DashboardSavedObject } from '../../saved_dashboards'; import { setFiltersAndQuery } from '../state/dashboard_state_slice'; import { pluginServices } from '../../services/plugin_services'; type SyncDashboardFilterStateProps = DashboardBuildContext & { initialDashboardState: DashboardState; - savedDashboard: DashboardSavedObject; }; /** @@ -35,7 +32,6 @@ type SyncDashboardFilterStateProps = DashboardBuildContext & { * and the dashboard Redux store. */ export const syncDashboardFilterState = ({ - savedDashboard, kbnUrlStateStorage, initialDashboardState, $checkForUnsavedChanges, @@ -46,25 +42,17 @@ export const syncDashboardFilterState = ({ const { data: { query: queryService, search }, } = pluginServices.getServices(); - const { filterManager, queryString, timefilter } = queryService; + const { queryString, timefilter } = queryService; const { timefilter: timefilterService } = timefilter; // apply initial dashboard filter state. applyDashboardFilterState({ currentDashboardState: initialDashboardState, kbnUrlStateStorage, - savedDashboard, }); - // this callback will be used any time new filters and query need to be applied. - const applyFilters = (query: Query, filters: Filter[]) => { - savedDashboard.searchSource.setField('query', query); - savedDashboard.searchSource.setField('filter', filters); - dispatchDashboardStateChange(setQuery(query)); - }; - // starts syncing `_g` portion of url with query services - const { stop: stopSyncingQueryServiceStateWithUrl } = syncQueryStateWithUrl( + const { stop: stopSyncingQueryServiceStateWithUrl } = syncGlobalQueryStateWithUrl( queryService, kbnUrlStateStorage ); @@ -81,7 +69,6 @@ export const syncDashboardFilterState = ({ set: ({ filters, query }) => { intermediateFilterState.filters = cleanFiltersForSerialize(filters ?? []) || []; intermediateFilterState.query = query || queryString.getDefaultQuery(); - applyFilters(intermediateFilterState.query, intermediateFilterState.filters); dispatchDashboardStateChange(setFiltersAndQuery(intermediateFilterState)); }, state$: $onDashboardStateChange.pipe( @@ -97,11 +84,6 @@ export const syncDashboardFilterState = ({ } ); - // apply filters when the filter manager changes - const filterManagerSubscription = merge(filterManager.getUpdates$(), queryString.getUpdates$()) - .pipe(debounceTime(100)) - .subscribe(() => applyFilters(queryString.getQuery() as Query, filterManager.getFilters())); - const timeRefreshSubscription = merge( timefilterService.getRefreshIntervalUpdate$(), timefilterService.getTimeUpdate$() @@ -127,26 +109,23 @@ export const syncDashboardFilterState = ({ .subscribe(); const stopSyncingDashboardFilterState = () => { - filterManagerSubscription.unsubscribe(); forceRefreshSubscription.unsubscribe(); timeRefreshSubscription.unsubscribe(); stopSyncingQueryServiceStateWithUrl(); stopSyncingAppFilters(); }; - return { applyFilters, stopSyncingDashboardFilterState }; + return { stopSyncingDashboardFilterState }; }; interface ApplyDashboardFilterStateProps { kbnUrlStateStorage: DashboardBuildContext['kbnUrlStateStorage']; currentDashboardState: DashboardState; - savedDashboard: DashboardSavedObject; } export const applyDashboardFilterState = ({ currentDashboardState, kbnUrlStateStorage, - savedDashboard, }: ApplyDashboardFilterStateProps) => { const { data: { @@ -155,13 +134,9 @@ export const applyDashboardFilterState = ({ } = pluginServices.getServices(); const { timefilter: timefilterService } = timefilter; - // apply filters to the query service and to the saved dashboard + // apply filters and query to the query service filterManager.setAppFilters(_.cloneDeep(currentDashboardState.filters)); - savedDashboard.searchSource.setField('filter', currentDashboardState.filters); - - // apply query to the query service and to the saved dashboard queryString.setQuery(currentDashboardState.query); - savedDashboard.searchSource.setField('query', currentDashboardState.query); /** * If a global time range is not set explicitly and the time range was saved with the dashboard, apply @@ -169,18 +144,11 @@ export const applyDashboardFilterState = ({ */ if (currentDashboardState.timeRestore) { const globalQueryState = kbnUrlStateStorage.get('_g'); - if (!globalQueryState?.time) { - if (savedDashboard.timeFrom && savedDashboard.timeTo) { - timefilterService.setTime({ - from: savedDashboard.timeFrom, - to: savedDashboard.timeTo, - }); - } + if (!globalQueryState?.time && currentDashboardState.timeRange) { + timefilterService.setTime(currentDashboardState.timeRange); } - if (!globalQueryState?.refreshInterval) { - if (savedDashboard.refreshInterval) { - timefilterService.setRefreshInterval(savedDashboard.refreshInterval); - } + if (!globalQueryState?.refreshInterval && currentDashboardState.refreshInterval) { + timefilterService.setRefreshInterval(currentDashboardState.refreshInterval); } } }; diff --git a/src/plugins/dashboard/public/application/lib/sync_dashboard_url_state.ts b/src/plugins/dashboard/public/application/lib/sync_dashboard_url_state.ts index 947e3f5d69de7..31101ae3679f0 100644 --- a/src/plugins/dashboard/public/application/lib/sync_dashboard_url_state.ts +++ b/src/plugins/dashboard/public/application/lib/sync_dashboard_url_state.ts @@ -8,41 +8,52 @@ import _ from 'lodash'; import { debounceTime } from 'rxjs/operators'; +import semverSatisfies from 'semver/functions/satisfies'; import { replaceUrlHashQuery } from '@kbn/kibana-utils-plugin/public'; -import { migrateAppState } from '.'; -import { DashboardSavedObject } from '../..'; + import { setDashboardState } from '../state'; import { migrateLegacyQuery } from './migrate_legacy_query'; -import { applyDashboardFilterState } from './sync_dashboard_filter_state'; +import { pluginServices } from '../../services/plugin_services'; import { DASHBOARD_STATE_STORAGE_KEY } from '../../dashboard_constants'; -import type { - DashboardBuildContext, - DashboardPanelMap, - DashboardState, - RawDashboardState, -} from '../../types'; -import { convertSavedPanelsToPanelMap } from './convert_dashboard_panels'; +import { applyDashboardFilterState } from './sync_dashboard_filter_state'; +import { dashboardSavedObjectErrorStrings } from '../../dashboard_strings'; +import { convertSavedPanelsToPanelMap, DashboardPanelMap } from '../../../common'; +import type { DashboardBuildContext, DashboardState, RawDashboardState } from '../../types'; -type SyncDashboardUrlStateProps = DashboardBuildContext & { savedDashboard: DashboardSavedObject }; +/** + * We no longer support loading panels from a version older than 7.3 in the URL. + * @returns whether or not there is a panel in the URL state saved with a version before 7.3 + */ +export const isPanelVersionTooOld = (panels: RawDashboardState['panels']) => { + for (const panel of panels) { + if (!panel.version || semverSatisfies(panel.version, '<7.3')) return true; + } + return false; +}; export const syncDashboardUrlState = ({ dispatchDashboardStateChange, getLatestDashboardState, kbnUrlStateStorage, - savedDashboard, -}: SyncDashboardUrlStateProps) => { +}: DashboardBuildContext) => { /** * Loads any dashboard state from the URL, and removes the state from the URL. */ const loadAndRemoveDashboardState = (): Partial => { + const { + notifications: { toasts }, + } = pluginServices.getServices(); const rawAppStateInUrl = kbnUrlStateStorage.get(DASHBOARD_STATE_STORAGE_KEY); if (!rawAppStateInUrl) return {}; - let panelsMap: DashboardPanelMap = {}; + let panelsMap: DashboardPanelMap | undefined; if (rawAppStateInUrl.panels && rawAppStateInUrl.panels.length > 0) { - const rawState = migrateAppState(rawAppStateInUrl); - panelsMap = convertSavedPanelsToPanelMap(rawState.panels); + if (isPanelVersionTooOld(rawAppStateInUrl.panels)) { + toasts.addWarning(dashboardSavedObjectErrorStrings.getPanelTooOldError()); + } else { + panelsMap = convertSavedPanelsToPanelMap(rawAppStateInUrl.panels); + } } const migratedQuery = rawAppStateInUrl.query @@ -58,7 +69,7 @@ export const syncDashboardUrlState = ({ return { ..._.omit(rawAppStateInUrl, ['panels', 'query']), ...(migratedQuery ? { query: migratedQuery } : {}), - ...(rawAppStateInUrl.panels ? { panels: panelsMap } : {}), + ...(panelsMap ? { panels: panelsMap } : {}), }; }; @@ -75,7 +86,6 @@ export const syncDashboardUrlState = ({ applyDashboardFilterState({ currentDashboardState: updatedDashboardState, kbnUrlStateStorage, - savedDashboard, }); if (Object.keys(stateFromUrl).length === 0) return; diff --git a/src/plugins/dashboard/public/application/lib/url.test.ts b/src/plugins/dashboard/public/application/lib/url.test.ts deleted file mode 100644 index fc7e51b8c2e3e..0000000000000 --- a/src/plugins/dashboard/public/application/lib/url.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { getDashboardIdFromUrl } from './url'; - -test('getDashboardIdFromUrl', () => { - let url = - "http://localhost:5601/wev/app/dashboards#/create?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(description:'',filters:!()"; - expect(getDashboardIdFromUrl(url)).toEqual(undefined); - - url = - "http://localhost:5601/wev/app/dashboards#/view/625357282?_a=(description:'',filters:!()&_g=(refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))"; - expect(getDashboardIdFromUrl(url)).toEqual('625357282'); - - url = 'http://myserver.mydomain.com:5601/wev/app/dashboards#/view/777182'; - expect(getDashboardIdFromUrl(url)).toEqual('777182'); - - url = - "http://localhost:5601/app/dashboards#/create?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(description:'',filters:!()"; - expect(getDashboardIdFromUrl(url)).toEqual(undefined); - - url = '/view/test/?_g=(refreshInterval:'; - expect(getDashboardIdFromUrl(url)).toEqual('test'); - - url = 'view/test/?_g=(refreshInterval:'; - expect(getDashboardIdFromUrl(url)).toEqual('test'); - - url = '/other-app/test/'; - expect(getDashboardIdFromUrl(url)).toEqual(undefined); -}); diff --git a/src/plugins/dashboard/public/application/lib/url.ts b/src/plugins/dashboard/public/application/lib/url.ts deleted file mode 100644 index 0ff2809a92667..0000000000000 --- a/src/plugins/dashboard/public/application/lib/url.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -/** - * Returns dashboard id from URL - * literally looks from id after `dashboard/` string and before `/`, `?` and end of string - * @param url to extract dashboardId from - * input: http://localhost:5601/lib/app/kibana#/dashboard?param1=x¶m2=y¶m3=z - * output: undefined - * input: http://localhost:5601/lib/app/kibana#/dashboard/39292992?param1=x¶m2=y¶m3=z - * output: 39292992 - */ -export function getDashboardIdFromUrl(url: string): string | undefined { - const [, dashboardId] = url.match(/view\/(.*?)(\/|\?|$)/) ?? [ - undefined, // full match - undefined, // group with dashboardId - ]; - return dashboardId ?? undefined; -} diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.tsx b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.tsx index 5712b4c6ee2f8..4a77249aeb39c 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.tsx @@ -9,19 +9,15 @@ import React from 'react'; import { mount } from 'enzyme'; -import { I18nProvider, FormattedRelative } from '@kbn/i18n-react'; -import { SimpleSavedObject } from '@kbn/core/public'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; import { TableListViewKibanaDependencies, TableListViewKibanaProvider, } from '@kbn/content-management-table-list'; +import { I18nProvider, FormattedRelative } from '@kbn/i18n-react'; +import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; -import { DashboardAppServices } from '../../types'; -import { DashboardListing, DashboardListingProps } from './dashboard_listing'; -import { makeDefaultServices } from '../test_helpers'; import { pluginServices } from '../../services/plugin_services'; +import { DashboardListing, DashboardListingProps } from './dashboard_listing'; import { DASHBOARD_PANELS_UNSAVED_ID } from '../../services/dashboard_session_storage/dashboard_session_storage_service'; function makeDefaultProps(): DashboardListingProps { @@ -31,14 +27,7 @@ function makeDefaultProps(): DashboardListingProps { }; } -function mountWith({ - props: incomingProps, - services: incomingServices, -}: { - props?: DashboardListingProps; - services?: DashboardAppServices; -}) { - const services = incomingServices ?? makeDefaultServices(); +function mountWith({ props: incomingProps }: { props?: DashboardListingProps }) { const props = incomingProps ?? makeDefaultProps(); const wrappingComponent: React.FC<{ children: React.ReactNode; @@ -47,35 +36,32 @@ function mountWith({ return ( - {/* Can't get rid of KibanaContextProvider here yet because of 'call to action when no dashboards exist' tests below */} - - null, - }, + null, }, - } as unknown as TableListViewKibanaDependencies['savedObjectsTagging'] - } - FormattedRelative={FormattedRelative} - toMountPoint={() => () => () => undefined} - > - {children} - - + }, + } as unknown as TableListViewKibanaDependencies['savedObjectsTagging'] + } + FormattedRelative={FormattedRelative} + toMountPoint={() => () => () => undefined} + > + {children} + ); }; const component = mount(, { wrappingComponent }); - return { component, props, services }; + return { component, props }; } describe('after fetch', () => { @@ -89,14 +75,14 @@ describe('after fetch', () => { }); test('renders call to action when no dashboards exist', async () => { - const services = makeDefaultServices(); - services.savedDashboards.find = () => { - return Promise.resolve({ - total: 0, - hits: [], - }); - }; - const { component } = mountWith({ services }); + ( + pluginServices.getServices().dashboardSavedObject.findDashboards.findSavedObjects as jest.Mock + ).mockResolvedValue({ + total: 0, + hits: [], + }); + + const { component } = mountWith({}); // Ensure all promises resolve await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected @@ -105,18 +91,18 @@ describe('after fetch', () => { }); test('renders call to action with continue when no dashboards exist but one is in progress', async () => { - const services = makeDefaultServices(); - services.savedDashboards.find = () => { - return Promise.resolve({ - total: 0, - hits: [], - }); - }; pluginServices.getServices().dashboardSessionStorage.getDashboardIdsWithUnsavedChanges = jest .fn() .mockReturnValueOnce([DASHBOARD_PANELS_UNSAVED_ID]) .mockReturnValue(['dashboardUnsavedOne', 'dashboardUnsavedTwo']); - const { component } = mountWith({ services }); + ( + pluginServices.getServices().dashboardSavedObject.findDashboards.findSavedObjects as jest.Mock + ).mockResolvedValue({ + total: 0, + hits: [], + }); + + const { component } = mountWith({}); // Ensure all promises resolve await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected @@ -139,17 +125,9 @@ describe('after fetch', () => { const title = 'search by title'; const props = makeDefaultProps(); props.title = title; - pluginServices.getServices().savedObjects.client.find = () => { - return Promise.resolve({ - perPage: 10, - total: 2, - page: 0, - savedObjects: [ - { attributes: { title: `${title}_number1` }, id: 'hello there' } as SimpleSavedObject, - { attributes: { title: `${title}_number2` }, id: 'goodbye' } as SimpleSavedObject, - ], - }); - }; + ( + pluginServices.getServices().dashboardSavedObject.findDashboards.findByTitle as jest.Mock + ).mockResolvedValue(undefined); const { component } = mountWith({ props }); // Ensure all promises resolve await new Promise((resolve) => process.nextTick(resolve)); @@ -163,14 +141,9 @@ describe('after fetch', () => { const title = 'search by title'; const props = makeDefaultProps(); props.title = title; - pluginServices.getServices().savedObjects.client.find = () => { - return Promise.resolve({ - perPage: 10, - total: 1, - page: 0, - savedObjects: [{ attributes: { title }, id: 'you_found_me' } as SimpleSavedObject], - }); - }; + ( + pluginServices.getServices().dashboardSavedObject.findDashboards.findByTitle as jest.Mock + ).mockResolvedValue({ id: 'you_found_me' }); const { component } = mountWith({ props }); // Ensure all promises resolve await new Promise((resolve) => process.nextTick(resolve)); diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx index 40753c556a56a..1e78b94303478 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx @@ -6,7 +6,10 @@ * Side Public License, v 1. */ +import useMount from 'react-use/lib/useMount'; import { FormattedMessage } from '@kbn/i18n-react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; + import { EuiLink, EuiButton, @@ -15,30 +18,29 @@ import { EuiFlexItem, EuiButtonEmpty, } from '@elastic/eui'; -import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import type { SavedObjectsFindOptionsReference } from '@kbn/core/public'; -import useMount from 'react-use/lib/useMount'; -import type { SavedObjectReference } from '@kbn/core/types'; -import { useExecutionContext, useKibana } from '@kbn/kibana-react-plugin/public'; +import { useExecutionContext } from '@kbn/kibana-react-plugin/public'; import { syncGlobalQueryStateWithUrl } from '@kbn/data-plugin/public'; +import type { SavedObjectsFindOptionsReference, SimpleSavedObject } from '@kbn/core/public'; import type { IKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; import { TableListView, type UserContentCommonSchema } from '@kbn/content-management-table-list'; -import { attemptLoadDashboardByTitle } from '../lib'; -import { DashboardAppServices, DashboardRedirect } from '../../types'; import { getDashboardBreadcrumb, - dashboardListingTable, + dashboardListingTableStrings, noItemsStrings, dashboardUnsavedListingStrings, getNewDashboardTitle, + dashboardSavedObjectErrorStrings, } from '../../dashboard_strings'; +import { DashboardConstants } from '../..'; +import { DashboardRedirect } from '../../types'; +import { pluginServices } from '../../services/plugin_services'; import { DashboardUnsavedListing } from './dashboard_unsaved_listing'; -import { confirmCreateWithUnsaved, confirmDiscardUnsavedChanges } from './confirm_overlays'; import { getDashboardListItemLink } from './get_dashboard_list_item_link'; +import { confirmCreateWithUnsaved, confirmDiscardUnsavedChanges } from './confirm_overlays'; import { DashboardAppNoDataPage, isDashboardAppInNoDataState } from '../dashboard_app_no_data'; -import { pluginServices } from '../../services/plugin_services'; import { DASHBOARD_PANELS_UNSAVED_ID } from '../../services/dashboard_session_storage/dashboard_session_storage_service'; +import { DashboardAttributes } from '../embeddable'; const SAVED_OBJECTS_LIMIT_SETTING = 'savedObjects:listingLimit'; const SAVED_OBJECTS_PER_PAGE_SETTING = 'savedObjects:perPage'; @@ -52,17 +54,18 @@ interface DashboardSavedObjectUserContent extends UserContentCommonSchema { } const toTableListViewSavedObject = ( - savedObject: Record + savedObject: SimpleSavedObject ): DashboardSavedObjectUserContent => { + const { title, description, timeRestore } = savedObject.attributes; return { - id: savedObject.id as string, - updatedAt: savedObject.updatedAt! as string, - references: savedObject.references as SavedObjectReference[], type: 'dashboard', + id: savedObject.id, + updatedAt: savedObject.updatedAt!, + references: savedObject.references, attributes: { - title: (savedObject.title as string) ?? '', - description: savedObject.description as string, - timeRestore: savedObject.timeRestore as boolean, + title, + description, + timeRestore, }, }; }; @@ -80,19 +83,16 @@ export const DashboardListing = ({ initialFilter, kbnUrlStateStorage, }: DashboardListingProps) => { - const { - services: { savedDashboards }, - } = useKibana(); - const { application, + data: { query }, + dashboardSessionStorage, + settings: { uiSettings }, + notifications: { toasts }, chrome: { setBreadcrumbs }, coreContext: { executionContext }, dashboardCapabilities: { showWriteControls }, - dashboardSessionStorage, - data: { query }, - savedObjects: { client }, - settings: { uiSettings }, + dashboardSavedObject: { findDashboards, savedObjectsClient }, } = pluginServices.getServices(); const [showNoDataPage, setShowNoDataPage] = useState(false); @@ -125,7 +125,7 @@ export const DashboardListing = ({ kbnUrlStateStorage ); if (title) { - attemptLoadDashboardByTitle(title).then((result) => { + findDashboards.findByTitle(title).then((result) => { if (!result) return; redirectTo({ destination: 'dashboard', @@ -138,7 +138,7 @@ export const DashboardListing = ({ return () => { stopSyncingQueryServiceStateWithUrl(); }; - }, [title, client, redirectTo, query, kbnUrlStateStorage]); + }, [title, redirectTo, query, kbnUrlStateStorage, findDashboards]); const listingLimit = uiSettings.get(SAVED_OBJECTS_LIMIT_SETTING); const initialPageSize = uiSettings.get(SAVED_OBJECTS_PER_PAGE_SETTING); @@ -262,10 +262,11 @@ export const DashboardListing = ({ const fetchItems = useCallback( (searchTerm: string, references?: SavedObjectsFindOptionsReference[]) => { - return savedDashboards - .find(searchTerm, { - hasReference: references, + return findDashboards + .findSavedObjects({ + search: searchTerm, size: listingLimit, + hasReference: references, }) .then(({ total, hits }) => { return { @@ -274,16 +275,24 @@ export const DashboardListing = ({ }; }); }, - [listingLimit, savedDashboards] + [findDashboards, listingLimit] ); const deleteItems = useCallback( - (dashboards: Array<{ id: string }>) => { - dashboards.map((d) => dashboardSessionStorage.clearState(d.id)); + async (dashboardsToDelete: Array<{ id: string }>) => { + await Promise.all( + dashboardsToDelete.map(({ id }) => { + dashboardSessionStorage.clearState(id); + return savedObjectsClient.delete(DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, id); + }) + ).catch((error) => { + toasts.addError(error, { + title: dashboardSavedObjectErrorStrings.getErrorDeletingDashboardToast(), + }); + }); setUnsavedDashboardIds(dashboardSessionStorage.getDashboardIdsWithUnsavedChanges()); - return savedDashboards.delete(dashboards.map((d) => d.id)); }, - [savedDashboards, dashboardSessionStorage] + [savedObjectsClient, dashboardSessionStorage, toasts] ); const editItem = useCallback( @@ -292,7 +301,7 @@ export const DashboardListing = ({ [redirectTo] ); - const { getEntityName, getTableListTitle, getEntityNamePlural } = dashboardListingTable; + const { getEntityName, getTableListTitle, getEntityNamePlural } = dashboardListingTableStrings; return ( <> {showNoDataPage && ( diff --git a/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.test.tsx b/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.test.tsx index 1feec9bbdc42f..34a78c5181b92 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.test.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.test.tsx @@ -11,87 +11,46 @@ import { mount } from 'enzyme'; import { I18nProvider } from '@kbn/i18n-react'; import { waitFor } from '@testing-library/react'; import { findTestSubject } from '@elastic/eui/lib/test'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { DashboardSavedObject } from '../..'; -import { DashboardAppServices } from '../../types'; -import { makeDefaultServices } from '../test_helpers'; -import { SavedObjectLoader } from '../../services/saved_object_loader'; import { DashboardUnsavedListing, DashboardUnsavedListingProps } from './dashboard_unsaved_listing'; import { DASHBOARD_PANELS_UNSAVED_ID } from '../../services/dashboard_session_storage/dashboard_session_storage_service'; import { pluginServices } from '../../services/plugin_services'; -const mockedDashboards: { [key: string]: DashboardSavedObject } = { - dashboardUnsavedOne: { - id: `dashboardUnsavedOne`, - title: `Dashboard Unsaved One`, - } as DashboardSavedObject, - dashboardUnsavedTwo: { - id: `dashboardUnsavedTwo`, - title: `Dashboard Unsaved Two`, - } as DashboardSavedObject, - dashboardUnsavedThree: { - id: `dashboardUnsavedThree`, - title: `Dashboard Unsaved Three`, - } as DashboardSavedObject, -}; - -function makeServices(): DashboardAppServices { - const services = makeDefaultServices(); - const savedDashboards = {} as SavedObjectLoader; - savedDashboards.get = jest - .fn() - .mockImplementation((id: string) => Promise.resolve(mockedDashboards[id])); - return { - ...services, - savedDashboards, - }; -} - const makeDefaultProps = (): DashboardUnsavedListingProps => ({ redirectTo: jest.fn(), unsavedDashboardIds: ['dashboardUnsavedOne', 'dashboardUnsavedTwo', 'dashboardUnsavedThree'], refreshUnsavedDashboards: jest.fn(), }); -function mountWith({ - services: incomingServices, - props: incomingProps, -}: { - services?: DashboardAppServices; - props?: DashboardUnsavedListingProps; -}) { - const services = incomingServices ?? makeServices(); +function mountWith({ props: incomingProps }: { props?: DashboardUnsavedListingProps }) { const props = incomingProps ?? makeDefaultProps(); const wrappingComponent: React.FC<{ children: React.ReactNode; }> = ({ children }) => { - return ( - - {/* Only the old savedObjects service is used for `DashboardUnsavedListing`, so will need to wrap this in - `DashboardServicesProvider` instead once that is removed as part of https://github.com/elastic/kibana/pull/138774*/} - {children} - - ); + return {children}; }; const component = mount(, { wrappingComponent }); - return { component, props, services }; + return { component, props }; } describe('Unsaved listing', () => { it('Gets information for each unsaved dashboard', async () => { - const { services } = mountWith({}); + mountWith({}); await waitFor(() => { - expect(services.savedDashboards.get).toHaveBeenCalledTimes(3); + expect( + pluginServices.getServices().dashboardSavedObject.findDashboards.findByIds + ).toHaveBeenCalledTimes(1); }); }); - it('Does not attempt to get unsaved dashboard id', async () => { + it('Does not attempt to get newly created dashboard', async () => { const props = makeDefaultProps(); props.unsavedDashboardIds = ['dashboardUnsavedOne', DASHBOARD_PANELS_UNSAVED_ID]; - const { services } = mountWith({ props }); + mountWith({ props }); await waitFor(() => { - expect(services.savedDashboards.get).toHaveBeenCalledTimes(1); + expect( + pluginServices.getServices().dashboardSavedObject.findDashboards.findByIds + ).toHaveBeenCalledWith(['dashboardUnsavedOne']); }); }); @@ -146,14 +105,22 @@ describe('Unsaved listing', () => { }); it('removes unsaved changes from any dashboard which errors on fetch', async () => { - const services = makeServices(); + ( + pluginServices.getServices().dashboardSavedObject.findDashboards.findByIds as jest.Mock + ).mockResolvedValue([ + { + id: 'failCase1', + status: 'error', + error: { error: 'oh no', message: 'bwah', statusCode: 100 }, + }, + { + id: 'failCase2', + status: 'error', + error: { error: 'oh no', message: 'bwah', statusCode: 100 }, + }, + ]); + const props = makeDefaultProps(); - services.savedDashboards.get = jest.fn().mockImplementation((id: string) => { - if (id === 'failCase1' || id === 'failCase2') { - return Promise.reject(new Error()); - } - return Promise.resolve(mockedDashboards[id]); - }); props.unsavedDashboardIds = [ 'dashboardUnsavedOne', @@ -162,7 +129,7 @@ describe('Unsaved listing', () => { 'failCase1', 'failCase2', ]; - const { component } = mountWith({ services, props }); + const { component } = mountWith({ props }); waitFor(() => { component.update(); expect(pluginServices.getServices().dashboardSessionStorage.clearState).toHaveBeenCalledWith( diff --git a/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.tsx b/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.tsx index a5c5b1b224a32..3aa862fe30264 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_unsaved_listing.tsx @@ -6,8 +6,6 @@ * Side Public License, v 1. */ -import React, { useCallback, useEffect, useState } from 'react'; - import { EuiButtonEmpty, EuiCallOut, @@ -17,14 +15,14 @@ import { EuiSpacer, EuiTitle, } from '@elastic/eui'; -import { useKibana } from '@kbn/kibana-react-plugin/public'; +import React, { useCallback, useEffect, useState } from 'react'; -import type { DashboardSavedObject } from '../..'; -import { dashboardUnsavedListingStrings, getNewDashboardTitle } from '../../dashboard_strings'; -import type { DashboardAppServices, DashboardRedirect } from '../../types'; -import { confirmDiscardUnsavedChanges } from './confirm_overlays'; +import type { DashboardRedirect } from '../../types'; import { pluginServices } from '../../services/plugin_services'; +import { confirmDiscardUnsavedChanges } from './confirm_overlays'; +import { dashboardUnsavedListingStrings, getNewDashboardTitle } from '../../dashboard_strings'; import { DASHBOARD_PANELS_UNSAVED_ID } from '../../services/dashboard_session_storage/dashboard_session_storage_service'; +import { DashboardAttributes } from '../embeddable'; const DashboardUnsavedItem = ({ id, @@ -102,7 +100,7 @@ const DashboardUnsavedItem = ({ }; interface UnsavedItemMap { - [key: string]: DashboardSavedObject; + [key: string]: DashboardAttributes; } export interface DashboardUnsavedListingProps { @@ -117,10 +115,9 @@ export const DashboardUnsavedListing = ({ refreshUnsavedDashboards, }: DashboardUnsavedListingProps) => { const { - services: { savedDashboards }, - } = useKibana(); - - const { dashboardSessionStorage } = pluginServices.getServices(); + dashboardSessionStorage, + dashboardSavedObject: { savedObjectsClient, findDashboards }, + } = pluginServices.getServices(); const [items, setItems] = useState({}); @@ -146,28 +143,24 @@ export const DashboardUnsavedListing = ({ return; } let canceled = false; - const dashPromises = unsavedDashboardIds - .filter((id) => id !== DASHBOARD_PANELS_UNSAVED_ID) - .map((dashboardId) => { - return (savedDashboards.get(dashboardId) as Promise).catch( - () => dashboardId - ); - }); - Promise.all(dashPromises).then((dashboards: Array) => { + const existingDashboardsWithUnsavedChanges = unsavedDashboardIds.filter( + (id) => id !== DASHBOARD_PANELS_UNSAVED_ID + ); + findDashboards.findByIds(existingDashboardsWithUnsavedChanges).then((results) => { const dashboardMap = {}; if (canceled) { return; } let hasError = false; - const newItems = dashboards.reduce((map, dashboard) => { - if (typeof dashboard === 'string') { + const newItems = results.reduce((map, result) => { + if (result.status === 'error') { hasError = true; - dashboardSessionStorage.clearState(dashboard); + dashboardSessionStorage.clearState(result.id); return map; } return { ...map, - [dashboard.id || DASHBOARD_PANELS_UNSAVED_ID]: dashboard, + [result.id || DASHBOARD_PANELS_UNSAVED_ID]: result.attributes, }; }, dashboardMap); if (hasError) { @@ -179,7 +172,13 @@ export const DashboardUnsavedListing = ({ return () => { canceled = true; }; - }, [savedDashboards, dashboardSessionStorage, refreshUnsavedDashboards, unsavedDashboardIds]); + }, [ + refreshUnsavedDashboards, + dashboardSessionStorage, + unsavedDashboardIds, + savedObjectsClient, + findDashboards, + ]); return unsavedDashboardIds.length === 0 ? null : ( <> diff --git a/src/plugins/dashboard/public/application/state/dashboard_state_slice.ts b/src/plugins/dashboard/public/application/state/dashboard_state_slice.ts index f28d095c9b9b4..669bde5c3eb65 100644 --- a/src/plugins/dashboard/public/application/state/dashboard_state_slice.ts +++ b/src/plugins/dashboard/public/application/state/dashboard_state_slice.ts @@ -7,11 +7,14 @@ */ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; -import { PersistableControlGroupInput } from '@kbn/controls-plugin/common'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; +import { ViewMode } from '@kbn/embeddable-plugin/public'; +import { RefreshInterval } from '@kbn/data-plugin/common'; import type { Filter, Query, TimeRange } from '@kbn/es-query'; -import type { DashboardOptions, DashboardPanelMap, DashboardState } from '../../types'; +import { PersistableControlGroupInput } from '@kbn/controls-plugin/common'; + +import { DashboardPanelMap } from '../../../common'; +import type { DashboardOptions, DashboardState } from '../../types'; export const dashboardStateSlice = createSlice({ name: 'dashboardState', @@ -33,11 +36,15 @@ export const dashboardStateSlice = createSlice({ description: string; tags?: string[]; timeRestore: boolean; + timeRange?: TimeRange; + refreshInterval?: RefreshInterval; }> ) => { state.title = action.payload.title; state.description = action.payload.description; state.timeRestore = action.payload.timeRestore; + state.timeRange = action.payload.timeRange; + state.refreshInterval = action.payload.refreshInterval; if (action.payload.tags) { state.tags = action.payload.tags; } diff --git a/src/plugins/dashboard/public/application/test_helpers/get_saved_dashboard_mock.ts b/src/plugins/dashboard/public/application/test_helpers/get_saved_dashboard_mock.ts deleted file mode 100644 index 69da1dbbe56a2..0000000000000 --- a/src/plugins/dashboard/public/application/test_helpers/get_saved_dashboard_mock.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { dataPluginMock } from '@kbn/data-plugin/public/mocks'; -import { DashboardSavedObject } from '../../saved_dashboards'; - -export function getSavedDashboardMock( - config?: Partial -): DashboardSavedObject { - const searchSource = dataPluginMock.createStartContract(); - - return { - id: '123', - title: 'my dashboard', - panelsJSON: '[]', - searchSource: searchSource.search.searchSource.create(), - copyOnSave: false, - timeRestore: false, - timeTo: 'now', - timeFrom: 'now-15m', - optionsJSON: '', - lastSavedTitle: '', - destroy: () => {}, - save: () => { - return Promise.resolve('123'); - }, - getQuery: () => ({ query: '', language: 'kuery' }), - getFilters: () => [], - ...config, - } as DashboardSavedObject; -} diff --git a/src/plugins/dashboard/public/application/test_helpers/index.ts b/src/plugins/dashboard/public/application/test_helpers/index.ts index 7c8ae86074a46..c4d149e8c10b2 100644 --- a/src/plugins/dashboard/public/application/test_helpers/index.ts +++ b/src/plugins/dashboard/public/application/test_helpers/index.ts @@ -7,6 +7,4 @@ */ export { getSampleDashboardInput, getSampleDashboardPanel } from './get_sample_dashboard_input'; -export { getSavedDashboardMock } from './get_saved_dashboard_mock'; -export { makeDefaultServices } from './make_default_services'; export { setupIntersectionObserverMock } from './intersection_observer_mock'; diff --git a/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts b/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts deleted file mode 100644 index 3ffe9dc3b70e9..0000000000000 --- a/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts +++ /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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { - SavedObjectLoader, - type SavedObjectLoaderFindOptions, -} from '../../services/saved_object_loader'; -import { DashboardAppServices } from '../../types'; -import { getSavedDashboardMock } from './get_saved_dashboard_mock'; - -// TODO: Remove as part of https://github.com/elastic/kibana/pull/138774 -export function makeDefaultServices(): DashboardAppServices { - const savedDashboards = {} as SavedObjectLoader; - savedDashboards.find = (search: string, sizeOrOptions: number | SavedObjectLoaderFindOptions) => { - const size = typeof sizeOrOptions === 'number' ? sizeOrOptions : sizeOrOptions.size ?? 10; - const hits = []; - for (let i = 0; i < size; i++) { - hits.push({ - id: `dashboard${i}`, - title: `dashboard${i} - ${search} - title`, - description: `dashboard${i} desc`, - references: [], - timeRestore: true, - type: '', - url: '', - updatedAt: '', - panelsJSON: '', - lastSavedTitle: '', - }); - } - return Promise.resolve({ - total: size, - hits, - }); - }; - savedDashboards.get = jest - .fn() - .mockImplementation((id?: string) => Promise.resolve(getSavedDashboardMock({ id }))); - - return { - savedDashboards, - }; -} diff --git a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx index 86fd56c2ec6a0..97630c48dc784 100644 --- a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx +++ b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx @@ -6,46 +6,32 @@ * Side Public License, v 1. */ -import { METRIC_TYPE } from '@kbn/analytics'; -import { Required } from '@kbn/utility-types'; -import { EuiHorizontalRule } from '@elastic/eui'; import UseUnmount from 'react-use/lib/useUnmount'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import type { OverlayRef } from '@kbn/core/public'; -import type { TopNavMenuProps } from '@kbn/navigation-plugin/public'; -import type { BaseVisType, VisTypeAlias } from '@kbn/visualizations-plugin/public'; import { - AddFromLibraryButton, + withSuspense, LazyLabsFlyout, - PrimaryActionButton, + SolutionToolbar, QuickButtonGroup, QuickButtonProps, - SolutionToolbar, - withSuspense, + PrimaryActionButton, + AddFromLibraryButton, } from '@kbn/presentation-util-plugin/public'; -import type { SavedQuery } from '@kbn/data-plugin/common'; -import { isErrorEmbeddable, openAddPanelFlyout, ViewMode } from '@kbn/embeddable-plugin/public'; import { - getSavedObjectFinder, - type SaveResult, showSaveModal, + type SaveResult, + getSavedObjectFinder, } from '@kbn/saved-objects-plugin/public'; +import { METRIC_TYPE } from '@kbn/analytics'; +import { Required } from '@kbn/utility-types'; +import { EuiHorizontalRule } from '@elastic/eui'; +import type { OverlayRef } from '@kbn/core/public'; +import type { SavedQuery } from '@kbn/data-plugin/common'; +import type { TopNavMenuProps } from '@kbn/navigation-plugin/public'; +import type { BaseVisType, VisTypeAlias } from '@kbn/visualizations-plugin/public'; +import { isErrorEmbeddable, openAddPanelFlyout, ViewMode } from '@kbn/embeddable-plugin/public'; -import { saveDashboard } from '../lib'; -import { TopNavIds } from './top_nav_ids'; -import { EditorMenu } from './editor_menu'; -import { UI_SETTINGS } from '../../../common'; -import { DashboardSaveModal } from './save_modal'; -import { showCloneModal } from './show_clone_modal'; -import { ShowShareModal } from './show_share_modal'; -import { getTopNavConfig } from './get_top_nav_config'; -import { showOptionsPopover } from './show_options_popover'; -import { DashboardConstants } from '../../dashboard_constants'; -import { confirmDiscardUnsavedChanges } from '../listing/confirm_overlays'; -import type { DashboardAppState, DashboardSaveOptions, NavAction } from '../../types'; -import type { DashboardEmbedSettings, DashboardRedirect } from '../../types'; -import { getCreateVisualizationButtonTitle, unsavedChangesBadge } from '../../dashboard_strings'; import { setFullScreenMode, setHidePanelTitles, @@ -58,8 +44,21 @@ import { useDashboardDispatch, useDashboardSelector, } from '../state'; +import { TopNavIds } from './top_nav_ids'; +import { EditorMenu } from './editor_menu'; +import { UI_SETTINGS } from '../../../common'; +import { DashboardSaveModal } from './save_modal'; +import { showCloneModal } from './show_clone_modal'; +import { ShowShareModal } from './show_share_modal'; +import { getTopNavConfig } from './get_top_nav_config'; +import { showOptionsPopover } from './show_options_popover'; import { pluginServices } from '../../services/plugin_services'; +import { DashboardEmbedSettings, DashboardRedirect, DashboardState } from '../../types'; +import { confirmDiscardUnsavedChanges } from '../listing/confirm_overlays'; import { useDashboardMountContext } from '../hooks/dashboard_mount_context'; +import { DashboardConstants, getFullEditPath } from '../../dashboard_constants'; +import { DashboardAppState, DashboardSaveOptions, NavAction } from '../../types'; +import { getCreateVisualizationButtonTitle, unsavedChangesBadge } from '../../dashboard_strings'; export interface DashboardTopNavState { chromeIsVisible: boolean; @@ -70,18 +69,13 @@ export interface DashboardTopNavState { type CompleteDashboardAppState = Required< DashboardAppState, - 'getLatestDashboardState' | 'dashboardContainer' | 'savedDashboard' | 'applyFilters' + 'getLatestDashboardState' | 'dashboardContainer' >; export const isCompleteDashboardAppState = ( state: DashboardAppState ): state is CompleteDashboardAppState => { - return ( - Boolean(state.getLatestDashboardState) && - Boolean(state.dashboardContainer) && - Boolean(state.savedDashboard) && - Boolean(state.applyFilters) - ); + return Boolean(state.getLatestDashboardState) && Boolean(state.dashboardContainer); }; export interface DashboardTopNavProps { @@ -101,24 +95,28 @@ export function DashboardTopNav({ }: DashboardTopNavProps) { const { setHeaderActionMenu } = useDashboardMountContext(); const { + dashboardSavedObject: { + checkForDuplicateDashboardTitle, + saveDashboardStateToSavedObject, + savedObjectsClient, + }, chrome: { getIsVisible$: getChromeIsVisible$, recentlyAccessed: chromeRecentlyAccessed, docTitle, }, coreContext: { i18nContext }, - dashboardCapabilities, + share, + overlays, + notifications, + usageCollection, data: { query, search }, - embeddable: { getEmbeddableFactory, getEmbeddableFactories, getStateTransfer }, - initializerContext: { allowByValueEmbeddables }, navigation: { TopNavMenu }, - notifications, - overlays, - savedObjects, - savedObjectsTagging: { hasTagDecoration, hasApi }, settings: { uiSettings, theme }, - share, - usageCollection, + initializerContext: { allowByValueEmbeddables }, + dashboardCapabilities: { showWriteControls, saveQuery: showSaveQuery }, + savedObjectsTagging: { hasApi: hasSavedObjectsTagging }, + embeddable: { getEmbeddableFactory, getEmbeddableFactories, getStateTransfer }, visualizations: { get: getVisualization, getAliases: getVisTypeAliases }, } = pluginServices.getServices(); @@ -144,24 +142,18 @@ export function DashboardTopNav({ const visibleSubscription = getChromeIsVisible$().subscribe((chromeIsVisible) => { setState((s) => ({ ...s, chromeIsVisible })); }); - const { id, title, getFullEditPath } = dashboardAppState.savedDashboard; - if (id && title) { + const { savedObjectId, title, viewMode } = dashboardState; + if (savedObjectId && title) { chromeRecentlyAccessed.add( - getFullEditPath(dashboardState.viewMode === ViewMode.EDIT), + getFullEditPath(savedObjectId, viewMode === ViewMode.EDIT), title, - id + savedObjectId ); } return () => { visibleSubscription.unsubscribe(); }; - }, [ - getChromeIsVisible$, - chromeRecentlyAccessed, - allowByValueEmbeddables, - dashboardState.viewMode, - dashboardAppState.savedDashboard, - ]); + }, [allowByValueEmbeddables, chromeRecentlyAccessed, dashboardState, getChromeIsVisible$]); const addFromLibrary = useCallback(() => { if (!isErrorEmbeddable(dashboardAppState.dashboardContainer)) { @@ -173,7 +165,7 @@ export function DashboardTopNav({ getFactory: getEmbeddableFactory, notifications, overlays, - SavedObjectFinder: getSavedObjectFinder(savedObjects, uiSettings), + SavedObjectFinder: getSavedObjectFinder({ client: savedObjectsClient }, uiSettings), reportUiCounter: usageCollection.reportUiCounter, theme, }), @@ -181,14 +173,14 @@ export function DashboardTopNav({ } }, [ dashboardAppState.dashboardContainer, + usageCollection.reportUiCounter, getEmbeddableFactories, getEmbeddableFactory, + savedObjectsClient, notifications, - savedObjects, overlays, - theme, uiSettings, - usageCollection, + theme, ]); const createNewVisType = useCallback( @@ -258,48 +250,71 @@ export function DashboardTopNav({ onTitleDuplicate, isTitleDuplicateConfirmed, }: DashboardSaveOptions): Promise => { + const { + timefilter: { timefilter }, + } = query; + const saveOptions = { confirmOverwrite: false, isTitleDuplicateConfirmed, onTitleDuplicate, + saveAsCopy: newCopyOnSave, }; - const stateFromSaveModal = { + const stateFromSaveModal: Pick< + DashboardState, + 'title' | 'description' | 'timeRestore' | 'timeRange' | 'refreshInterval' | 'tags' + > = { title: newTitle, + tags: [] as string[], description: newDescription, timeRestore: newTimeRestore, - tags: [] as string[], + timeRange: newTimeRestore ? timefilter.getTime() : undefined, + refreshInterval: newTimeRestore ? timefilter.getRefreshInterval() : undefined, }; - if (hasApi && newTags) { - // remove `hasAPI` once the savedObjectsTagging service is optional + if (hasSavedObjectsTagging && newTags) { + // remove `hasSavedObjectsTagging` once the savedObjectsTagging service is optional stateFromSaveModal.tags = newTags; } - dashboardAppState.savedDashboard.copyOnSave = newCopyOnSave; - const saveResult = await saveDashboard({ + if ( + !(await checkForDuplicateDashboardTitle({ + title: newTitle, + onTitleDuplicate, + lastSavedTitle: currentState.title, + copyOnSave: newCopyOnSave, + isTitleDuplicateConfirmed, + })) + ) { + // do not save if title is duplicate and is unconfirmed + return {}; + } + + const saveResult = await saveDashboardStateToSavedObject({ redirectTo, saveOptions, - savedDashboard: dashboardAppState.savedDashboard, currentState: { ...currentState, ...stateFromSaveModal }, }); if (saveResult.id && !saveResult.redirected) { dispatchDashboardStateChange(setStateFromSaveModal(stateFromSaveModal)); - dashboardAppState.updateLastSavedState?.(); - docTitle.change(stateFromSaveModal.title); + setTimeout(() => { + /** + * set timeout so dashboard state subject can update with the new title before updating the last saved state. + * TODO: Remove this timeout once the last saved state is also handled in Redux. + **/ + dashboardAppState.updateLastSavedState?.(); + docTitle.change(stateFromSaveModal.title); + }, 1); } - return saveResult.id ? { id: saveResult.id } : { error: saveResult.error }; + return saveResult.id ? { id: saveResult.id } : { error: new Error(saveResult.error) }; }; - const lastDashboardId = dashboardAppState.savedDashboard.id; - const savedTags = hasTagDecoration?.(dashboardAppState.savedDashboard) - ? dashboardAppState.savedDashboard.getTags() - : []; - const currentTagsSet = new Set([...savedTags, ...currentState.tags]); + const lastDashboardId = currentState.savedObjectId; const dashboardSaveModal = ( {}} - tags={Array.from(currentTagsSet)} + tags={currentState.tags} title={currentState.title} timeRestore={currentState.timeRestore} description={currentState.description} @@ -309,24 +324,25 @@ export function DashboardTopNav({ closeAllFlyouts(); showSaveModal(dashboardSaveModal, i18nContext); }, [ + saveDashboardStateToSavedObject, + checkForDuplicateDashboardTitle, dispatchDashboardStateChange, - hasApi, - hasTagDecoration, + hasSavedObjectsTagging, dashboardAppState, - i18nContext, - docTitle, closeAllFlyouts, + i18nContext, redirectTo, + docTitle, + query, ]); const runQuickSave = useCallback(async () => { setState((s) => ({ ...s, isSaveInProgress: true })); const currentState = dashboardAppState.getLatestDashboardState(); - const saveResult = await saveDashboard({ + const saveResult = await saveDashboardStateToSavedObject({ redirectTo, currentState, saveOptions: {}, - savedDashboard: dashboardAppState.savedDashboard, }); if (saveResult.id && !saveResult.redirected) { dashboardAppState.updateLastSavedState?.(); @@ -336,7 +352,7 @@ export function DashboardTopNav({ if (!mounted) return; setState((s) => ({ ...s, isSaveInProgress: false })); }, DashboardConstants.CHANGE_CHECK_DEBOUNCE); - }, [dashboardAppState, redirectTo, mounted]); + }, [dashboardAppState, saveDashboardStateToSavedObject, redirectTo, mounted]); const runClone = useCallback(() => { const currentState = dashboardAppState.getLatestDashboardState(); @@ -345,22 +361,33 @@ export function DashboardTopNav({ isTitleDuplicateConfirmed: boolean, onTitleDuplicate: () => void ) => { - dashboardAppState.savedDashboard.copyOnSave = true; - const saveOptions = { - confirmOverwrite: false, - isTitleDuplicateConfirmed, - onTitleDuplicate, - }; - const saveResult = await saveDashboard({ + if ( + !(await checkForDuplicateDashboardTitle({ + title: newTitle, + onTitleDuplicate, + lastSavedTitle: currentState.title, + copyOnSave: true, + isTitleDuplicateConfirmed, + })) + ) { + // do not clone if title is duplicate and is unconfirmed + return {}; + } + + const saveResult = await saveDashboardStateToSavedObject({ redirectTo, - saveOptions, - savedDashboard: dashboardAppState.savedDashboard, + saveOptions: { saveAsCopy: true }, currentState: { ...currentState, title: newTitle }, }); return saveResult.id ? { id: saveResult.id } : { error: saveResult.error }; }; showCloneModal({ onClone, title: currentState.title }); - }, [dashboardAppState, redirectTo]); + }, [ + checkForDuplicateDashboardTitle, + saveDashboardStateToSavedObject, + dashboardAppState, + redirectTo, + ]); const showOptions = useCallback( (anchorElement: HTMLElement) => { @@ -394,7 +421,6 @@ export function DashboardTopNav({ ShowShareModal({ anchorElement, currentDashboardState: currentState, - savedDashboard: dashboardAppState.savedDashboard, isDirty: Boolean(dashboardAppState.hasUnsavedChanges), }); }, @@ -442,7 +468,7 @@ export function DashboardTopNav({ }); const getNavBarProps = (): TopNavMenuProps => { - const { hasUnsavedChanges, savedDashboard } = dashboardAppState; + const { hasUnsavedChanges } = dashboardAppState; const shouldShowNavBarComponent = (forceShow: boolean): boolean => (forceShow || state.chromeIsVisible) && !dashboardState.fullScreenMode; @@ -464,11 +490,11 @@ export function DashboardTopNav({ dashboardAppState.getLatestDashboardState().viewMode, dashboardTopNavActions, { - showWriteControls: dashboardCapabilities.showWriteControls, - isDirty: Boolean(dashboardAppState.hasUnsavedChanges), - isSaveInProgress: state.isSaveInProgress, - isNewDashboard: !savedDashboard.id, isLabsEnabled, + showWriteControls, + isSaveInProgress: state.isSaveInProgress, + isNewDashboard: !dashboardState.savedObjectId, + isDirty: Boolean(dashboardAppState.hasUnsavedChanges), } ); @@ -485,22 +511,22 @@ export function DashboardTopNav({ return { badges, - appName: 'dashboard', - config: showTopNavMenu ? topNav : undefined, - className: isFullScreenMode ? 'kbnTopNavMenu-isFullScreen' : undefined, screenTitle, - showSearchBar, showQueryBar, + showSearchBar, + showFilterBar, + showSaveQuery, showQueryInput, showDatePicker, - showFilterBar, - setMenuMountPoint: embedSettings ? undefined : setHeaderActionMenu, - indexPatterns: dashboardAppState.dataViews, - showSaveQuery: dashboardCapabilities.saveQuery, + appName: 'dashboard', useDefaultBehaviors: true, + visible: printMode !== true, savedQuery: state.savedQuery, savedQueryId: dashboardState.savedQuery, - visible: printMode !== true, + indexPatterns: dashboardAppState.dataViews, + config: showTopNavMenu ? topNav : undefined, + setMenuMountPoint: embedSettings ? undefined : setHeaderActionMenu, + className: isFullScreenMode ? 'kbnTopNavMenu-isFullScreen' : undefined, onQuerySubmit: (_payload, isUpdate) => { if (isUpdate === false) { dashboardAppState.$triggerDashboardRefresh.next({ force: true }); diff --git a/src/plugins/dashboard/public/application/top_nav/show_share_modal.test.tsx b/src/plugins/dashboard/public/application/top_nav/show_share_modal.test.tsx index ad9d85926a94b..7e76ef1789a38 100644 --- a/src/plugins/dashboard/public/application/top_nav/show_share_modal.test.tsx +++ b/src/plugins/dashboard/public/application/top_nav/show_share_modal.test.tsx @@ -10,10 +10,9 @@ import { Capabilities } from '@kbn/core/public'; import { DashboardState } from '../../types'; import { DashboardAppLocatorParams } from '../..'; +import { pluginServices } from '../../services/plugin_services'; import { stateToRawDashboardState } from '../lib/convert_dashboard_state'; -import { getSavedDashboardMock } from '../test_helpers'; import { showPublicUrlSwitch, ShowShareModal, ShowShareModalProps } from './show_share_modal'; -import { pluginServices } from '../../services/plugin_services'; describe('showPublicUrlSwitch', () => { test('returns false if "dashboard" app is not available', () => { @@ -75,9 +74,8 @@ describe('ShowShareModal', () => { .mockReturnValue(unsavedState); return { isDirty: true, - savedDashboard: getSavedDashboardMock(), anchorElement: document.createElement('div'), - currentDashboardState: { panels: {} } as unknown as DashboardState, + currentDashboardState: { panels: {} } as DashboardState, }; }; @@ -139,7 +137,7 @@ describe('ShowShareModal', () => { }); unsavedStateKeys.forEach((key) => { expect(shareLocatorParams[key]).toStrictEqual( - (rawDashboardState as Partial)[key] + (rawDashboardState as unknown as Partial)[key] ); }); }); diff --git a/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx b/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx index f93061f56d6ec..0f7d119427dd7 100644 --- a/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx +++ b/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx @@ -9,28 +9,26 @@ import moment from 'moment'; import React, { ReactElement, useState } from 'react'; -import { EuiCheckboxGroup } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { EuiCheckboxGroup } from '@elastic/eui'; import type { Capabilities } from '@kbn/core/public'; -import type { SerializableControlGroupInput } from '@kbn/controls-plugin/common'; import { ViewMode } from '@kbn/embeddable-plugin/public'; import { setStateToKbnUrl, unhashUrl } from '@kbn/kibana-utils-plugin/public'; +import type { SerializableControlGroupInput } from '@kbn/controls-plugin/common'; -import type { DashboardSavedObject } from '../..'; -import { shareModalStrings } from '../../dashboard_strings'; -import { DashboardAppLocatorParams, DASHBOARD_APP_LOCATOR } from '../../locator'; import type { DashboardState } from '../../types'; import { dashboardUrlParams } from '../dashboard_router'; -import { stateToRawDashboardState } from '../lib/convert_dashboard_state'; -import { convertPanelMapToSavedPanels } from '../lib/convert_dashboard_panels'; +import { shareModalStrings } from '../../dashboard_strings'; +import { convertPanelMapToSavedPanels } from '../../../common'; import { pluginServices } from '../../services/plugin_services'; +import { stateToRawDashboardState } from '../lib/convert_dashboard_state'; +import { DashboardAppLocatorParams, DASHBOARD_APP_LOCATOR } from '../../locator'; const showFilterBarId = 'showFilterBar'; export interface ShowShareModalProps { isDirty: boolean; anchorElement: HTMLElement; - savedDashboard: DashboardSavedObject; currentDashboardState: DashboardState; } @@ -45,7 +43,6 @@ export const showPublicUrlSwitch = (anonymousUserCapabilities: Capabilities) => export function ShowShareModal({ isDirty, anchorElement, - savedDashboard, currentDashboardState, }: ShowShareModalProps) { const { @@ -59,6 +56,7 @@ export function ShowShareModal({ }, }, share: { toggleShareContextMenu }, + initializerContext: { kibanaVersion }, } = pluginServices.getServices(); if (!toggleShareContextMenu) return; // TODO: Make this logic cleaner once share is an optional service @@ -124,7 +122,9 @@ export function ShowShareModal({ DashboardAppLocatorParams, 'options' | 'query' | 'savedQuery' | 'filters' | 'panels' | 'controlGroupInput' > = {}; - const unsavedDashboardState = dashboardSessionStorage.getState(savedDashboard.id); + const { savedObjectId, title } = currentDashboardState; + const unsavedDashboardState = dashboardSessionStorage.getState(savedObjectId); + if (unsavedDashboardState) { unsavedStateForLocator = { query: unsavedDashboardState.query, @@ -133,13 +133,16 @@ export function ShowShareModal({ savedQuery: unsavedDashboardState.savedQuery, controlGroupInput: unsavedDashboardState.controlGroupInput as SerializableControlGroupInput, panels: unsavedDashboardState.panels - ? convertPanelMapToSavedPanels(unsavedDashboardState.panels) + ? (convertPanelMapToSavedPanels( + unsavedDashboardState.panels, + kibanaVersion + ) as DashboardAppLocatorParams['panels']) : undefined, }; } const locatorParams: DashboardAppLocatorParams = { - dashboardId: savedDashboard.id, + dashboardId: savedObjectId, preserveSavedFilters: true, refreshInterval: undefined, // We don't share refresh interval externally viewMode: ViewMode.VIEW, // For share locators we always load the dashboard in view mode @@ -161,11 +164,11 @@ export function ShowShareModal({ { useHash: false, storeInHashQuery: true }, unhashUrl(window.location.href) ), - objectId: savedDashboard.id, + objectId: savedObjectId, objectType: 'dashboard', sharingData: { title: - savedDashboard.title || + title || i18n.translate('dashboard.share.defaultDashboardTitle', { defaultMessage: 'Dashboard [{date}]', values: { date: moment().toISOString(true) }, diff --git a/src/plugins/dashboard/public/dashboard_constants.ts b/src/plugins/dashboard/public/dashboard_constants.ts index badc14ddaee66..9bbe97681032d 100644 --- a/src/plugins/dashboard/public/dashboard_constants.ts +++ b/src/plugins/dashboard/public/dashboard_constants.ts @@ -6,9 +6,18 @@ * Side Public License, v 1. */ +import { ViewMode } from '@kbn/embeddable-plugin/common'; +import type { DashboardState } from './types'; + export const DASHBOARD_STATE_STORAGE_KEY = '_a'; export const GLOBAL_STATE_STORAGE_KEY = '_g'; +export const DASHBOARD_GRID_COLUMN_COUNT = 48; +export const DASHBOARD_GRID_HEIGHT = 20; +export const DEFAULT_PANEL_WIDTH = DASHBOARD_GRID_COLUMN_COUNT / 2; +export const DEFAULT_PANEL_HEIGHT = 15; +export const DASHBOARD_CONTAINER_TYPE = 'dashboard'; + export const DashboardConstants = { LANDING_PAGE_PATH: '/list', CREATE_NEW_DASHBOARD_URL: '/create', @@ -18,11 +27,37 @@ export const DashboardConstants = { ADD_EMBEDDABLE_TYPE: 'addEmbeddableType', DASHBOARDS_ID: 'dashboards', DASHBOARD_ID: 'dashboard', + DASHBOARD_SAVED_OBJECT_TYPE: 'dashboard', SEARCH_SESSION_ID: 'searchSessionId', CHANGE_CHECK_DEBOUNCE: 100, CHANGE_APPLY_DEBOUNCE: 50, }; +export const defaultDashboardState: DashboardState = { + viewMode: ViewMode.EDIT, // new dashboards start in edit mode. + fullScreenMode: false, + timeRestore: false, + query: { query: '', language: 'kuery' }, + description: '', + filters: [], + panels: {}, + title: '', + tags: [], + options: { + useMargins: true, + syncColors: false, + syncTooltips: false, + hidePanelTitles: false, + }, +}; + +export const getFullPath = (aliasId?: string, id?: string) => + `/app/dashboards#${createDashboardEditUrl(aliasId || id)}`; + +export const getFullEditPath = (id?: string, editMode?: boolean) => { + return `/app/dashboards#${createDashboardEditUrl(id, editMode)}`; +}; + export function createDashboardEditUrl(id?: string, editMode?: boolean) { if (!id) { return `${DashboardConstants.CREATE_NEW_DASHBOARD_URL}`; diff --git a/src/plugins/dashboard/public/dashboard_strings.ts b/src/plugins/dashboard/public/dashboard_strings.ts index 5679ac28f838b..6474c7dc2bba6 100644 --- a/src/plugins/dashboard/public/dashboard_strings.ts +++ b/src/plugins/dashboard/public/dashboard_strings.ts @@ -382,7 +382,7 @@ export const panelStorageErrorStrings = { }), }; -export const dashboardLoadingErrorStrings = { +export const dashboardSavedObjectErrorStrings = { getDashboardLoadError: (message: string) => i18n.translate('dashboard.loadingError.errorMessage', { defaultMessage: 'Error encountered while loading saved dashboard: {message}', @@ -393,6 +393,14 @@ export const dashboardLoadingErrorStrings = { defaultMessage: 'Unable to load dashboard: {message}', values: { message }, }), + getErrorDeletingDashboardToast: () => + i18n.translate('dashboard.deleteError.toastDescription', { + defaultMessage: 'Error encountered while deleting dashboard', + }), + getPanelTooOldError: () => + i18n.translate('dashboard.loadURLError.PanelTooOld', { + defaultMessage: 'Cannot load panels from a URL created in a version older than 7.3', + }), }; /* @@ -432,7 +440,7 @@ export const emptyScreenStrings = { /* Dashboard Listing Page */ -export const dashboardListingTable = { +export const dashboardListingTableStrings = { getEntityName: () => i18n.translate('dashboard.listing.table.entityName', { defaultMessage: 'dashboard', @@ -450,8 +458,8 @@ export const dashboardUnsavedListingStrings = { defaultMessage: 'You have unsaved changes in the following {dash}:', values: { dash: plural - ? dashboardListingTable.getEntityNamePlural() - : dashboardListingTable.getEntityName(), + ? dashboardListingTableStrings.getEntityNamePlural() + : dashboardListingTableStrings.getEntityName(), }, }), getLoadingTitle: () => diff --git a/src/plugins/dashboard/public/index.ts b/src/plugins/dashboard/public/index.ts index 7cb54db209c1d..598940bbd666c 100644 --- a/src/plugins/dashboard/public/index.ts +++ b/src/plugins/dashboard/public/index.ts @@ -9,11 +9,7 @@ import { PluginInitializerContext } from '@kbn/core/public'; import { DashboardPlugin } from './plugin'; -export { - DashboardContainer, - DashboardContainerFactoryDefinition, - DASHBOARD_CONTAINER_TYPE, -} from './application'; +export { DASHBOARD_CONTAINER_TYPE } from './dashboard_constants'; export { DashboardConstants, createDashboardEditUrl } from './dashboard_constants'; export type { DashboardSetup, DashboardStart, DashboardFeatureFlagConfig } from './plugin'; @@ -23,7 +19,6 @@ export { cleanEmptyKeys, } from './locator'; -export type { DashboardSavedObject } from './saved_dashboards'; export type { SavedDashboardPanel, DashboardContainerInput } from './types'; export function plugin(initializerContext: PluginInitializerContext) { diff --git a/src/plugins/dashboard/public/locator.ts b/src/plugins/dashboard/public/locator.ts index e3cd3f159f738..a66015afcb00b 100644 --- a/src/plugins/dashboard/public/locator.ts +++ b/src/plugins/dashboard/public/locator.ts @@ -94,7 +94,7 @@ export type DashboardAppLocatorParams = { /** * List of dashboard panels */ - panels?: SavedDashboardPanel[]; + panels?: Array; // used SerializableRecord here to force the GridData type to be read as serializable /** * Saved query ID diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index 9d1df9d2acb12..a0d35e2c7be48 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -9,73 +9,56 @@ import { BehaviorSubject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; -import { Start as InspectorStartContract } from '@kbn/inspector-plugin/public'; -import type { UrlForwardingSetup, UrlForwardingStart } from '@kbn/url-forwarding-plugin/public'; -import { APP_WRAPPER_CLASS } from '@kbn/core/public'; import { App, Plugin, - type CoreSetup, - type CoreStart, AppUpdater, ScopedHistory, + type CoreSetup, + type CoreStart, AppMountParameters, DEFAULT_APP_CATEGORIES, PluginInitializerContext, SavedObjectsClientContract, } from '@kbn/core/public'; -import { - CONTEXT_MENU_TRIGGER, - EmbeddableSetup, - EmbeddableStart, - PANEL_BADGE_TRIGGER, - PANEL_NOTIFICATION_TRIGGER, -} from '@kbn/embeddable-plugin/public'; import type { ScreenshotModePluginSetup, ScreenshotModePluginStart, } from '@kbn/screenshot-mode-plugin/public'; -import type { SpacesPluginStart } from '@kbn/spaces-plugin/public'; -import type { HomePublicPluginSetup } from '@kbn/home-plugin/public'; -import { replaceUrlHashQuery } from '@kbn/kibana-utils-plugin/public'; -import { createKbnUrlTracker } from '@kbn/kibana-utils-plugin/public'; -import type { VisualizationsStart } from '@kbn/visualizations-plugin/public'; -import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; import type { UsageCollectionSetup, UsageCollectionStart, } from '@kbn/usage-collection-plugin/public'; +import { APP_WRAPPER_CLASS } from '@kbn/core/public'; +import { replaceUrlHashQuery } from '@kbn/kibana-utils-plugin/public'; +import { createKbnUrlTracker } from '@kbn/kibana-utils-plugin/public'; + +import type { SpacesPluginStart } from '@kbn/spaces-plugin/public'; +import type { HomePublicPluginSetup } from '@kbn/home-plugin/public'; +import type { SavedObjectsStart } from '@kbn/saved-objects-plugin/public'; +import type { VisualizationsStart } from '@kbn/visualizations-plugin/public'; +import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; import type { NavigationPublicPluginStart } from '@kbn/navigation-plugin/public'; import type { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public'; +import type { Start as InspectorStartContract } from '@kbn/inspector-plugin/public'; import type { UiActionsSetup, UiActionsStart } from '@kbn/ui-actions-plugin/public'; +import type { EmbeddableSetup, EmbeddableStart } from '@kbn/embeddable-plugin/public'; import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public'; +import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; import type { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public'; +import type { UrlForwardingSetup, UrlForwardingStart } from '@kbn/url-forwarding-plugin/public'; import type { SavedObjectTaggingOssPluginStart } from '@kbn/saved-objects-tagging-oss-plugin/public'; -import { getSavedObjectFinder, type SavedObjectsStart } from '@kbn/saved-objects-plugin/public'; -import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; import { - ClonePanelAction, - createDashboardContainerByValueRenderer, - DASHBOARD_CONTAINER_TYPE, - DashboardContainerFactory, + type DashboardContainerFactory, DashboardContainerFactoryDefinition, - ExpandPanelAction, - ReplacePanelAction, - UnlinkFromLibraryAction, - AddToLibraryAction, - LibraryNotificationAction, - CopyToDashboardAction, -} from './application'; -import { SavedObjectLoader } from './services/saved_object_loader'; -import { DashboardAppLocatorDefinition, DashboardAppLocator } from './locator'; -import { createSavedDashboardLoader } from './saved_dashboards'; -import { DashboardConstants } from './dashboard_constants'; -import { PlaceholderEmbeddableFactory } from './application/embeddable/placeholder'; -import { ExportCSVAction } from './application/actions/export_csv_action'; -import { dashboardFeatureCatalog } from './dashboard_strings'; -import { FiltersNotificationBadge } from './application/actions/filters_notification_badge'; + createDashboardContainerByValueRenderer, +} from './application/embeddable'; import type { DashboardMountContextProps } from './types'; +import { dashboardFeatureCatalog } from './dashboard_strings'; +import { type DashboardAppLocator, DashboardAppLocatorDefinition } from './locator'; +import { PlaceholderEmbeddableFactory } from './application/embeddable/placeholder'; +import { DashboardConstants, DASHBOARD_CONTAINER_TYPE } from './dashboard_constants'; export interface DashboardFeatureFlagConfig { allowByValueEmbeddables: boolean; @@ -118,7 +101,6 @@ export interface DashboardSetup { } export interface DashboardStart { - getSavedDashboardLoader: () => SavedObjectLoader; getDashboardContainerByValueRenderer: () => ReturnType< typeof createDashboardContainerByValueRenderer >; @@ -159,9 +141,14 @@ export class DashboardPlugin new DashboardAppLocatorDefinition({ useHashedUrl: core.uiSettings.get('state:storeInSessionStorage'), getDashboardFilterFields: async (dashboardId: string) => { - const [, , selfStart] = await core.getStartServices(); - const dashboard = await selfStart.getSavedDashboardLoader().get(dashboardId); - return dashboard?.searchSource?.getField('filter') ?? []; + const { pluginServices } = await import('./services/plugin_services'); + const { + dashboardSavedObject: { loadDashboardStateFromSavedObject }, + } = pluginServices.getServices(); + return ( + (await loadDashboardStateFromSavedObject({ id: dashboardId })).dashboardState + ?.filters ?? [] + ); }, }) ); @@ -305,58 +292,16 @@ export class DashboardPlugin } public start(core: CoreStart, plugins: DashboardStartDependencies): DashboardStart { - const { uiSettings } = core; - const { uiActions, share, presentationUtil } = plugins; - this.startDashboardKibanaServices(core, plugins, this.initializerContext).then(() => { - const clonePanelAction = new ClonePanelAction(core.savedObjects); - uiActions.registerAction(clonePanelAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, clonePanelAction.id); - - const SavedObjectFinder = getSavedObjectFinder(core.savedObjects, uiSettings); - const changeViewAction = new ReplacePanelAction(SavedObjectFinder); - uiActions.registerAction(changeViewAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, changeViewAction.id); - - const panelLevelFiltersNotification = new FiltersNotificationBadge(); - uiActions.registerAction(panelLevelFiltersNotification); - uiActions.attachAction(PANEL_BADGE_TRIGGER, panelLevelFiltersNotification.id); - - if (share) { - const ExportCSVPlugin = new ExportCSVAction(); - uiActions.addTriggerAction(CONTEXT_MENU_TRIGGER, ExportCSVPlugin); - } - - if (this.dashboardFeatureFlagConfig?.allowByValueEmbeddables) { - const addToLibraryAction = new AddToLibraryAction(); - uiActions.registerAction(addToLibraryAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, addToLibraryAction.id); - - const unlinkFromLibraryAction = new UnlinkFromLibraryAction(); - uiActions.registerAction(unlinkFromLibraryAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, unlinkFromLibraryAction.id); - - const libraryNotificationAction = new LibraryNotificationAction(unlinkFromLibraryAction); - uiActions.registerAction(libraryNotificationAction); - uiActions.attachAction(PANEL_NOTIFICATION_TRIGGER, libraryNotificationAction.id); - - const copyToDashboardAction = new CopyToDashboardAction(presentationUtil.ContextProvider); - uiActions.registerAction(copyToDashboardAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, copyToDashboardAction.id); - } - }); - - const expandPanelAction = new ExpandPanelAction(); // this action does't rely on any services - uiActions.registerAction(expandPanelAction); - uiActions.attachAction(CONTEXT_MENU_TRIGGER, expandPanelAction.id); - - const savedDashboardLoader = createSavedDashboardLoader({ - savedObjectsClient: core.savedObjects.client, - savedObjects: plugins.savedObjects, - embeddableStart: plugins.embeddable, + this.startDashboardKibanaServices(core, plugins, this.initializerContext).then(async () => { + const { buildAllDashboardActions } = await import('./application/actions'); + buildAllDashboardActions({ + core, + plugins, + allowByValueEmbeddables: this.dashboardFeatureFlagConfig?.allowByValueEmbeddables, + }); }); return { - getSavedDashboardLoader: () => savedDashboardLoader, getDashboardContainerByValueRenderer: () => { const dashboardContainerFactory = plugins.embeddable.getEmbeddableFactory(DASHBOARD_CONTAINER_TYPE); diff --git a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts deleted file mode 100644 index c23b6eb2a87e0..0000000000000 --- a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { assign, cloneDeep } from 'lodash'; -import { SavedObjectsClientContract } from '@kbn/core/public'; -import type { ResolvedSimpleSavedObject } from '@kbn/core/public'; -import { SavedObjectAttributes, SavedObjectReference } from '@kbn/core/types'; -import { RawControlGroupAttributes } from '@kbn/controls-plugin/common'; -import { EmbeddableStart } from '@kbn/embeddable-plugin/public'; -import { ISearchSource } from '@kbn/data-plugin/common'; -import { RefreshInterval } from '@kbn/data-plugin/public'; -import { Query, Filter } from '@kbn/es-query'; -import type { SavedObject, SavedObjectsStart } from '@kbn/saved-objects-plugin/public'; - -import { createDashboardEditUrl } from '../dashboard_constants'; -import { extractReferences, injectReferences } from '../../common/saved_dashboard_references'; - -import { DashboardOptions } from '../types'; - -export interface DashboardSavedObject extends SavedObject { - id?: string; - timeRestore: boolean; - timeTo?: string; - timeFrom?: string; - description?: string; - panelsJSON: string; - optionsJSON?: string; - // TODO: write a migration to rid of this, it's only around for bwc. - uiStateJSON?: string; - lastSavedTitle: string; - refreshInterval?: RefreshInterval; - searchSource: ISearchSource; - getQuery(): Query; - getFilters(): Filter[]; - getFullEditPath: (editMode?: boolean) => string; - outcome?: ResolvedSimpleSavedObject['outcome']; - aliasId?: ResolvedSimpleSavedObject['alias_target_id']; - aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; - - controlGroupInput?: Omit; -} - -const defaults = { - title: '', - hits: 0, - description: '', - panelsJSON: '[]', - optionsJSON: JSON.stringify({ - // for BWC reasons we can't default dashboards that already exist without this setting to true. - useMargins: true, - syncColors: false, - syncTooltips: false, - hidePanelTitles: false, - } as DashboardOptions), - version: 1, - timeRestore: false, - timeTo: undefined, - timeFrom: undefined, - refreshInterval: undefined, -}; - -// Used only by the savedDashboards service, usually no reason to change this -export function createSavedDashboardClass( - savedObjectStart: SavedObjectsStart, - embeddableStart: EmbeddableStart, - savedObjectsClient: SavedObjectsClientContract -): new (id: string) => DashboardSavedObject { - class SavedDashboard extends savedObjectStart.SavedObjectClass { - // save these objects with the 'dashboard' type - public static type = 'dashboard'; - - // if type:dashboard has no mapping, we push this mapping into ES - public static mapping = { - title: 'text', - hits: 'integer', - description: 'text', - panelsJSON: 'text', - optionsJSON: 'text', - version: 'integer', - timeRestore: 'boolean', - timeTo: 'keyword', - timeFrom: 'keyword', - refreshInterval: { - type: 'object', - properties: { - display: { type: 'keyword' }, - pause: { type: 'boolean' }, - section: { type: 'integer' }, - value: { type: 'integer' }, - }, - }, - controlGroupInput: { - type: 'object', - properties: { - controlStyle: { type: 'keyword' }, - panelsJSON: { type: 'text' }, - }, - }, - }; - public static fieldOrder = ['title', 'description']; - public static searchSource = true; - public showInRecentlyAccessed = true; - - public outcome?: ResolvedSimpleSavedObject['outcome']; - public aliasId?: ResolvedSimpleSavedObject['alias_target_id']; - public aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; - - constructor(arg: { id: string; useResolve: boolean } | string) { - super({ - type: SavedDashboard.type, - mapping: SavedDashboard.mapping, - searchSource: SavedDashboard.searchSource, - extractReferences: (opts: { - attributes: SavedObjectAttributes; - references: SavedObjectReference[]; - }) => extractReferences(opts, { embeddablePersistableStateService: embeddableStart }), - injectReferences: (so: DashboardSavedObject, references: SavedObjectReference[]) => { - const newAttributes = injectReferences( - { attributes: so._serialize().attributes, references }, - { - embeddablePersistableStateService: embeddableStart, - } - ); - Object.assign(so, newAttributes); - }, - - // if this is null/undefined then the SavedObject will be assigned the defaults - id: typeof arg === 'object' ? arg.id : arg, - - // default values that will get assigned if the doc is new - defaults, - }); - - const id: string = typeof arg === 'object' ? arg.id : arg; - const useResolve = typeof arg === 'object' ? arg.useResolve : false; - - this.getFullPath = () => `/app/dashboards#${createDashboardEditUrl(this.aliasId || this.id)}`; - - // Overwrite init if we want to use resolve - if (useResolve || true) { - this.init = async () => { - const esType = SavedDashboard.type; - // ensure that the esType is defined - if (!esType) throw new Error('You must define a type name to use SavedObject objects.'); - - if (!id) { - // just assign the defaults and be done - assign(this, defaults); - await this.hydrateIndexPattern!(); - - return this; - } - - const { - outcome, - alias_target_id: aliasId, - alias_purpose: aliasPurpose, - saved_object: resp, - } = await savedObjectsClient.resolve(esType, id); - - const respMapped = { - _id: resp.id, - _type: resp.type, - _source: cloneDeep(resp.attributes), - references: resp.references, - found: !!resp._version, - }; - - this.outcome = outcome; - this.aliasId = aliasId; - this.aliasPurpose = aliasPurpose; - await this.applyESResp(respMapped); - - return this; - }; - } - } - - getQuery() { - return this.searchSource!.getOwnField('query') || { query: '', language: 'kuery' }; - } - - getFilters() { - return this.searchSource!.getOwnField('filter') || []; - } - - getFullEditPath = (editMode?: boolean) => { - return `/app/dashboards#${createDashboardEditUrl(this.id, editMode)}`; - }; - } - - // Unfortunately this throws a typescript error without the casting. I think it's due to the - // convoluted way SavedObjects are created. - return SavedDashboard as unknown as new (id: string) => DashboardSavedObject; -} diff --git a/src/plugins/dashboard/public/saved_dashboards/saved_dashboards.ts b/src/plugins/dashboard/public/saved_dashboards/saved_dashboards.ts deleted file mode 100644 index a154fdad96562..0000000000000 --- a/src/plugins/dashboard/public/saved_dashboards/saved_dashboards.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { SavedObjectsClientContract } from '@kbn/core/public'; -import { EmbeddableStart } from '@kbn/embeddable-plugin/public'; -import type { SavedObjectsStart } from '@kbn/saved-objects-plugin/public'; - -import { SavedObjectLoader } from '../services/saved_object_loader'; -import { createSavedDashboardClass } from './saved_dashboard'; - -interface Services { - savedObjectsClient: SavedObjectsClientContract; - savedObjects: SavedObjectsStart; - embeddableStart: EmbeddableStart; -} - -/** - * @param services - */ -export function createSavedDashboardLoader({ - savedObjects, - savedObjectsClient, - embeddableStart, -}: Services) { - const SavedDashboard = createSavedDashboardClass( - savedObjects, - embeddableStart, - savedObjectsClient - ); - return new SavedObjectLoader(SavedDashboard, savedObjectsClient); -} diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object.stub.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object.stub.ts new file mode 100644 index 0000000000000..c23a76746404d --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object.stub.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { savedObjectsServiceMock } from '@kbn/core/public/mocks'; +import { PluginServiceFactory } from '@kbn/presentation-util-plugin/public'; +import { DashboardAttributes } from '../../application'; +import { FindDashboardSavedObjectsResponse } from './lib/find_dashboard_saved_objects'; + +import { DashboardSavedObjectService } from './types'; +import { LoadDashboardFromSavedObjectReturn } from './lib/load_dashboard_state_from_saved_object'; + +type DashboardSavedObjectServiceFactory = PluginServiceFactory; + +export const dashboardSavedObjectServiceFactory: DashboardSavedObjectServiceFactory = () => { + const { client: savedObjectsClient } = savedObjectsServiceMock.createStartContract(); + return { + loadDashboardStateFromSavedObject: jest.fn().mockImplementation(() => + Promise.resolve({ + dashboardState: {}, + } as LoadDashboardFromSavedObjectReturn) + ), + saveDashboardStateToSavedObject: jest.fn(), + findDashboards: { + findSavedObjects: jest.fn().mockImplementation(({ search, size }) => { + const sizeToUse = size ?? 10; + const hits: FindDashboardSavedObjectsResponse['hits'] = []; + for (let i = 0; i < sizeToUse; i++) { + hits.push({ + type: 'dashboard', + id: `dashboard${i}`, + attributes: { + description: `dashboard${i} desc`, + title: `dashboard${i} - ${search} - title`, + }, + } as FindDashboardSavedObjectsResponse['hits'][0]); + } + return Promise.resolve({ + total: sizeToUse, + hits, + }); + }), + findByIds: jest.fn().mockImplementation(() => + Promise.resolve([ + { + id: `dashboardUnsavedOne`, + status: 'success', + attributes: { + title: `Dashboard Unsaved One`, + } as unknown as DashboardAttributes, + }, + { + id: `dashboardUnsavedTwo`, + status: 'success', + attributes: { + title: `Dashboard Unsaved Two`, + } as unknown as DashboardAttributes, + }, + { + id: `dashboardUnsavedThree`, + status: 'success', + attributes: { + title: `Dashboard Unsaved Three`, + } as unknown as DashboardAttributes, + }, + ]) + ), + findByTitle: jest.fn(), + }, + checkForDuplicateDashboardTitle: jest.fn(), + savedObjectsClient, + }; +}; diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object_service.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object_service.ts new file mode 100644 index 0000000000000..7fb558309936e --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/dashboard_saved_object_service.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { KibanaPluginServiceFactory } from '@kbn/presentation-util-plugin/public'; + +import type { DashboardStartDependencies } from '../../plugin'; +import { checkForDuplicateDashboardTitle } from './lib/check_for_duplicate_dashboard_title'; +import { + findDashboardIdByTitle, + findDashboardSavedObjects, + findDashboardSavedObjectsByIds, +} from './lib/find_dashboard_saved_objects'; +import { loadDashboardStateFromSavedObject } from './lib/load_dashboard_state_from_saved_object'; +import { saveDashboardStateToSavedObject } from './lib/save_dashboard_state_to_saved_object'; +import type { DashboardSavedObjectRequiredServices, DashboardSavedObjectService } from './types'; + +export type DashboardSavedObjectServiceFactory = KibanaPluginServiceFactory< + DashboardSavedObjectService, + DashboardStartDependencies, + DashboardSavedObjectRequiredServices +>; + +export const dashboardSavedObjectServiceFactory: DashboardSavedObjectServiceFactory = ( + { coreStart }, + requiredServices +) => { + const { + savedObjects: { client: savedObjectsClient }, + } = coreStart; + + return { + loadDashboardStateFromSavedObject: ({ id, getScopedHistory }) => + loadDashboardStateFromSavedObject({ + id, + getScopedHistory, + savedObjectsClient, + ...requiredServices, + }), + saveDashboardStateToSavedObject: ({ currentState, redirectTo, saveOptions }) => + saveDashboardStateToSavedObject({ + redirectTo, + saveOptions, + currentState, + savedObjectsClient, + ...requiredServices, + }), + findDashboards: { + findSavedObjects: ({ hasReference, search, size }) => + findDashboardSavedObjects({ hasReference, search, size, savedObjectsClient }), + findByIds: (ids) => findDashboardSavedObjectsByIds(savedObjectsClient, ids), + findByTitle: (title) => findDashboardIdByTitle(title, savedObjectsClient), + }, + checkForDuplicateDashboardTitle: (props) => + checkForDuplicateDashboardTitle(props, savedObjectsClient), + savedObjectsClient, + }; +}; diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/lib/check_for_duplicate_dashboard_title.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/check_for_duplicate_dashboard_title.ts new file mode 100644 index 0000000000000..e03345e78c41f --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/check_for_duplicate_dashboard_title.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsClientContract } from '@kbn/core/public'; + +import { DashboardConstants } from '../../..'; +import type { DashboardAttributes } from '../../../application'; + +export interface DashboardDuplicateTitleCheckProps { + title: string; + copyOnSave: boolean; + lastSavedTitle: string; + onTitleDuplicate: () => void; + isTitleDuplicateConfirmed: boolean; +} + +/** + * check for an existing dashboard with the same title in ES + * returns Promise when there is no duplicate, or runs the provided onTitleDuplicate + * function when the title already exists + */ +export async function checkForDuplicateDashboardTitle( + { + title, + copyOnSave, + lastSavedTitle, + onTitleDuplicate, + isTitleDuplicateConfirmed, + }: DashboardDuplicateTitleCheckProps, + savedObjectsClient: SavedObjectsClientContract +): Promise { + // Don't check for duplicates if user has already confirmed save with duplicate title + if (isTitleDuplicateConfirmed) { + return true; + } + + // Don't check if the user isn't updating the title, otherwise that would become very annoying to have + // to confirm the save every time, except when copyOnSave is true, then we do want to check. + if (title === lastSavedTitle && !copyOnSave) { + return true; + } + const response = await savedObjectsClient.find({ + perPage: 10, + fields: ['title'], + search: `"${title}"`, + searchFields: ['title'], + type: DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, + }); + const duplicate = response.savedObjects.find( + (obj) => obj.get('title').toLowerCase() === title.toLowerCase() + ); + if (!duplicate) { + return true; + } + onTitleDuplicate?.(); + return false; +} diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/lib/find_dashboard_saved_objects.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/find_dashboard_saved_objects.ts new file mode 100644 index 0000000000000..c24511f56d3e2 --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/find_dashboard_saved_objects.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { + SavedObjectError, + SavedObjectsClientContract, + SavedObjectsFindOptionsReference, + SimpleSavedObject, +} from '@kbn/core/public'; + +import { DashboardConstants } from '../../..'; +import type { DashboardAttributes } from '../../../application'; + +export interface FindDashboardSavedObjectsArgs { + hasReference?: SavedObjectsFindOptionsReference[]; + savedObjectsClient: SavedObjectsClientContract; + search: string; + size: number; +} + +export interface FindDashboardSavedObjectsResponse { + total: number; + hits: Array>; +} + +export async function findDashboardSavedObjects({ + savedObjectsClient, + hasReference, + search, + size, +}: FindDashboardSavedObjectsArgs): Promise { + const { total, savedObjects } = await savedObjectsClient.find({ + type: DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, + search: search ? `${search}*` : undefined, + searchFields: ['title^3', 'description'], + defaultSearchOperator: 'AND' as 'AND', + perPage: size, + hasReference, + page: 1, + }); + return { + total, + hits: savedObjects, + }; +} + +export type FindDashboardBySavedObjectIdsResult = { id: string } & ( + | { status: 'success'; attributes: DashboardAttributes } + | { status: 'error'; error: SavedObjectError } +); + +export async function findDashboardSavedObjectsByIds( + savedObjectsClient: SavedObjectsClientContract, + ids: string[] +): Promise { + const { savedObjects } = await savedObjectsClient.bulkGet( + ids.map((id) => ({ id, type: DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE })) + ); + + return savedObjects.map((savedObjectResult) => { + if (savedObjectResult.error) + return { status: 'error', error: savedObjectResult.error, id: savedObjectResult.id }; + const { attributes, id } = savedObjectResult; + return { + id, + status: 'success', + attributes: attributes as DashboardAttributes, + }; + }); +} + +export async function findDashboardIdByTitle( + title: string, + savedObjectsClient: SavedObjectsClientContract +): Promise<{ id: string } | undefined> { + const results = await savedObjectsClient.find({ + search: `"${title}"`, + searchFields: ['title'], + type: 'dashboard', + }); + // The search isn't an exact match, lets see if we can find a single exact match to use + const matchingDashboards = results.savedObjects.filter( + (dashboard) => dashboard.attributes.title.toLowerCase() === title.toLowerCase() + ); + if (matchingDashboards.length === 1) { + return { id: matchingDashboards[0].id }; + } +} diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts new file mode 100644 index 0000000000000..963814013dc30 --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/load_dashboard_state_from_saved_object.ts @@ -0,0 +1,201 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { ReactElement } from 'react'; + +import { Filter } from '@kbn/es-query'; +import { ViewMode } from '@kbn/embeddable-plugin/public'; +import { SavedObjectNotFound } from '@kbn/kibana-utils-plugin/public'; +import { rawControlGroupAttributesToControlGroupInput } from '@kbn/controls-plugin/common'; +import { parseSearchSourceJSON, injectSearchSourceReferences } from '@kbn/data-plugin/public'; +import { SavedObjectAttributes, SavedObjectsClientContract, ScopedHistory } from '@kbn/core/public'; + +import { migrateLegacyQuery } from '../../../application/lib/migrate_legacy_query'; + +import { + DashboardConstants, + defaultDashboardState, + createDashboardEditUrl, +} from '../../../dashboard_constants'; +import type { DashboardAttributes } from '../../../application'; +import { DashboardSavedObjectRequiredServices } from '../types'; +import { DashboardOptions, DashboardState } from '../../../types'; +import { cleanFiltersForSerialize } from '../../../application/lib'; +import { convertSavedPanelsToPanelMap, injectReferences } from '../../../../common'; + +export type LoadDashboardFromSavedObjectProps = DashboardSavedObjectRequiredServices & { + id?: string; + getScopedHistory?: () => ScopedHistory; + savedObjectsClient: SavedObjectsClientContract; +}; + +export interface LoadDashboardFromSavedObjectReturn { + redirectedToAlias?: boolean; + dashboardState?: DashboardState; + createConflictWarning?: () => ReactElement | undefined; +} + +type SuccessfulLoadDashboardFromSavedObjectReturn = LoadDashboardFromSavedObjectReturn & { + dashboardState: DashboardState; +}; + +export const dashboardStateLoadWasSuccessful = ( + incoming?: LoadDashboardFromSavedObjectReturn +): incoming is SuccessfulLoadDashboardFromSavedObjectReturn => { + return Boolean(incoming && incoming?.dashboardState && !incoming.redirectedToAlias); +}; + +export const loadDashboardStateFromSavedObject = async ({ + savedObjectsTagging, + savedObjectsClient, + getScopedHistory, + screenshotMode, + embeddable, + spaces, + data, + id, +}: LoadDashboardFromSavedObjectProps): Promise => { + const { + search: dataSearchService, + query: { queryString }, + } = data; + + /** + * This is a newly created dashboard, so there is no saved object state to load. + */ + if (!id) return { dashboardState: defaultDashboardState }; + + /** + * Load the saved object + */ + const { + outcome, + alias_purpose: aliasPurpose, + alias_target_id: aliasId, + saved_object: rawDashboardSavedObject, + } = await savedObjectsClient.resolve( + DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, + id + ); + if (!rawDashboardSavedObject._version) { + throw new SavedObjectNotFound(DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, id); + } + + /** + * Inject saved object references back into the saved object attributes + */ + const { references, attributes: rawAttributes } = rawDashboardSavedObject; + const attributes = (() => { + if (!references || references.length === 0) return rawAttributes; + return injectReferences( + { references, attributes: rawAttributes as unknown as SavedObjectAttributes }, + { + embeddablePersistableStateService: embeddable, + } + ) as unknown as DashboardAttributes; + })(); + + /** + * Handle saved object resolve alias outcome by redirecting + */ + const scopedHistory = getScopedHistory?.(); + if (scopedHistory && outcome === 'aliasMatch' && id && aliasId) { + const path = scopedHistory.location.hash.replace(id, aliasId); + if (screenshotMode.isScreenshotMode()) { + scopedHistory.replace(path); + } else { + await spaces.redirectLegacyUrl?.({ path, aliasPurpose }); + } + return { redirectedToAlias: true }; + } + + /** + * Create conflict warning component if there is a saved object id conflict + */ + const createConflictWarning = + scopedHistory && outcome === 'conflict' && aliasId + ? () => + spaces.getLegacyUrlConflict?.({ + currentObjectId: id, + otherObjectId: aliasId, + otherObjectPath: `#${createDashboardEditUrl(aliasId)}${scopedHistory.location.search}`, + }) + : undefined; + + /** + * Create search source and pull filters and query from it. + */ + const searchSourceJSON = attributes.kibanaSavedObjectMeta.searchSourceJSON; + const searchSource = await (async () => { + if (!searchSourceJSON) { + return await dataSearchService.searchSource.create(); + } + try { + let searchSourceValues = parseSearchSourceJSON(searchSourceJSON); + searchSourceValues = injectSearchSourceReferences(searchSourceValues as any, references); + return await dataSearchService.searchSource.create(searchSourceValues); + } catch (error: any) { + return await dataSearchService.searchSource.create(); + } + })(); + + const filters = cleanFiltersForSerialize((searchSource?.getOwnField('filter') as Filter[]) ?? []); + + const query = migrateLegacyQuery( + searchSource?.getOwnField('query') || queryString.getDefaultQuery() // TODO SAVED DASHBOARDS determine if migrateLegacyQuery is still needed + ); + + const { + refreshInterval, + description, + timeRestore, + optionsJSON, + panelsJSON, + timeFrom, + timeTo, + title, + } = attributes; + + const timeRange = + timeRestore && timeFrom && timeTo + ? { + from: timeFrom, + to: timeTo, + } + : undefined; + + /** + * Parse panels and options from JSON + */ + const options: DashboardOptions = optionsJSON ? JSON.parse(optionsJSON) : undefined; + const panels = convertSavedPanelsToPanelMap(panelsJSON ? JSON.parse(panelsJSON) : []); + + return { + createConflictWarning, + dashboardState: { + ...defaultDashboardState, + + savedObjectId: id, + refreshInterval, + timeRestore, + description, + timeRange, + options, + filters, + panels, + title, + query, + + viewMode: ViewMode.VIEW, // dashboards loaded from saved object default to view mode. If it was edited recently, the view mode from session storage will override this. + tags: savedObjectsTagging.getTagIdsFromReferences?.(references) ?? [], + + controlGroupInput: + attributes.controlGroupInput && + rawControlGroupAttributesToControlGroupInput(attributes.controlGroupInput), + }, + }; +}; diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts new file mode 100644 index 0000000000000..11c6988d22f96 --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/lib/save_dashboard_state_to_saved_object.ts @@ -0,0 +1,182 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { pick } from 'lodash'; + +import { isFilterPinned } from '@kbn/es-query'; +import { SavedObjectsClientContract } from '@kbn/core/public'; +import { SavedObjectAttributes } from '@kbn/core-saved-objects-common'; + +import { extractSearchSourceReferences, RefreshInterval } from '@kbn/data-plugin/public'; +import { SavedObjectSaveOpts } from '@kbn/saved-objects-plugin/public'; + +import type { DashboardAttributes } from '../../../application'; +import { DashboardSavedObjectRequiredServices } from '../types'; +import { DashboardConstants } from '../../../dashboard_constants'; +import { convertTimeToUTCString } from '../../../application/lib'; +import { DashboardRedirect, DashboardState } from '../../../types'; +import { dashboardSaveToastStrings } from '../../../dashboard_strings'; +import { convertPanelMapToSavedPanels, extractReferences } from '../../../../common'; +import { serializeControlGroupInput } from '../../../application/lib/dashboard_control_group'; + +export type SavedDashboardSaveOpts = SavedObjectSaveOpts & { saveAsCopy?: boolean }; + +export type SaveDashboardProps = DashboardSavedObjectRequiredServices & { + currentState: DashboardState; + redirectTo: DashboardRedirect; + saveOptions: SavedDashboardSaveOpts; + savedObjectsClient: SavedObjectsClientContract; +}; + +export interface SaveDashboardReturn { + id?: string; + error?: string; + redirected?: boolean; +} + +export const saveDashboardStateToSavedObject = async ({ + data, + redirectTo, + embeddable, + saveOptions, + currentState, + savedObjectsClient, + savedObjectsTagging, + dashboardSessionStorage, + notifications: { toasts }, + initializerContext: { kibanaVersion }, +}: SaveDashboardProps): Promise => { + const { + search: dataSearchService, + query: { + timefilter: { timefilter }, + }, + } = data; + + const { + tags, + query, + title, + panels, + filters, + options, + timeRestore, + description, + savedObjectId, + controlGroupInput, + } = currentState; + + /** + * Stringify filters and query into search source JSON + */ + const { searchSourceJSON, searchSourceReferences } = await (async () => { + const searchSource = await dataSearchService.searchSource.create(); + searchSource.setField( + 'filter', // save only unpinned filters + filters.filter((filter) => !isFilterPinned(filter)) + ); + searchSource.setField('query', query); + + const rawSearchSourceFields = searchSource.getSerializedFields(); + const [fields, references] = extractSearchSourceReferences(rawSearchSourceFields); + return { searchSourceReferences: references, searchSourceJSON: JSON.stringify(fields) }; + })(); + + /** + * Stringify options and panels + */ + const optionsJSON = JSON.stringify(options); + const panelsJSON = JSON.stringify(convertPanelMapToSavedPanels(panels, kibanaVersion)); + + /** + * Parse global time filter settings + */ + const { from, to } = timefilter.getTime(); + const timeFrom = timeRestore ? convertTimeToUTCString(from) : undefined; + const timeTo = timeRestore ? convertTimeToUTCString(to) : undefined; + const refreshInterval = timeRestore + ? (pick(timefilter.getRefreshInterval(), [ + 'display', + 'pause', + 'section', + 'value', + ]) as RefreshInterval) + : undefined; + + const rawDashboardAttributes: DashboardAttributes = { + controlGroupInput: serializeControlGroupInput(controlGroupInput), + kibanaSavedObjectMeta: { searchSourceJSON }, + refreshInterval, + timeRestore, + optionsJSON, + description, + panelsJSON, + timeFrom, + title, + timeTo, + version: 1, // todo - where does version come from? Why is it needed? + }; + + /** + * Extract references from raw attributes and tags into the references array. + */ + const { attributes, references: dashboardReferences } = extractReferences( + { + attributes: rawDashboardAttributes as unknown as SavedObjectAttributes, + references: searchSourceReferences, + }, + { embeddablePersistableStateService: embeddable } + ); + const references = savedObjectsTagging.updateTagsReferences + ? savedObjectsTagging.updateTagsReferences(dashboardReferences, tags) + : dashboardReferences; + + /** + * Save the saved object using the saved objects client + */ + const idToSaveTo = saveOptions.saveAsCopy ? undefined : savedObjectId; + try { + const { id: newId } = await savedObjectsClient.create( + DashboardConstants.DASHBOARD_SAVED_OBJECT_TYPE, + attributes, + { + id: idToSaveTo, + overwrite: true, + references, + } + ); + + if (newId) { + toasts.addSuccess({ + title: dashboardSaveToastStrings.getSuccessString(currentState.title), + 'data-test-subj': 'saveDashboardSuccess', + }); + + /** + * If the dashboard id has been changed, redirect to the new ID to keep the url param in sync. + */ + if (newId !== savedObjectId) { + dashboardSessionStorage.clearState(savedObjectId); + redirectTo({ + id: newId, + editMode: true, + useReplace: true, + destination: 'dashboard', + }); + return { redirected: true, id: newId }; + } + } + return { id: newId }; + } catch (error) { + toasts.addDanger({ + title: dashboardSaveToastStrings.getFailureString(currentState.title, error.message), + 'data-test-subj': 'saveDashboardFailure', + }); + return { error }; + } +}; diff --git a/src/plugins/dashboard/public/services/dashboard_saved_object/types.ts b/src/plugins/dashboard/public/services/dashboard_saved_object/types.ts new file mode 100644 index 0000000000000..dd817c751aa8d --- /dev/null +++ b/src/plugins/dashboard/public/services/dashboard_saved_object/types.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { SavedObjectsClientContract } from '@kbn/core/public'; + +import { DashboardDataService } from '../data/types'; +import { DashboardSpacesService } from '../spaces/types'; +import { DashboardEmbeddableService } from '../embeddable/types'; +import { DashboardNotificationsService } from '../notifications/types'; +import { DashboardScreenshotModeService } from '../screenshot_mode/types'; +import { DashboardInitializerContextService } from '../initializer_context/types'; +import { DashboardSavedObjectsTaggingService } from '../saved_objects_tagging/types'; +import { DashboardSessionStorageServiceType } from '../dashboard_session_storage/types'; + +import { + LoadDashboardFromSavedObjectProps, + LoadDashboardFromSavedObjectReturn, +} from './lib/load_dashboard_state_from_saved_object'; +import { + SaveDashboardProps, + SaveDashboardReturn, +} from './lib/save_dashboard_state_to_saved_object'; +import { + FindDashboardBySavedObjectIdsResult, + FindDashboardSavedObjectsArgs, + FindDashboardSavedObjectsResponse, +} from './lib/find_dashboard_saved_objects'; +import { DashboardDuplicateTitleCheckProps } from './lib/check_for_duplicate_dashboard_title'; + +export interface DashboardSavedObjectRequiredServices { + screenshotMode: DashboardScreenshotModeService; + embeddable: DashboardEmbeddableService; + spaces: DashboardSpacesService; + data: DashboardDataService; + initializerContext: DashboardInitializerContextService; + notifications: DashboardNotificationsService; + savedObjectsTagging: DashboardSavedObjectsTaggingService; + dashboardSessionStorage: DashboardSessionStorageServiceType; +} + +export interface DashboardSavedObjectService { + loadDashboardStateFromSavedObject: ( + props: Pick + ) => Promise; + + saveDashboardStateToSavedObject: ( + props: Pick + ) => Promise; + findDashboards: { + findSavedObjects: ( + props: Pick + ) => Promise; + findByIds: (ids: string[]) => Promise; + findByTitle: (title: string) => Promise<{ id: string } | undefined>; + }; + checkForDuplicateDashboardTitle: (meta: DashboardDuplicateTitleCheckProps) => Promise; + savedObjectsClient: SavedObjectsClientContract; +} diff --git a/src/plugins/dashboard/public/services/embeddable/embeddable.stub.ts b/src/plugins/dashboard/public/services/embeddable/embeddable.stub.ts index 18f952d4620e2..a1a6b2973664f 100644 --- a/src/plugins/dashboard/public/services/embeddable/embeddable.stub.ts +++ b/src/plugins/dashboard/public/services/embeddable/embeddable.stub.ts @@ -16,9 +16,13 @@ export const embeddableServiceFactory: EmbeddableServiceFactory = () => { const pluginMock = embeddablePluginMock.createStartContract(); return { - getEmbeddableFactory: pluginMock.getEmbeddableFactory, getEmbeddableFactories: pluginMock.getEmbeddableFactories, + getEmbeddableFactory: pluginMock.getEmbeddableFactory, getStateTransfer: pluginMock.getStateTransfer, + getAllMigrations: pluginMock.getAllMigrations, EmbeddablePanel: pluginMock.EmbeddablePanel, + telemetry: pluginMock.telemetry, + extract: pluginMock.extract, + inject: pluginMock.inject, }; }; diff --git a/src/plugins/dashboard/public/services/embeddable/embeddable_service.ts b/src/plugins/dashboard/public/services/embeddable/embeddable_service.ts index 258c11f697bc5..c796bbde2d7da 100644 --- a/src/plugins/dashboard/public/services/embeddable/embeddable_service.ts +++ b/src/plugins/dashboard/public/services/embeddable/embeddable_service.ts @@ -6,7 +6,10 @@ * Side Public License, v 1. */ +import { pick } from 'lodash'; + import type { KibanaPluginServiceFactory } from '@kbn/presentation-util-plugin/public'; + import type { DashboardStartDependencies } from '../../plugin'; import type { DashboardEmbeddableService } from './types'; @@ -15,14 +18,16 @@ export type EmbeddableServiceFactory = KibanaPluginServiceFactory< DashboardStartDependencies >; export const embeddableServiceFactory: EmbeddableServiceFactory = ({ startPlugins }) => { - const { - embeddable: { getEmbeddableFactory, getEmbeddableFactories, getStateTransfer, EmbeddablePanel }, - } = startPlugins; + const { embeddable } = startPlugins; - return { - getEmbeddableFactory, - getEmbeddableFactories, - getStateTransfer, - EmbeddablePanel, - }; + return pick(embeddable, [ + 'getEmbeddableFactory', + 'getEmbeddableFactories', + 'getStateTransfer', + 'EmbeddablePanel', + 'getAllMigrations', + 'telemetry', + 'extract', + 'inject', + ]); }; diff --git a/src/plugins/dashboard/public/services/embeddable/types.ts b/src/plugins/dashboard/public/services/embeddable/types.ts index ef24db7c2e624..40d0ae02bfa7c 100644 --- a/src/plugins/dashboard/public/services/embeddable/types.ts +++ b/src/plugins/dashboard/public/services/embeddable/types.ts @@ -8,9 +8,14 @@ import type { EmbeddableStart } from '@kbn/embeddable-plugin/public'; -export interface DashboardEmbeddableService { - getEmbeddableFactory: EmbeddableStart['getEmbeddableFactory']; - getEmbeddableFactories: EmbeddableStart['getEmbeddableFactories']; - getStateTransfer: EmbeddableStart['getStateTransfer']; - EmbeddablePanel: EmbeddableStart['EmbeddablePanel']; -} +export type DashboardEmbeddableService = Pick< + EmbeddableStart, + | 'getEmbeddableFactories' + | 'getEmbeddableFactory' + | 'getAllMigrations' + | 'getStateTransfer' + | 'EmbeddablePanel' + | 'telemetry' + | 'extract' + | 'inject' +>; diff --git a/src/plugins/dashboard/public/services/plugin_services.stub.ts b/src/plugins/dashboard/public/services/plugin_services.stub.ts index c703b8b6767ac..b8c39909dd61a 100644 --- a/src/plugins/dashboard/public/services/plugin_services.stub.ts +++ b/src/plugins/dashboard/public/services/plugin_services.stub.ts @@ -29,7 +29,6 @@ import { initializerContextServiceFactory } from './initializer_context/initiali import { navigationServiceFactory } from './navigation/navigation.stub'; import { notificationsServiceFactory } from './notifications/notifications.stub'; import { overlaysServiceFactory } from './overlays/overlays.stub'; -import { savedObjectsServiceFactory } from './saved_objects/saved_objects.stub'; import { savedObjectsTaggingServiceFactory } from './saved_objects_tagging/saved_objects_tagging.stub'; import { screenshotModeServiceFactory } from './screenshot_mode/screenshot_mode.stub'; import { settingsServiceFactory } from './settings/settings.stub'; @@ -38,8 +37,10 @@ import { usageCollectionServiceFactory } from './usage_collection/usage_collecti import { spacesServiceFactory } from './spaces/spaces.stub'; import { urlForwardingServiceFactory } from './url_forwarding/url_fowarding.stub'; import { visualizationsServiceFactory } from './visualizations/visualizations.stub'; +import { dashboardSavedObjectServiceFactory } from './dashboard_saved_object/dashboard_saved_object.stub'; export const providers: PluginServiceProviders = { + dashboardSavedObject: new PluginServiceProvider(dashboardSavedObjectServiceFactory), analytics: new PluginServiceProvider(analyticsServiceFactory), application: new PluginServiceProvider(applicationServiceFactory), chrome: new PluginServiceProvider(chromeServiceFactory), @@ -55,7 +56,6 @@ export const providers: PluginServiceProviders = { navigation: new PluginServiceProvider(navigationServiceFactory), notifications: new PluginServiceProvider(notificationsServiceFactory), overlays: new PluginServiceProvider(overlaysServiceFactory), - savedObjects: new PluginServiceProvider(savedObjectsServiceFactory), savedObjectsTagging: new PluginServiceProvider(savedObjectsTaggingServiceFactory), screenshotMode: new PluginServiceProvider(screenshotModeServiceFactory), settings: new PluginServiceProvider(settingsServiceFactory), diff --git a/src/plugins/dashboard/public/services/plugin_services.ts b/src/plugins/dashboard/public/services/plugin_services.ts index 421b5e75c482c..b4ee1b566a8ac 100644 --- a/src/plugins/dashboard/public/services/plugin_services.ts +++ b/src/plugins/dashboard/public/services/plugin_services.ts @@ -30,7 +30,6 @@ import { navigationServiceFactory } from './navigation/navigation_service'; import { notificationsServiceFactory } from './notifications/notifications_service'; import { overlaysServiceFactory } from './overlays/overlays_service'; import { screenshotModeServiceFactory } from './screenshot_mode/screenshot_mode_service'; -import { savedObjectsServiceFactory } from './saved_objects/saved_objects_service'; import { savedObjectsTaggingServiceFactory } from './saved_objects_tagging/saved_objects_tagging_service'; import { settingsServiceFactory } from './settings/settings_service'; import { shareServiceFactory } from './share/share_services'; @@ -39,17 +38,29 @@ import { urlForwardingServiceFactory } from './url_forwarding/url_forwarding_ser import { visualizationsServiceFactory } from './visualizations/visualizations_service'; import { usageCollectionServiceFactory } from './usage_collection/usage_collection_service'; import { analyticsServiceFactory } from './analytics/analytics_service'; +import { dashboardSavedObjectServiceFactory } from './dashboard_saved_object/dashboard_saved_object_service'; const providers: PluginServiceProviders = { + dashboardSavedObject: new PluginServiceProvider(dashboardSavedObjectServiceFactory, [ + 'dashboardSessionStorage', + 'savedObjectsTagging', + 'initializerContext', + 'screenshotMode', + 'notifications', + 'embeddable', + 'spaces', + 'data', + ]), + dashboardSessionStorage: new PluginServiceProvider(dashboardSessionStorageServiceFactory, [ + 'notifications', + 'spaces', + ]), + analytics: new PluginServiceProvider(analyticsServiceFactory), application: new PluginServiceProvider(applicationServiceFactory), chrome: new PluginServiceProvider(chromeServiceFactory), coreContext: new PluginServiceProvider(coreContextServiceFactory), dashboardCapabilities: new PluginServiceProvider(dashboardCapabilitiesServiceFactory), - dashboardSessionStorage: new PluginServiceProvider(dashboardSessionStorageServiceFactory, [ - 'notifications', - 'spaces', - ]), data: new PluginServiceProvider(dataServiceFactory), dataViewEditor: new PluginServiceProvider(dataViewEditorServiceFactory), documentationLinks: new PluginServiceProvider(documentationLinksServiceFactory), @@ -59,7 +70,6 @@ const providers: PluginServiceProviders SavedObject; - public type: string; - public lowercaseType: string; - public loaderProperties: Record; - - constructor( - SavedObjectClass: any, - private readonly savedObjectsClient: SavedObjectsClientContract - ) { - this.type = SavedObjectClass.type; - this.Class = SavedObjectClass; - this.lowercaseType = this.type.toLowerCase(); - - this.loaderProperties = { - name: `${this.lowercaseType}s`, - noun: upperFirst(this.type), - nouns: `${this.lowercaseType}s`, - }; - } - - /** - * Retrieve a saved object by id or create new one. - * Returns a promise that completes when the object finishes - * initializing. - * @param opts - * @returns {Promise} - */ - async get(opts?: Record | string) { - // can accept object as argument in accordance to SavedVis class - // see src/plugins/saved_objects/public/saved_object/saved_object_loader.ts - // @ts-ignore - const obj = new this.Class(opts); - return obj.init(); - } - - urlFor(id: string) { - return `#/${this.lowercaseType}/${encodeURIComponent(id)}`; - } - - async delete(ids: string | string[]) { - const idsUsed = !Array.isArray(ids) ? [ids] : ids; - - const deletions = idsUsed.map((id) => { - // @ts-ignore - const savedObject = new this.Class(id); - return savedObject.delete(); - }); - await Promise.all(deletions); - } - - /** - * Updates source to contain an id, url and references fields, and returns the updated - * source object. - * @param source - * @param id - * @param references - * @returns {source} The modified source object, with an id and url field. - */ - mapHitSource( - source: Record, - id: string, - references: SavedObjectReference[] = [], - updatedAt?: string - ): Record { - return { - ...source, - id, - url: this.urlFor(id), - references, - updatedAt, - }; - } - - /** - * Updates hit.attributes to contain an id and url field, and returns the updated - * attributes object. - * @param hit - * @returns {hit.attributes} The modified hit.attributes object, with an id and url field. - */ - mapSavedObjectApiHits({ - attributes, - id, - references = [], - updatedAt, - }: { - attributes: Record; - id: string; - references?: SavedObjectReference[]; - updatedAt?: string; - }) { - return this.mapHitSource(attributes, id, references, updatedAt); - } - - /** - * TODO: Rather than use a hardcoded limit, implement pagination. See - * https://github.com/elastic/kibana/issues/8044 for reference. - * - * @param search - * @param size - * @param fields - * @returns {Promise} - */ - private findAll( - search: string = '', - { size = 100, fields, hasReference }: SavedObjectLoaderFindOptions - ) { - return this.savedObjectsClient - .find>({ - type: this.lowercaseType, - search: search ? `${search}*` : undefined, - perPage: size, - page: 1, - searchFields: ['title^3', 'description'], - defaultSearchOperator: 'AND', - fields, - hasReference, - } as SavedObjectsFindOptions) - .then((resp) => { - return { - total: resp.total, - hits: resp.savedObjects.map((savedObject) => this.mapSavedObjectApiHits(savedObject)), - }; - }); - } - - find(search: string = '', sizeOrOptions: number | SavedObjectLoaderFindOptions = 100) { - const options: SavedObjectLoaderFindOptions = - typeof sizeOrOptions === 'number' - ? { - size: sizeOrOptions, - } - : sizeOrOptions; - - return this.findAll(search, options).then((resp) => { - return { - total: resp.total, - hits: resp.hits.filter((savedObject) => !savedObject.error), - }; - }); - } -} diff --git a/src/plugins/dashboard/public/services/saved_objects/saved_objects.stub.ts b/src/plugins/dashboard/public/services/saved_objects/saved_objects.stub.ts deleted file mode 100644 index f26e36392603f..0000000000000 --- a/src/plugins/dashboard/public/services/saved_objects/saved_objects.stub.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { savedObjectsServiceMock } from '@kbn/core-saved-objects-browser-mocks'; -import { PluginServiceFactory } from '@kbn/presentation-util-plugin/public'; -import { DashboardSavedObjectsService } from './types'; - -type SavedObjectsServiceFactory = PluginServiceFactory; - -export const savedObjectsServiceFactory: SavedObjectsServiceFactory = () => { - const pluginMock = savedObjectsServiceMock.createStartContract(); - - return { - client: pluginMock.client, - }; -}; diff --git a/src/plugins/dashboard/public/services/saved_objects/saved_objects_service.ts b/src/plugins/dashboard/public/services/saved_objects/saved_objects_service.ts deleted file mode 100644 index 3fff4d9e1c361..0000000000000 --- a/src/plugins/dashboard/public/services/saved_objects/saved_objects_service.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import type { KibanaPluginServiceFactory } from '@kbn/presentation-util-plugin/public'; -import type { DashboardStartDependencies } from '../../plugin'; -import type { DashboardSavedObjectsService } from './types'; - -export type SavedObjectsServiceFactory = KibanaPluginServiceFactory< - DashboardSavedObjectsService, - DashboardStartDependencies ->; - -export const savedObjectsServiceFactory: SavedObjectsServiceFactory = ({ coreStart }) => { - const { - savedObjects: { client }, - } = coreStart; - - return { - client, - }; -}; diff --git a/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging.stub.ts b/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging.stub.ts index d526eedbc1e47..1a1bcd6ca93bf 100644 --- a/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging.stub.ts +++ b/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging.stub.ts @@ -20,9 +20,10 @@ export const savedObjectsTaggingServiceFactory: SavedObjectsTaggingServiceFactor // I'm not defining components so that I don't have to update the snapshot of `save_modal.test` // However, if it's ever necessary, it can be done via: `components: pluginMock.components`, - getSearchBarFilter: pluginMock.getSearchBarFilter, - getTableColumnDefinition: pluginMock.getTableColumnDefinition, hasTagDecoration: pluginMock.hasTagDecoration, parseSearchQuery: pluginMock.parseSearchQuery, + getSearchBarFilter: pluginMock.getSearchBarFilter, + getTagIdsFromReferences: pluginMock.getTagIdsFromReferences, + getTableColumnDefinition: pluginMock.getTableColumnDefinition, }; }; diff --git a/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging_service.ts b/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging_service.ts index 7e252ed79d7b7..a100282b4cff2 100644 --- a/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging_service.ts +++ b/src/plugins/dashboard/public/services/saved_objects_tagging/saved_objects_tagging_service.ts @@ -27,19 +27,23 @@ export const savedObjectsTaggingServiceFactory: SavedObjectsTaggingServiceFactor const { ui: { components, + parseSearchQuery, + hasTagDecoration, getSearchBarFilter, + updateTagsReferences, + getTagIdsFromReferences, getTableColumnDefinition, - hasTagDecoration, - parseSearchQuery, }, } = taggingApi; return { hasApi: true, components, - getSearchBarFilter, - getTableColumnDefinition, hasTagDecoration, parseSearchQuery, + getSearchBarFilter, + updateTagsReferences, + getTagIdsFromReferences, + getTableColumnDefinition, }; }; diff --git a/src/plugins/dashboard/public/services/saved_objects_tagging/types.ts b/src/plugins/dashboard/public/services/saved_objects_tagging/types.ts index 803db5ff46d9a..ba08a53709346 100644 --- a/src/plugins/dashboard/public/services/saved_objects_tagging/types.ts +++ b/src/plugins/dashboard/public/services/saved_objects_tagging/types.ts @@ -12,9 +12,10 @@ export interface DashboardSavedObjectsTaggingService { hasApi: boolean; // remove this once the entire service is optional components?: SavedObjectsTaggingApi['ui']['components']; - getSearchBarFilter?: SavedObjectsTaggingApi['ui']['getSearchBarFilter']; - getTableColumnDefinition?: SavedObjectsTaggingApi['ui']['getTableColumnDefinition']; hasTagDecoration?: SavedObjectsTaggingApi['ui']['hasTagDecoration']; parseSearchQuery?: SavedObjectsTaggingApi['ui']['parseSearchQuery']; + getSearchBarFilter?: SavedObjectsTaggingApi['ui']['getSearchBarFilter']; + updateTagsReferences?: SavedObjectsTaggingApi['ui']['updateTagsReferences']; getTagIdsFromReferences?: SavedObjectsTaggingApi['ui']['getTagIdsFromReferences']; + getTableColumnDefinition?: SavedObjectsTaggingApi['ui']['getTableColumnDefinition']; } diff --git a/src/plugins/dashboard/public/services/types.ts b/src/plugins/dashboard/public/services/types.ts index 3309ce0575971..5d14b59e8a125 100644 --- a/src/plugins/dashboard/public/services/types.ts +++ b/src/plugins/dashboard/public/services/types.ts @@ -15,6 +15,7 @@ import { DashboardApplicationService } from './application/types'; import { DashboardChromeService } from './chrome/types'; import { DashboardCoreContextService } from './core_context/types'; import { DashboardCapabilitiesService } from './dashboard_capabilities/types'; +import { DashboardSavedObjectService } from './dashboard_saved_object/types'; import { DashboardSessionStorageServiceType } from './dashboard_session_storage/types'; import { DashboardDataService } from './data/types'; import { DashboardDataViewEditorService } from './data_view_editor/types'; @@ -25,7 +26,6 @@ import { DashboardInitializerContextService } from './initializer_context/types' import { DashboardNavigationService } from './navigation/types'; import { DashboardNotificationsService } from './notifications/types'; import { DashboardOverlaysService } from './overlays/types'; -import { DashboardSavedObjectsService } from './saved_objects/types'; import { DashboardSavedObjectsTaggingService } from './saved_objects_tagging/types'; import { DashboardScreenshotModeService } from './screenshot_mode/types'; import { DashboardSettingsService } from './settings/types'; @@ -39,12 +39,14 @@ export type DashboardPluginServiceParams = KibanaPluginServiceParams void; -export interface SavedDashboardPanelMap { - [key: string]: SavedDashboardPanel; -} - -export interface DashboardPanelMap { - [key: string]: DashboardPanelState; -} /** * DashboardState contains all pieces of tracked state for an individual dashboard @@ -48,11 +41,13 @@ export interface DashboardState { description: string; savedQuery?: string; timeRestore: boolean; + timeRange?: TimeRange; + savedObjectId?: string; fullScreenMode: boolean; expandedPanelId?: string; options: DashboardOptions; panels: DashboardPanelMap; - timeRange?: TimeRange; + refreshInterval?: RefreshInterval; timeslice?: [number, number]; controlGroupInput?: PersistableControlGroupInput; @@ -95,19 +90,17 @@ export interface DashboardAppState { dataViews?: DataView[]; updateLastSavedState?: () => void; resetToLastSavedState?: () => void; - savedDashboard?: DashboardSavedObject; dashboardContainer?: DashboardContainer; + createConflictWarning?: () => ReactElement | undefined; getLatestDashboardState?: () => DashboardState; $triggerDashboardRefresh: Subject<{ force?: boolean }>; $onDashboardStateChange: BehaviorSubject; - applyFilters?: (query: Query, filters: Filter[]) => void; } /** * The shared services and tools used to build a dashboard from a saved object ID. */ -// TODO: Remove reference to DashboardAppServices as part of https://github.com/elastic/kibana/pull/138774 -export type DashboardBuildContext = Pick & { +export interface DashboardBuildContext { locatorState?: DashboardAppLocatorParams; history: History; isEmbeddedExternally: boolean; @@ -118,7 +111,7 @@ export type DashboardBuildContext = Pick; $onDashboardStateChange: BehaviorSubject; executionContext?: KibanaExecutionContext; -}; +} // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export type DashboardOptions = { @@ -156,8 +149,3 @@ export interface DashboardMountContextProps { onAppLeave: AppMountParameters['onAppLeave']; setHeaderActionMenu: AppMountParameters['setHeaderActionMenu']; } - -// TODO: Remove DashboardAppServices as part of https://github.com/elastic/kibana/pull/138774 -export interface DashboardAppServices { - savedDashboards: SavedObjectLoader; -} diff --git a/src/plugins/dashboard/server/embeddable/dashboard_container_embeddable_factory.ts b/src/plugins/dashboard/server/embeddable/dashboard_container_embeddable_factory.ts index 31c236da607a4..df183f631a3ec 100644 --- a/src/plugins/dashboard/server/embeddable/dashboard_container_embeddable_factory.ts +++ b/src/plugins/dashboard/server/embeddable/dashboard_container_embeddable_factory.ts @@ -8,10 +8,7 @@ import { EmbeddablePersistableStateService } from '@kbn/embeddable-plugin/common'; import { EmbeddableRegistryDefinition } from '@kbn/embeddable-plugin/server'; -import { - createExtract, - createInject, -} from '../../common/embeddable/dashboard_container_persistable_state'; +import { createExtract, createInject } from '../../common'; export const dashboardPersistableStateServiceFactory = ( persistableStateService: EmbeddablePersistableStateService diff --git a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts b/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts deleted file mode 100644 index b3625bec3e8a9..0000000000000 --- a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { Serializable } from '@kbn/utility-types'; -import { get, flow, mapValues } from 'lodash'; -import { - SavedObjectAttributes, - SavedObjectMigrationFn, - SavedObjectMigrationMap, -} from '@kbn/core/server'; - -import { EmbeddableSetup } from '@kbn/embeddable-plugin/server'; -import { SavedObjectEmbeddableInput } from '@kbn/embeddable-plugin/common'; -import { DATA_VIEW_SAVED_OBJECT_TYPE } from '@kbn/data-plugin/common'; -import { - mergeMigrationFunctionMaps, - MigrateFunction, - MigrateFunctionsObject, -} from '@kbn/kibana-utils-plugin/common'; -import { - CONTROL_GROUP_TYPE, - rawControlGroupAttributesToSerializable, - serializableToRawControlGroupAttributes, -} from '@kbn/controls-plugin/common'; -import { migrations730 } from './migrations_730'; -import { SavedDashboardPanel } from '../../common/types'; -import { migrateMatchAllQuery } from './migrate_match_all_query'; -import { DashboardDoc700To720, DashboardDoc730ToLatest } from '../../common'; -import { injectReferences, extractReferences } from '../../common/saved_dashboard_references'; -import { - convertPanelStateToSavedDashboardPanel, - convertSavedDashboardPanelToPanelState, -} from '../../common/embeddable/embeddable_saved_object_converters'; -import { replaceIndexPatternReference } from './replace_index_pattern_reference'; - -function migrateIndexPattern(doc: DashboardDoc700To720) { - const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); - if (typeof searchSourceJSON !== 'string') { - return; - } - let searchSource; - try { - searchSource = JSON.parse(searchSourceJSON); - } catch (e) { - // Let it go, the data is invalid and we'll leave it as is - return; - } - if (searchSource.index) { - searchSource.indexRefName = 'kibanaSavedObjectMeta.searchSourceJSON.index'; - doc.references.push({ - name: searchSource.indexRefName, - type: DATA_VIEW_SAVED_OBJECT_TYPE, - id: searchSource.index, - }); - delete searchSource.index; - } - if (searchSource.filter) { - searchSource.filter.forEach((filterRow: any, i: number) => { - if (!filterRow.meta || !filterRow.meta.index) { - return; - } - filterRow.meta.indexRefName = `kibanaSavedObjectMeta.searchSourceJSON.filter[${i}].meta.index`; - doc.references.push({ - name: filterRow.meta.indexRefName, - type: DATA_VIEW_SAVED_OBJECT_TYPE, - id: filterRow.meta.index, - }); - delete filterRow.meta.index; - }); - } - doc.attributes.kibanaSavedObjectMeta.searchSourceJSON = JSON.stringify(searchSource); -} - -const migrations700: SavedObjectMigrationFn = (doc): DashboardDoc700To720 => { - // Set new "references" attribute - doc.references = doc.references || []; - - // Migrate index pattern - migrateIndexPattern(doc as DashboardDoc700To720); - // Migrate panels - const panelsJSON = get(doc, 'attributes.panelsJSON'); - if (typeof panelsJSON !== 'string') { - return doc as DashboardDoc700To720; - } - let panels; - try { - panels = JSON.parse(panelsJSON); - } catch (e) { - // Let it go, the data is invalid and we'll leave it as is - return doc as DashboardDoc700To720; - } - if (!Array.isArray(panels)) { - return doc as DashboardDoc700To720; - } - panels.forEach((panel, i) => { - if (!panel.type || !panel.id) { - return; - } - panel.panelRefName = `panel_${i}`; - doc.references!.push({ - name: `panel_${i}`, - type: panel.type, - id: panel.id, - }); - delete panel.type; - delete panel.id; - }); - doc.attributes.panelsJSON = JSON.stringify(panels); - return doc as DashboardDoc700To720; -}; - -/** - * In 7.8.0 we introduced dashboard drilldowns which are stored inside dashboard saved object as part of embeddable state - * In 7.11.0 we created an embeddable references/migrations system that allows to properly extract embeddable persistable state - * https://github.com/elastic/kibana/issues/71409 - * The idea of this migration is to inject all the embeddable panel references and then run the extraction again. - * As the result of the extraction: - * 1. In addition to regular `panel_` we will get new references which are extracted by `embeddablePersistableStateService` (dashboard drilldown references) - * 2. `panel_` references will be regenerated - * All other references like index-patterns are forwarded non touched - * @param deps - */ -function createExtractPanelReferencesMigration( - deps: DashboardSavedObjectTypeMigrationsDeps -): SavedObjectMigrationFn { - return (doc) => { - const references = doc.references ?? []; - - /** - * Remembering this because dashboard's extractReferences won't return those - * All other references like `panel_` will be overwritten - */ - const oldNonPanelReferences = references.filter((ref) => !ref.name.startsWith('panel_')); - - const injectedAttributes = injectReferences( - { - attributes: doc.attributes as unknown as SavedObjectAttributes, - references, - }, - { embeddablePersistableStateService: deps.embeddable } - ); - - const { attributes, references: newPanelReferences } = extractReferences( - { attributes: injectedAttributes, references: [] }, - { embeddablePersistableStateService: deps.embeddable } - ); - - return { - ...doc, - references: [...oldNonPanelReferences, ...newPanelReferences], - attributes, - }; - }; -} - -type ValueOrReferenceInput = SavedObjectEmbeddableInput & { - attributes?: Serializable; - savedVis?: Serializable; -}; - -/** - * Before 7.10, hidden panel titles were stored as a blank string on the title attribute. In 7.10, this was replaced - * with a usage of the existing hidePanelTitles key. Even though blank string titles still technically work - * in versions > 7.10, they are less explicit than using the hidePanelTitles key. This migration transforms all - * blank string titled panels to panels with the titles explicitly hidden. - */ -export const migrateExplicitlyHiddenTitles: SavedObjectMigrationFn = (doc) => { - const { attributes } = doc; - - // Skip if panelsJSON is missing - if (typeof attributes?.panelsJSON !== 'string') return doc; - - try { - const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; - // Same here, prevent failing saved object import if ever panels aren't an array. - if (!Array.isArray(panels)) return doc; - - const newPanels: SavedDashboardPanel[] = []; - panels.forEach((panel) => { - // Convert each panel into the dashboard panel state - const originalPanelState = - convertSavedDashboardPanelToPanelState(panel); - newPanels.push( - convertPanelStateToSavedDashboardPanel( - { - ...originalPanelState, - explicitInput: { - ...originalPanelState.explicitInput, - ...(originalPanelState.explicitInput.title === '' && - !originalPanelState.explicitInput.hidePanelTitles - ? { hidePanelTitles: true } - : {}), - }, - }, - panel.version - ) - ); - }); - return { - ...doc, - attributes: { - ...attributes, - panelsJSON: JSON.stringify(newPanels), - }, - }; - } catch { - return doc; - } -}; - -// Runs the embeddable migrations on each panel -const migrateByValuePanels = - (migrate: MigrateFunction, version: string): SavedObjectMigrationFn => - (doc: any) => { - const { attributes } = doc; - - if (attributes?.controlGroupInput) { - const controlGroupInput = rawControlGroupAttributesToSerializable( - attributes.controlGroupInput - ); - const migratedControlGroupInput = migrate({ - ...controlGroupInput, - type: CONTROL_GROUP_TYPE, - }); - attributes.controlGroupInput = - serializableToRawControlGroupAttributes(migratedControlGroupInput); - } - - // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when - // importing objects without panelsJSON. At development time of this, there is no guarantee each saved - // object has panelsJSON in all previous versions of kibana. - if (typeof attributes?.panelsJSON !== 'string') { - return doc; - } - - const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; - // Same here, prevent failing saved object import if ever panels aren't an array. - if (!Array.isArray(panels)) { - return doc; - } - const newPanels: SavedDashboardPanel[] = []; - panels.forEach((panel) => { - // Convert each panel into a state that can be passed to EmbeddablesSetup.migrate - const originalPanelState = - convertSavedDashboardPanelToPanelState(panel); - - // saved vis is used to store by value input for Visualize. This should eventually be renamed to `attributes` to align with Lens and Maps - if ( - originalPanelState.explicitInput.attributes || - originalPanelState.explicitInput.savedVis - ) { - // If this panel is by value, migrate the state using embeddable migrations - const migratedInput = migrate({ - ...originalPanelState.explicitInput, - type: originalPanelState.type, - }); - // Convert the embeddable state back into the panel shape - newPanels.push( - convertPanelStateToSavedDashboardPanel( - { - ...originalPanelState, - explicitInput: { ...migratedInput, id: migratedInput.id as string }, - }, - version - ) - ); - } else { - newPanels.push(panel); - } - }); - return { - ...doc, - attributes: { - ...attributes, - panelsJSON: JSON.stringify(newPanels), - }, - }; - }; - -export interface DashboardSavedObjectTypeMigrationsDeps { - embeddable: EmbeddableSetup; -} - -export const createDashboardSavedObjectTypeMigrations = ( - deps: DashboardSavedObjectTypeMigrationsDeps -): SavedObjectMigrationMap => { - const embeddableMigrations = mapValues( - deps.embeddable.getAllMigrations(), - migrateByValuePanels - ) as MigrateFunctionsObject; - - const dashboardMigrations = { - /** - * We need to have this migration twice, once with a version prior to 7.0.0 once with a version - * after it. The reason for that is, that this migration has been introduced once 7.0.0 was already - * released. Thus a user who already had 7.0.0 installed already got the 7.0.0 migrations below running, - * so we need a version higher than that. But this fix was backported to the 6.7 release, meaning if we - * would only have the 7.0.1 migration in here a user on the 6.7 release will migrate their saved objects - * to the 7.0.1 state, and thus when updating their Kibana to 7.0, will never run the 7.0.0 migrations introduced - * in that version. So we apply this twice, once with 6.7.2 and once with 7.0.1 while the backport to 6.7 - * only contained the 6.7.2 migration and not the 7.0.1 migration. - */ - '6.7.2': flow(migrateMatchAllQuery), - '7.0.0': flow(migrations700), - '7.3.0': flow(migrations730), - '7.9.3': flow(migrateMatchAllQuery), - '7.11.0': flow(createExtractPanelReferencesMigration(deps)), - '7.14.0': flow(replaceIndexPatternReference), - '7.17.3': flow(migrateExplicitlyHiddenTitles), - }; - - return mergeMigrationFunctionMaps(dashboardMigrations, embeddableMigrations); -}; diff --git a/src/plugins/dashboard/server/saved_objects/dashboard.ts b/src/plugins/dashboard/server/saved_objects/dashboard_saved_object.ts similarity index 97% rename from src/plugins/dashboard/server/saved_objects/dashboard.ts rename to src/plugins/dashboard/server/saved_objects/dashboard_saved_object.ts index 953852bee59cf..b8474149ca87b 100644 --- a/src/plugins/dashboard/server/saved_objects/dashboard.ts +++ b/src/plugins/dashboard/server/saved_objects/dashboard_saved_object.ts @@ -10,7 +10,7 @@ import { SavedObjectsType } from '@kbn/core/server'; import { createDashboardSavedObjectTypeMigrations, DashboardSavedObjectTypeMigrationsDeps, -} from './dashboard_migrations'; +} from './migrations/dashboard_saved_object_migrations'; export const createDashboardSavedObjectType = ({ migrationDeps, diff --git a/src/plugins/dashboard/server/saved_objects/index.ts b/src/plugins/dashboard/server/saved_objects/index.ts index af3de2dfca529..c16af55945f9d 100644 --- a/src/plugins/dashboard/server/saved_objects/index.ts +++ b/src/plugins/dashboard/server/saved_objects/index.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { createDashboardSavedObjectType } from './dashboard'; +export { createDashboardSavedObjectType } from './dashboard_saved_object'; diff --git a/src/plugins/dashboard/server/saved_objects/is_dashboard_doc.ts b/src/plugins/dashboard/server/saved_objects/is_dashboard_doc.ts deleted file mode 100644 index cea39fc45b0fe..0000000000000 --- a/src/plugins/dashboard/server/saved_objects/is_dashboard_doc.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { SavedObjectUnsanitizedDoc } from '@kbn/core/server'; -import { DashboardDoc730ToLatest } from '../../common'; - -function isDoc( - doc: { [key: string]: unknown } | SavedObjectUnsanitizedDoc -): doc is SavedObjectUnsanitizedDoc { - return ( - typeof doc.id === 'string' && - typeof doc.type === 'string' && - doc.attributes !== null && - typeof doc.attributes === 'object' && - doc.references !== null && - typeof doc.references === 'object' - ); -} - -export function isDashboardDoc( - doc: { [key: string]: unknown } | DashboardDoc730ToLatest -): doc is DashboardDoc730ToLatest { - if (!isDoc(doc)) { - return false; - } - - if (typeof (doc as DashboardDoc730ToLatest).attributes.panelsJSON !== 'string') { - return false; - } - - return true; -} diff --git a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.test.ts similarity index 99% rename from src/plugins/dashboard/server/saved_objects/dashboard_migrations.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.test.ts index 0cefab5104d7d..1a2655c481835 100644 --- a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.test.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.test.ts @@ -6,17 +6,15 @@ * Side Public License, v 1. */ -import { SavedObjectReference, SavedObjectUnsanitizedDoc } from '@kbn/core/server'; +import { SerializableRecord } from '@kbn/utility-types'; import { savedObjectsServiceMock } from '@kbn/core/server/mocks'; import { createEmbeddableSetupMock } from '@kbn/embeddable-plugin/server/mocks'; -import { createDashboardSavedObjectTypeMigrations } from './dashboard_migrations'; -import { DashboardDoc730ToLatest } from '../../common'; -import { - createExtract, - createInject, -} from '../../common/embeddable/dashboard_container_persistable_state'; +import { SavedObjectReference, SavedObjectUnsanitizedDoc } from '@kbn/core/server'; + +import { createExtract, createInject } from '../../../common'; import { EmbeddableStateWithType } from '@kbn/embeddable-plugin/common'; -import { SerializableRecord } from '@kbn/utility-types'; +import { createDashboardSavedObjectTypeMigrations } from './dashboard_saved_object_migrations'; +import { DashboardDoc730ToLatest } from './migrate_to_730/types'; const embeddableSetupMock = createEmbeddableSetupMock(); const extract = createExtract(embeddableSetupMock); diff --git a/src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.ts b/src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.ts new file mode 100644 index 0000000000000..2f93c038065bb --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/dashboard_saved_object_migrations.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { flow, mapValues } from 'lodash'; + +import { + mergeMigrationFunctionMaps, + MigrateFunctionsObject, +} from '@kbn/kibana-utils-plugin/common'; +import { EmbeddableSetup } from '@kbn/embeddable-plugin/server'; +import { SavedObjectMigrationFn, SavedObjectMigrationMap } from '@kbn/core/server'; + +import { migrations730, migrations700 } from './migrate_to_730'; +import { migrateMatchAllQuery } from './migrate_match_all_query'; +import { migrateExplicitlyHiddenTitles } from './migrate_hidden_titles'; +import { replaceIndexPatternReference } from './migrate_index_pattern_reference'; +import { migrateByValueDashboardPanels } from './migrate_by_value_dashboard_panels'; +import { createExtractPanelReferencesMigration } from './migrate_extract_panel_references'; + +export interface DashboardSavedObjectTypeMigrationsDeps { + embeddable: EmbeddableSetup; +} + +export const createDashboardSavedObjectTypeMigrations = ( + deps: DashboardSavedObjectTypeMigrationsDeps +): SavedObjectMigrationMap => { + const embeddableMigrations = mapValues( + deps.embeddable.getAllMigrations(), + migrateByValueDashboardPanels + ) as MigrateFunctionsObject; + + const dashboardMigrations = { + '6.7.2': flow(migrateMatchAllQuery), + '7.0.0': flow(migrations700), + '7.3.0': flow(migrations730), + '7.9.3': flow(migrateMatchAllQuery), + '7.11.0': flow(createExtractPanelReferencesMigration(deps)), + '7.14.0': flow(replaceIndexPatternReference), + '7.17.3': flow(migrateExplicitlyHiddenTitles), + }; + + return mergeMigrationFunctionMaps(dashboardMigrations, embeddableMigrations); +}; diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_by_value_dashboard_panels.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_by_value_dashboard_panels.ts new file mode 100644 index 0000000000000..3bad12b537103 --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_by_value_dashboard_panels.ts @@ -0,0 +1,97 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { + CONTROL_GROUP_TYPE, + rawControlGroupAttributesToSerializable, + serializableToRawControlGroupAttributes, +} from '@kbn/controls-plugin/common'; +import { Serializable } from '@kbn/utility-types'; +import { SavedObjectMigrationFn } from '@kbn/core/server'; +import { MigrateFunction } from '@kbn/kibana-utils-plugin/common'; +import { SavedObjectEmbeddableInput } from '@kbn/embeddable-plugin/common'; + +import { + convertPanelStateToSavedDashboardPanel, + convertSavedDashboardPanelToPanelState, + SavedDashboardPanel, +} from '../../../common'; + +type ValueOrReferenceInput = SavedObjectEmbeddableInput & { + attributes?: Serializable; + savedVis?: Serializable; +}; + +// Runs the embeddable migrations on each panel +export const migrateByValueDashboardPanels = + (migrate: MigrateFunction, version: string): SavedObjectMigrationFn => + (doc: any) => { + const { attributes } = doc; + + if (attributes?.controlGroupInput) { + const controlGroupInput = rawControlGroupAttributesToSerializable( + attributes.controlGroupInput + ); + const migratedControlGroupInput = migrate({ + ...controlGroupInput, + type: CONTROL_GROUP_TYPE, + }); + attributes.controlGroupInput = + serializableToRawControlGroupAttributes(migratedControlGroupInput); + } + + // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when + // importing objects without panelsJSON. At development time of this, there is no guarantee each saved + // object has panelsJSON in all previous versions of kibana. + if (typeof attributes?.panelsJSON !== 'string') { + return doc; + } + + const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; + // Same here, prevent failing saved object import if ever panels aren't an array. + if (!Array.isArray(panels)) { + return doc; + } + const newPanels: SavedDashboardPanel[] = []; + panels.forEach((panel) => { + // Convert each panel into a state that can be passed to EmbeddablesSetup.migrate + const originalPanelState = + convertSavedDashboardPanelToPanelState(panel); + + // saved vis is used to store by value input for Visualize. This should eventually be renamed to `attributes` to align with Lens and Maps + if ( + originalPanelState.explicitInput.attributes || + originalPanelState.explicitInput.savedVis + ) { + // If this panel is by value, migrate the state using embeddable migrations + const migratedInput = migrate({ + ...originalPanelState.explicitInput, + type: originalPanelState.type, + }); + // Convert the embeddable state back into the panel shape + newPanels.push( + convertPanelStateToSavedDashboardPanel( + { + ...originalPanelState, + explicitInput: { ...migratedInput, id: migratedInput.id as string }, + }, + version + ) + ); + } else { + newPanels.push(panel); + } + }); + return { + ...doc, + attributes: { + ...attributes, + panelsJSON: JSON.stringify(newPanels), + }, + }; + }; diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts new file mode 100644 index 0000000000000..5a8de73af988b --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_extract_panel_references.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { SavedObjectAttributes, SavedObjectMigrationFn } from '@kbn/core/server'; + +import { DashboardAttributes, extractReferences, injectReferences } from '../../../common'; +import { DashboardSavedObjectTypeMigrationsDeps } from './dashboard_saved_object_migrations'; + +/** + * In 7.8.0 we introduced dashboard drilldowns which are stored inside dashboard saved object as part of embeddable state + * In 7.11.0 we created an embeddable references/migrations system that allows to properly extract embeddable persistable state + * https://github.com/elastic/kibana/issues/71409 + * The idea of this migration is to inject all the embeddable panel references and then run the extraction again. + * As the result of the extraction: + * 1. In addition to regular `panel_` we will get new references which are extracted by `embeddablePersistableStateService` (dashboard drilldown references) + * 2. `panel_` references will be regenerated + * All other references like index-patterns are forwarded non touched + * @param deps + */ +export function createExtractPanelReferencesMigration( + deps: DashboardSavedObjectTypeMigrationsDeps +): SavedObjectMigrationFn { + return (doc) => { + const references = doc.references ?? []; + + /** + * Remembering this because dashboard's extractReferences won't return those + * All other references like `panel_` will be overwritten + */ + const oldNonPanelReferences = references.filter((ref) => !ref.name.startsWith('panel_')); + + const injectedAttributes = injectReferences( + { + attributes: doc.attributes as unknown as SavedObjectAttributes, + references, + }, + { embeddablePersistableStateService: deps.embeddable } + ); + + const { attributes, references: newPanelReferences } = extractReferences( + { attributes: injectedAttributes, references: [] }, + { embeddablePersistableStateService: deps.embeddable } + ); + + return { + ...doc, + references: [...oldNonPanelReferences, ...newPanelReferences], + attributes, + }; + }; +} diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_hidden_titles.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_hidden_titles.ts new file mode 100644 index 0000000000000..8a9a917231204 --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_hidden_titles.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { SavedObjectMigrationFn } from '@kbn/core/server'; +import { EmbeddableInput } from '@kbn/embeddable-plugin/common'; + +import { + convertSavedDashboardPanelToPanelState, + convertPanelStateToSavedDashboardPanel, + SavedDashboardPanel, +} from '../../../common'; + +/** + * Before 7.10, hidden panel titles were stored as a blank string on the title attribute. In 7.10, this was replaced + * with a usage of the existing hidePanelTitles key. Even though blank string titles still technically work + * in versions > 7.10, they are less explicit than using the hidePanelTitles key. This migration transforms all + * blank string titled panels to panels with the titles explicitly hidden. + */ +export const migrateExplicitlyHiddenTitles: SavedObjectMigrationFn = (doc) => { + const { attributes } = doc; + + // Skip if panelsJSON is missing + if (typeof attributes?.panelsJSON !== 'string') return doc; + + try { + const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; + // Same here, prevent failing saved object import if ever panels aren't an array. + if (!Array.isArray(panels)) return doc; + + const newPanels: SavedDashboardPanel[] = []; + panels.forEach((panel) => { + // Convert each panel into the dashboard panel state + const originalPanelState = convertSavedDashboardPanelToPanelState(panel); + newPanels.push( + convertPanelStateToSavedDashboardPanel( + { + ...originalPanelState, + explicitInput: { + ...originalPanelState.explicitInput, + ...(originalPanelState.explicitInput.title === '' && + !originalPanelState.explicitInput.hidePanelTitles + ? { hidePanelTitles: true } + : {}), + }, + }, + panel.version + ) + ); + }); + return { + ...doc, + attributes: { + ...attributes, + panelsJSON: JSON.stringify(newPanels), + }, + }; + } catch { + return doc; + } +}; diff --git a/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_index_pattern_reference.test.ts similarity index 94% rename from src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_index_pattern_reference.test.ts index 13db82790c9d0..a9682bdb8719d 100644 --- a/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_index_pattern_reference.test.ts @@ -7,7 +7,7 @@ */ import type { SavedObjectMigrationContext, SavedObjectMigrationFn } from '@kbn/core/server'; -import { replaceIndexPatternReference } from './replace_index_pattern_reference'; +import { replaceIndexPatternReference } from './migrate_index_pattern_reference'; describe('replaceIndexPatternReference', () => { const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; diff --git a/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_index_pattern_reference.ts similarity index 100% rename from src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_index_pattern_reference.ts diff --git a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_match_all_query.test.ts similarity index 100% rename from src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_match_all_query.test.ts diff --git a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_match_all_query.ts similarity index 100% rename from src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_match_all_query.ts index 147aa47a7a6e9..a7c1f0ff6bdb5 100644 --- a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_match_all_query.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -import { SavedObjectMigrationFn } from '@kbn/core/server'; import { get } from 'lodash'; import { DEFAULT_QUERY_LANGUAGE } from '@kbn/data-plugin/common'; +import { SavedObjectMigrationFn } from '@kbn/core/server'; /** * This migration script is related to: diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/index.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/index.ts new file mode 100644 index 0000000000000..2cf0813583235 --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { migrations730 } from './migrations_730'; +export { migrations700 } from './migrations_700'; diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.test.ts similarity index 99% rename from src/plugins/dashboard/common/migrate_to_730_panels.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.test.ts index bdcd3bf8cedc0..4eacf9b93d85d 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.test.ts @@ -8,13 +8,14 @@ import { migratePanelsTo730 } from './migrate_to_730_panels'; import { + SavedDashboardPanel730ToLatest, + RawSavedDashboardPanel640To720, RawSavedDashboardPanelTo60, RawSavedDashboardPanel630, - RawSavedDashboardPanel640To720, RawSavedDashboardPanel610, RawSavedDashboardPanel620, -} from './bwc/types'; -import { SavedDashboardPanelTo60, SavedDashboardPanel730ToLatest } from './types'; + SavedDashboardPanelTo60, +} from './types'; test('6.0 migrates uiState, sort, scales, and gridData', async () => { const uiState = { diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.ts similarity index 98% rename from src/plugins/dashboard/common/migrate_to_730_panels.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.ts index f40240bd7247c..531a0715038d5 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrate_to_730_panels.ts @@ -6,25 +6,25 @@ * Side Public License, v 1. */ +import uuid from 'uuid'; +import semverSatisfies from 'semver/functions/satisfies'; + import { i18n } from '@kbn/i18n'; import type { SerializableRecord } from '@kbn/utility-types'; -import semverSatisfies from 'semver/functions/satisfies'; -import uuid from 'uuid'; + import { - GridData, - SavedDashboardPanelTo60, SavedDashboardPanel620, SavedDashboardPanel630, SavedDashboardPanel610, -} from '.'; -import { - RawSavedDashboardPanelTo60, + SavedDashboardPanelTo60, RawSavedDashboardPanel630, - RawSavedDashboardPanel640To720, - RawSavedDashboardPanel730ToLatest, RawSavedDashboardPanel610, RawSavedDashboardPanel620, -} from './bwc/types'; + RawSavedDashboardPanelTo60, + RawSavedDashboardPanel640To720, + RawSavedDashboardPanel730ToLatest, +} from './types'; +import { GridData } from '../../../../common'; const PANEL_HEIGHT_SCALE_FACTOR = 5; const PANEL_HEIGHT_SCALE_FACTOR_WITH_MARGINS = 4; @@ -266,7 +266,6 @@ export function migratePanelsTo730( | RawSavedDashboardPanel620 | RawSavedDashboardPanel630 | RawSavedDashboardPanel640To720 - // We run these on post processed panels too for url BWC | SavedDashboardPanelTo60 | SavedDashboardPanel610 | SavedDashboardPanel620 diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_700.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_700.ts new file mode 100644 index 0000000000000..d1954e8266d88 --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_700.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { get } from 'lodash'; + +import { SavedObjectMigrationFn } from '@kbn/core/server'; +import { DATA_VIEW_SAVED_OBJECT_TYPE } from '@kbn/data-views-plugin/common'; + +import { DashboardDoc700To720 } from './types'; + +function migrateIndexPattern(doc: DashboardDoc700To720) { + const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); + if (typeof searchSourceJSON !== 'string') { + return; + } + let searchSource; + try { + searchSource = JSON.parse(searchSourceJSON); + } catch (e) { + // Let it go, the data is invalid and we'll leave it as is + return; + } + if (searchSource.index) { + searchSource.indexRefName = 'kibanaSavedObjectMeta.searchSourceJSON.index'; + doc.references.push({ + name: searchSource.indexRefName, + type: DATA_VIEW_SAVED_OBJECT_TYPE, + id: searchSource.index, + }); + delete searchSource.index; + } + if (searchSource.filter) { + searchSource.filter.forEach((filterRow: any, i: number) => { + if (!filterRow.meta || !filterRow.meta.index) { + return; + } + filterRow.meta.indexRefName = `kibanaSavedObjectMeta.searchSourceJSON.filter[${i}].meta.index`; + doc.references.push({ + name: filterRow.meta.indexRefName, + type: DATA_VIEW_SAVED_OBJECT_TYPE, + id: filterRow.meta.index, + }); + delete filterRow.meta.index; + }); + } + doc.attributes.kibanaSavedObjectMeta.searchSourceJSON = JSON.stringify(searchSource); +} + +export const migrations700: SavedObjectMigrationFn = (doc): DashboardDoc700To720 => { + // Set new "references" attribute + doc.references = doc.references || []; + + // Migrate index pattern + migrateIndexPattern(doc as DashboardDoc700To720); + // Migrate panels + const panelsJSON = get(doc, 'attributes.panelsJSON'); + if (typeof panelsJSON !== 'string') { + return doc as DashboardDoc700To720; + } + let panels; + try { + panels = JSON.parse(panelsJSON); + } catch (e) { + // Let it go, the data is invalid and we'll leave it as is + return doc as DashboardDoc700To720; + } + if (!Array.isArray(panels)) { + return doc as DashboardDoc700To720; + } + panels.forEach((panel, i) => { + if (!panel.type || !panel.id) { + return; + } + panel.panelRefName = `panel_${i}`; + doc.references!.push({ + name: `panel_${i}`, + type: panel.type, + id: panel.id, + }); + delete panel.type; + delete panel.id; + }); + doc.attributes.panelsJSON = JSON.stringify(panels); + return doc as DashboardDoc700To720; +}; diff --git a/src/plugins/dashboard/server/saved_objects/migrations_730.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.test.ts similarity index 96% rename from src/plugins/dashboard/server/saved_objects/migrations_730.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.test.ts index 2fc999b067496..6314546b5933a 100644 --- a/src/plugins/dashboard/server/saved_objects/migrations_730.test.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.test.ts @@ -7,12 +7,17 @@ */ import { savedObjectsServiceMock } from '@kbn/core/server/mocks'; -import { createDashboardSavedObjectTypeMigrations } from './dashboard_migrations'; -import { migrations730 } from './migrations_730'; -import { DashboardDoc700To720, DashboardDoc730ToLatest, DashboardDocPre700 } from '../../common'; -import { RawSavedDashboardPanel730ToLatest } from '../../common'; import { createEmbeddableSetupMock } from '@kbn/embeddable-plugin/server/mocks'; +import { + DashboardDocPre700, + DashboardDoc700To720, + DashboardDoc730ToLatest, + RawSavedDashboardPanel730ToLatest, +} from './types'; +import { migrations730 } from './migrations_730'; +import { createDashboardSavedObjectTypeMigrations } from '../dashboard_saved_object_migrations'; + const mockContext = savedObjectsServiceMock.createMigrationContext(); const migrations = createDashboardSavedObjectTypeMigrations({ embeddable: createEmbeddableSetupMock(), diff --git a/src/plugins/dashboard/server/saved_objects/migrations_730.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts similarity index 69% rename from src/plugins/dashboard/server/saved_objects/migrations_730.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts index 3cc34d8513a45..dcd1c2f2cb878 100644 --- a/src/plugins/dashboard/server/saved_objects/migrations_730.ts +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/migrations_730.ts @@ -7,11 +7,38 @@ */ import { inspect } from 'util'; -import { SavedObjectMigrationContext } from '@kbn/core/server'; -import { DashboardDoc730ToLatest } from '../../common'; -import { isDashboardDoc } from './is_dashboard_doc'; +import { SavedObjectMigrationContext, SavedObjectUnsanitizedDoc } from '@kbn/core/server'; + import { moveFiltersToQuery } from './move_filters_to_query'; -import { migratePanelsTo730, DashboardDoc700To720 } from '../../common'; +import { migratePanelsTo730 } from './migrate_to_730_panels'; +import { DashboardDoc730ToLatest, DashboardDoc700To720 } from './types'; + +function isDoc( + doc: { [key: string]: unknown } | SavedObjectUnsanitizedDoc +): doc is SavedObjectUnsanitizedDoc { + return ( + typeof doc.id === 'string' && + typeof doc.type === 'string' && + doc.attributes !== null && + typeof doc.attributes === 'object' && + doc.references !== null && + typeof doc.references === 'object' + ); +} + +export function isDashboardDoc( + doc: { [key: string]: unknown } | DashboardDoc730ToLatest +): doc is DashboardDoc730ToLatest { + if (!isDoc(doc)) { + return false; + } + + if (typeof (doc as DashboardDoc730ToLatest).attributes.panelsJSON !== 'string') { + return false; + } + + return true; +} export const migrations730 = (doc: DashboardDoc700To720, { log }: SavedObjectMigrationContext) => { if (!isDashboardDoc(doc)) { diff --git a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.test.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/move_filters_to_query.test.ts similarity index 100% rename from src/plugins/dashboard/server/saved_objects/move_filters_to_query.test.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/move_filters_to_query.test.ts diff --git a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/move_filters_to_query.ts similarity index 100% rename from src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts rename to src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/move_filters_to_query.ts diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/readme.md b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/readme.md new file mode 100644 index 0000000000000..50f1b3283ca3f --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/readme.md @@ -0,0 +1,3 @@ +## Legacy Pre 7.3 Migrations + +This folder contains legacy migrations that migrate dashboard saved object from any previous version into Kibana 7.3.0. The migrations in this folder need to be able to handle state from any older version of dashboard from as early as 5.0 because Saved Object Migrations did not exist, and in-place migrations were used instead. After 7.3.0, saved object migrations are in place, so it can be assumed that any saved migration that is registered there will receive state from the version before. diff --git a/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/types.ts b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/types.ts new file mode 100644 index 0000000000000..2257b05c0a64e --- /dev/null +++ b/src/plugins/dashboard/server/saved_objects/migrations/migrate_to_730/types.ts @@ -0,0 +1,182 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { Serializable } from '@kbn/utility-types'; +import { SavedObjectReference } from '@kbn/core/server'; + +import type { + GridData, + DashboardAttributes as CurrentDashboardAttributes, // Dashboard attributes from common are the source of truth for the current version. +} from '../../../../common'; + +interface SavedObjectAttributes { + kibanaSavedObjectMeta: { + searchSourceJSON: string; + }; +} + +interface Doc { + references: SavedObjectReference[]; + attributes: Attributes; + id: string; + type: string; +} + +interface DocPre700 { + attributes: Attributes; + id: string; + type: string; +} + +interface DashboardAttributesTo720 extends SavedObjectAttributes { + panelsJSON: string; + description: string; + uiStateJSON?: string; + version: number; + timeRestore: boolean; + useMargins?: boolean; + title: string; + optionsJSON?: string; +} + +export type DashboardDoc730ToLatest = Doc; + +export type DashboardDoc700To720 = Doc; + +export type DashboardDocPre700 = DocPre700; + +// Note that these types are prefixed with `Raw` because there are some post processing steps +// that happen before the saved objects even reach the client. Namely, injecting type and id +// parameters back into the panels, where the raw saved objects actually have them stored elsewhere. +// +// Ideally, everywhere in the dashboard code would use references at the top level instead of +// embedded in the panels. The reason this is stored at the top level is so the references can be uniformly +// updated across all saved object types that have references. + +// Starting in 7.3 we introduced the possibility of embeddables existing without an id +// parameter. If there was no id, then type remains on the panel. So it either will have a name, +// or a type property. +export type RawSavedDashboardPanel730ToLatest = Pick< + RawSavedDashboardPanel640To720, + Exclude +> & { + // Should be either type, and not name (not backed by a saved object), or name but not type (backed by a + // saved object and type and id are stored on references). Had trouble with oring the two types + // because of optional properties being marked as required: https://github.com/microsoft/TypeScript/issues/20722 + readonly type?: string; + readonly name?: string; + + panelIndex: string; + panelRefName?: string; +}; + +// NOTE!! +// All of these types can actually exist in 7.2! The names are pretty confusing because we did +// in place migrations for so long. For example, `RawSavedDashboardPanelTo60` is what a panel +// created in 6.0 will look like after it's been migrated up to 7.2, *not* what it would look like in 6.0. +// That's why it actually doesn't have id or type, but has a name property, because that was a migration +// added in 7.0. + +// Hopefully since we finally have a formal saved object migration system and we can do less in place +// migrations, this will be easier to understand moving forward. + +// Starting in 6.4 we added an in-place edit on panels to remove columns and sort properties and put them +// inside the embeddable config (https://github.com/elastic/kibana/pull/17446). +// Note that this was not added as a saved object migration until 7.3, so there can still exist panels in +// this shape in v 7.2. +export type RawSavedDashboardPanel640To720 = Pick< + RawSavedDashboardPanel630, + Exclude +>; + +// In 6.3.0 we expanded the number of grid columns and rows: https://github.com/elastic/kibana/pull/16763 +// We added in-place migrations to multiply older x,y,h,w numbers. Note the typescript shape here is the same +// because it's just multiplying existing fields. +// Note that this was not added as a saved object migration until 7.3, so there can still exist panels in 7.2 +// that need to be modified. +export type RawSavedDashboardPanel630 = RawSavedDashboardPanel620; + +// In 6.2 we added an inplace migration, moving uiState into each panel's new embeddableConfig property. +// Source: https://github.com/elastic/kibana/pull/14949 +export type RawSavedDashboardPanel620 = RawSavedDashboardPanel610 & { + embeddableConfig: { [key: string]: Serializable }; + version: string; +}; + +// In 6.1 we switched from an angular grid to react grid layout (https://github.com/elastic/kibana/pull/13853) +// This used gridData instead of size_x, size_y, row and col. We also started tracking the version this panel +// was created in to make future migrations easier. +// Note that this was not added as a saved object migration until 7.3, so there can still exist panels in +// this shape in v 7.2. +export type RawSavedDashboardPanel610 = Pick< + RawSavedDashboardPanelTo60, + Exclude +> & { gridData: GridData; version: string }; + +export interface RawSavedDashboardPanelTo60 { + readonly columns?: string[]; + readonly sort?: string; + readonly size_x?: number; + readonly size_y?: number; + readonly row: number; + readonly col: number; + panelIndex?: number | string; // earlier versions allowed this to be number or string. Some very early versions seem to be missing this entirely + readonly name: string; + + // This is where custom panel titles are stored prior to Embeddable API v2 + title?: string; +} + +export type SavedDashboardPanel640To720 = Pick< + RawSavedDashboardPanel640To720, + Exclude +> & { + readonly id: string; + readonly type: string; +}; + +export type SavedDashboardPanel630 = Pick< + RawSavedDashboardPanel630, + Exclude +> & { + readonly id: string; + readonly type: string; +}; + +export type SavedDashboardPanel620 = Pick< + RawSavedDashboardPanel620, + Exclude +> & { + readonly id: string; + readonly type: string; +}; + +export type SavedDashboardPanel610 = Pick< + RawSavedDashboardPanel610, + Exclude +> & { + readonly id: string; + readonly type: string; +}; + +export type SavedDashboardPanelTo60 = Pick< + RawSavedDashboardPanelTo60, + Exclude +> & { + readonly id: string; + readonly type: string; +}; + +// id becomes optional starting in 7.3.0 +export type SavedDashboardPanel730ToLatest = Pick< + RawSavedDashboardPanel730ToLatest, + Exclude +> & { + readonly id?: string; + readonly type: string; +}; diff --git a/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts b/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts index ea981be3515f8..25a4986208d31 100644 --- a/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts +++ b/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedDashboardPanel730ToLatest } from '../../common'; +import { SavedDashboardPanel } from '../../common'; import { getEmptyDashboardData, collectPanelsByType } from './dashboard_telemetry'; import { EmbeddableStateWithType } from '@kbn/embeddable-plugin/common'; import { createEmbeddablePersistableStateServiceMock } from '@kbn/embeddable-plugin/common/mocks'; @@ -18,7 +18,7 @@ const visualizationType1ByValue = { }, }, type: 'visualization', -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const visualizationType2ByValue = { embeddableConfig: { @@ -27,7 +27,7 @@ const visualizationType2ByValue = { }, }, type: 'visualization', -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const visualizationType2ByReference = { ...visualizationType2ByValue, @@ -41,7 +41,7 @@ const lensTypeAByValue = { visualizationType: 'a', }, }, -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const lensTypeAByReference = { ...lensTypeAByValue, @@ -60,7 +60,7 @@ const lensXYSeriesA = { }, }, }, -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const lensXYSeriesB = { type: 'lens', @@ -90,7 +90,7 @@ const lensXYSeriesB = { }, }, }, -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const embeddablePersistableStateService = createEmbeddablePersistableStateServiceMock(); diff --git a/src/plugins/dashboard/server/usage/dashboard_telemetry.ts b/src/plugins/dashboard/server/usage/dashboard_telemetry.ts index ce41c50834689..1e8a0192ec38a 100644 --- a/src/plugins/dashboard/server/usage/dashboard_telemetry.ts +++ b/src/plugins/dashboard/server/usage/dashboard_telemetry.ts @@ -16,7 +16,7 @@ import { } from '@kbn/controls-plugin/common'; import { initializeControlGroupTelemetry } from '@kbn/controls-plugin/server'; import { TaskManagerStartContract } from '@kbn/task-manager-plugin/server'; -import { SavedDashboardPanel730ToLatest } from '../../common'; +import type { SavedDashboardPanel } from '../../common'; import { TASK_ID, DashboardTelemetryTaskState } from './dashboard_telemetry_collection_task'; export interface DashboardCollectorData { panels: { @@ -55,7 +55,7 @@ export const getEmptyPanelTypeData = () => ({ }); export const collectPanelsByType = ( - panels: SavedDashboardPanel730ToLatest[], + panels: SavedDashboardPanel[], collectorData: DashboardCollectorData, embeddableService: EmbeddablePersistableStateService ) => { diff --git a/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts b/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts index 823b5fadaaeae..1ca13b4308586 100644 --- a/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts +++ b/src/plugins/dashboard/server/usage/dashboard_telemetry_collection_task.ts @@ -14,17 +14,13 @@ import { TaskManagerStartContract, } from '@kbn/task-manager-plugin/server'; import { EmbeddableSetup } from '@kbn/embeddable-plugin/server'; -import { SavedDashboardPanel730ToLatest } from '../../common'; -import { - injectReferences, - SavedObjectAttributesAndReferences, -} from '../../common/saved_dashboard_references'; import { controlsCollectorFactory, collectPanelsByType, getEmptyDashboardData, DashboardCollectorData, } from './dashboard_telemetry'; +import { injectReferences, SavedDashboardPanel } from '../../common'; // This task is responsible for running daily and aggregating all the Dashboard telemerty data // into a single document. This is an effort to make sure the load of fetching/parsing all of the @@ -32,6 +28,11 @@ import { const TELEMETRY_TASK_TYPE = 'dashboard_telemetry'; export const TASK_ID = `Dashboard-${TELEMETRY_TASK_TYPE}`; +interface SavedObjectAttributesAndReferences { + attributes: SavedObjectAttributes; + references: SavedObjectReference[]; +} + export interface DashboardTelemetryTaskState { runs: number; telemetry: DashboardCollectorData; @@ -102,7 +103,7 @@ export function dashboardTaskRunner(logger: Logger, core: CoreSetup, embeddable: try { const panels = JSON.parse( attributes.panelsJSON as string - ) as unknown as SavedDashboardPanel730ToLatest[]; + ) as unknown as SavedDashboardPanel[]; collectPanelsByType(panels, dashboardData, embeddable); } catch (e) { diff --git a/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts b/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts index 8a3cdd71539f8..c5e8da8acbd4a 100644 --- a/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts +++ b/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedDashboardPanel730ToLatest } from '../../common'; +import type { SavedDashboardPanel } from '../../common'; import { findByValueEmbeddables } from './find_by_value_embeddables'; const visualizationByValue = { @@ -14,18 +14,18 @@ const visualizationByValue = { value: 'visualization-by-value', }, type: 'visualization', -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const mapByValue = { embeddableConfig: { value: 'map-by-value', }, type: 'map', -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; const embeddableByRef = { panelRefName: 'panel_ref_1', -} as unknown as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel; describe('findByValueEmbeddables', () => { it('finds the by value embeddables for the given type', async () => { diff --git a/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts b/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts index 694fe2007f844..502ba828944d4 100644 --- a/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts +++ b/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts @@ -7,7 +7,7 @@ */ import { ISavedObjectsRepository, SavedObjectAttributes } from '@kbn/core/server'; -import { SavedDashboardPanel730ToLatest } from '../../common'; +import type { SavedDashboardPanel } from '../../common'; export const findByValueEmbeddables = async ( savedObjectClient: Pick, @@ -22,7 +22,7 @@ export const findByValueEmbeddables = async ( try { return JSON.parse( dashboard.attributes.panelsJSON as string - ) as unknown as SavedDashboardPanel730ToLatest[]; + ) as unknown as SavedDashboardPanel[]; } catch (exception) { return []; } diff --git a/src/plugins/data/common/index.ts b/src/plugins/data/common/index.ts index f76b6b903fe95..38e4d802cd838 100644 --- a/src/plugins/data/common/index.ts +++ b/src/plugins/data/common/index.ts @@ -21,7 +21,8 @@ export { getTime, isQuery, isTimeRange, - queryStateToExpressionAst, + textBasedQueryStateToAstWithValidation, + textBasedQueryStateToExpressionAst, } from './query'; export type { QueryState } from './query'; export * from './search'; diff --git a/src/plugins/data/common/query/index.ts b/src/plugins/data/common/query/index.ts index dedc4b6a4d839..1aebdd09244e4 100644 --- a/src/plugins/data/common/query/index.ts +++ b/src/plugins/data/common/query/index.ts @@ -10,4 +10,5 @@ export * from './timefilter'; export * from './types'; export * from './is_query'; export * from './query_state'; -export { queryStateToExpressionAst } from './to_expression_ast'; +export { textBasedQueryStateToAstWithValidation } from './text_based_query_state_to_ast_with_validation'; +export { textBasedQueryStateToExpressionAst } from './text_based_query_state_to_ast'; diff --git a/src/plugins/data/common/query/to_expression_ast.test.ts b/src/plugins/data/common/query/text_based_query_state_to_ast.test.ts similarity index 65% rename from src/plugins/data/common/query/to_expression_ast.test.ts rename to src/plugins/data/common/query/text_based_query_state_to_ast.test.ts index d7c1424869aa8..64f9c5ca59111 100644 --- a/src/plugins/data/common/query/to_expression_ast.test.ts +++ b/src/plugins/data/common/query/text_based_query_state_to_ast.test.ts @@ -5,20 +5,17 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ -import { DataViewsContract } from '@kbn/data-views-plugin/common'; -import { queryStateToExpressionAst } from './to_expression_ast'; +import { textBasedQueryStateToExpressionAst } from './text_based_query_state_to_ast'; -describe('queryStateToExpressionAst', () => { +describe('textBasedQueryStateToExpressionAst', () => { it('returns an object with the correct structure', async () => { - const dataViewsService = {} as unknown as DataViewsContract; - const actual = await queryStateToExpressionAst({ + const actual = await textBasedQueryStateToExpressionAst({ filters: [], query: { language: 'lucene', query: '' }, time: { from: 'now', to: 'now+7d', }, - dataViewsService, }); expect(actual).toHaveProperty( @@ -33,31 +30,13 @@ describe('queryStateToExpressionAst', () => { }); it('returns an object with the correct structure for an SQL query', async () => { - const dataViewsService = { - getIdsWithTitle: jest.fn(() => { - return [ - { - title: 'foo', - id: 'bar', - }, - ]; - }), - get: jest.fn(() => { - return { - title: 'foo', - id: 'bar', - timeFieldName: 'baz', - }; - }), - } as unknown as DataViewsContract; - const actual = await queryStateToExpressionAst({ + const actual = await textBasedQueryStateToExpressionAst({ filters: [], query: { sql: 'SELECT * FROM foo' }, time: { from: 'now', to: 'now+7d', }, - dataViewsService, }); expect(actual).toHaveProperty( diff --git a/src/plugins/data/common/query/to_expression_ast.ts b/src/plugins/data/common/query/text_based_query_state_to_ast.ts similarity index 62% rename from src/plugins/data/common/query/to_expression_ast.ts rename to src/plugins/data/common/query/text_based_query_state_to_ast.ts index daf75ceb7a0c2..cb34d9c9c405c 100644 --- a/src/plugins/data/common/query/to_expression_ast.ts +++ b/src/plugins/data/common/query/text_based_query_state_to_ast.ts @@ -5,14 +5,8 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ -import { - isOfAggregateQueryType, - getAggregateQueryMode, - getIndexPatternFromSQLQuery, - Query, -} from '@kbn/es-query'; +import { isOfAggregateQueryType, getAggregateQueryMode, Query } from '@kbn/es-query'; import { buildExpression, buildExpressionFunction } from '@kbn/expressions-plugin/common'; -import type { DataViewsContract } from '@kbn/data-views-plugin/common'; import { ExpressionFunctionKibana, ExpressionFunctionKibanaContext, @@ -24,7 +18,7 @@ import { } from '..'; interface Args extends QueryState { - dataViewsService: DataViewsContract; + timeFieldName?: string; inputQuery?: Query; } @@ -34,12 +28,12 @@ interface Args extends QueryState { * @param query kibana query or aggregate query * @param time kibana time range */ -export async function queryStateToExpressionAst({ +export function textBasedQueryStateToExpressionAst({ filters, query, inputQuery, time, - dataViewsService, + timeFieldName, }: Args) { const kibana = buildExpressionFunction('kibana', {}); let q; @@ -52,24 +46,15 @@ export async function queryStateToExpressionAst({ filters: filters && filtersToAst(filters), }); const ast = buildExpression([kibana, kibanaContext]).toAst(); + if (query && isOfAggregateQueryType(query)) { const mode = getAggregateQueryMode(query); // sql query if (mode === 'sql' && 'sql' in query) { - const idxPattern = getIndexPatternFromSQLQuery(query.sql); - const idsTitles = await dataViewsService.getIdsWithTitle(); - const dataViewIdTitle = idsTitles.find(({ title }) => title === idxPattern); - - if (dataViewIdTitle) { - const dataView = await dataViewsService.get(dataViewIdTitle.id); - const timeFieldName = dataView.timeFieldName; - const essql = aggregateQueryToAst(query, timeFieldName); + const essql = aggregateQueryToAst(query, timeFieldName); - if (essql) { - ast.chain.push(essql); - } - } else { - throw new Error(`No data view found for index pattern ${idxPattern}`); + if (essql) { + ast.chain.push(essql); } } } diff --git a/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.test.ts b/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.test.ts new file mode 100644 index 0000000000000..d326f9cc70fa1 --- /dev/null +++ b/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.test.ts @@ -0,0 +1,102 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { DataViewsContract } from '@kbn/data-views-plugin/common'; +import { textBasedQueryStateToAstWithValidation } from './text_based_query_state_to_ast_with_validation'; + +describe('textBasedQueryStateToAstWithValidation', () => { + it('returns undefined for a non text based query', async () => { + const dataViewsService = {} as unknown as DataViewsContract; + const actual = await textBasedQueryStateToAstWithValidation({ + filters: [], + query: { language: 'lucene', query: '' }, + time: { + from: 'now', + to: 'now+7d', + }, + dataViewsService, + }); + + expect(actual).toBeUndefined(); + }); + + it('returns an object with the correct structure for an SQL query with existing dataview', async () => { + const dataViewsService = { + getIdsWithTitle: jest.fn(() => { + return [ + { + title: 'foo', + id: 'bar', + }, + ]; + }), + get: jest.fn(() => { + return { + title: 'foo', + id: 'bar', + timeFieldName: 'baz', + }; + }), + } as unknown as DataViewsContract; + const actual = await textBasedQueryStateToAstWithValidation({ + filters: [], + query: { sql: 'SELECT * FROM foo' }, + time: { + from: 'now', + to: 'now+7d', + }, + dataViewsService, + }); + + expect(actual).toHaveProperty( + 'chain.1.arguments.timeRange.0.chain.0.arguments', + expect.objectContaining({ + from: ['now'], + to: ['now+7d'], + }) + ); + + expect(actual).toHaveProperty( + 'chain.2.arguments', + expect.objectContaining({ + query: ['SELECT * FROM foo'], + }) + ); + }); + + it('returns an error for text based language with non existing dataview', async () => { + const dataViewsService = { + getIdsWithTitle: jest.fn(() => { + return [ + { + title: 'foo', + id: 'bar', + }, + ]; + }), + get: jest.fn(() => { + return { + title: 'foo', + id: 'bar', + timeFieldName: 'baz', + }; + }), + } as unknown as DataViewsContract; + + await expect( + textBasedQueryStateToAstWithValidation({ + filters: [], + query: { sql: 'SELECT * FROM another_dataview' }, + time: { + from: 'now', + to: 'now+7d', + }, + dataViewsService, + }) + ).rejects.toThrow('No data view found for index pattern another_dataview'); + }); +}); diff --git a/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.ts b/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.ts new file mode 100644 index 0000000000000..c065e8af8e914 --- /dev/null +++ b/src/plugins/data/common/query/text_based_query_state_to_ast_with_validation.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { + isOfAggregateQueryType, + getIndexPatternFromSQLQuery, + Query, + AggregateQuery, +} from '@kbn/es-query'; +import type { DataViewsContract } from '@kbn/data-views-plugin/common'; +import type { QueryState } from '..'; +import { textBasedQueryStateToExpressionAst } from './text_based_query_state_to_ast'; + +interface Args extends QueryState { + dataViewsService: DataViewsContract; + inputQuery?: Query; +} + +const getIndexPatternFromAggregateQuery = (query: AggregateQuery) => { + if ('sql' in query) { + return getIndexPatternFromSQLQuery(query.sql); + } +}; + +/** + * Converts QueryState to expression AST + * @param filters array of kibana filters + * @param query kibana query or aggregate query + * @param time kibana time range + */ +export async function textBasedQueryStateToAstWithValidation({ + filters, + query, + inputQuery, + time, + dataViewsService, +}: Args) { + let ast; + if (query && isOfAggregateQueryType(query)) { + // sql query + const idxPattern = getIndexPatternFromAggregateQuery(query); + const idsTitles = await dataViewsService.getIdsWithTitle(); + const dataViewIdTitle = idsTitles.find(({ title }) => title === idxPattern); + + if (dataViewIdTitle) { + const dataView = await dataViewsService.get(dataViewIdTitle.id); + const timeFieldName = dataView.timeFieldName; + + ast = textBasedQueryStateToExpressionAst({ + filters, + query, + inputQuery, + time, + timeFieldName, + }); + } else { + throw new Error(`No data view found for index pattern ${idxPattern}`); + } + } + return ast; +} diff --git a/src/plugins/data/common/search/aggs/buckets/index.ts b/src/plugins/data/common/search/aggs/buckets/index.ts index 9d7819157e189..000dcd5382b56 100644 --- a/src/plugins/data/common/search/aggs/buckets/index.ts +++ b/src/plugins/data/common/search/aggs/buckets/index.ts @@ -48,3 +48,4 @@ export * from './sampler_fn'; export * from './sampler'; export * from './diversified_sampler_fn'; export * from './diversified_sampler'; +export { SHARD_DELAY_AGG_NAME } from './shard_delay'; diff --git a/src/plugins/data/common/search/aggs/buckets/multi_terms.ts b/src/plugins/data/common/search/aggs/buckets/multi_terms.ts index 8dbde951ba183..a064f19390515 100644 --- a/src/plugins/data/common/search/aggs/buckets/multi_terms.ts +++ b/src/plugins/data/common/search/aggs/buckets/multi_terms.ts @@ -13,7 +13,7 @@ import { BucketAggType } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { createFilterMultiTerms } from './create_filter/multi_terms'; import { aggMultiTermsFnName } from './multi_terms_fn'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; import { MultiFieldKey } from './multi_field_key'; import { @@ -26,10 +26,9 @@ const termsTitle = i18n.translate('data.search.aggs.buckets.multiTermsTitle', { defaultMessage: 'Multi-Terms', }); -export interface AggParamsMultiTerms extends BaseAggParams { +interface CommonAggParamsMultiTerms extends BaseAggParams { fields: string[]; orderBy: string; - orderAgg?: AggConfigSerialized; order?: 'asc' | 'desc'; size?: number; shardSize?: number; @@ -38,6 +37,14 @@ export interface AggParamsMultiTerms extends BaseAggParams { separatorLabel?: string; } +export interface AggParamsMultiTermsSerialized extends CommonAggParamsMultiTerms { + orderAgg?: AggConfigSerialized; +} + +export interface AggParamsMultiTerms extends CommonAggParamsMultiTerms { + orderAgg?: IAggConfig; +} + export const getMultiTermsBucketAgg = () => { const keyCaches = new WeakMap(); return new BucketAggType({ diff --git a/src/plugins/data/common/search/aggs/buckets/terms.ts b/src/plugins/data/common/search/aggs/buckets/terms.ts index fdee9dfdb042f..8314d2cd532de 100644 --- a/src/plugins/data/common/search/aggs/buckets/terms.ts +++ b/src/plugins/data/common/search/aggs/buckets/terms.ts @@ -17,7 +17,7 @@ import { migrateIncludeExcludeFormat, } from './migrate_include_exclude_format'; import { aggTermsFnName } from './terms_fn'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; import { KBN_FIELD_TYPES } from '../../..'; @@ -33,11 +33,9 @@ const termsTitle = i18n.translate('data.search.aggs.buckets.termsTitle', { defaultMessage: 'Terms', }); -export interface AggParamsTerms extends BaseAggParams { +export interface CommonAggParamsTerms extends BaseAggParams { field: string; orderBy: string; - orderAgg?: AggConfigSerialized; - order?: 'asc' | 'desc'; size?: number; shardSize?: number; missingBucket?: boolean; @@ -45,12 +43,25 @@ export interface AggParamsTerms extends BaseAggParams { otherBucket?: boolean; otherBucketLabel?: string; // advanced - exclude?: string[] | number[]; - include?: string[] | number[]; + exclude?: string[] | string | number[]; + include?: string[] | string | number[]; includeIsRegex?: boolean; excludeIsRegex?: boolean; } +export interface AggParamsTermsSerialized extends CommonAggParamsTerms { + orderAgg?: AggConfigSerialized; + order?: 'asc' | 'desc'; +} + +export interface AggParamsTerms extends CommonAggParamsTerms { + orderAgg?: IAggConfig; + order?: { + value: 'asc' | 'desc'; + text: string; + }; +} + export const getTermsBucketAgg = () => new BucketAggType({ name: BUCKET_TYPES.TERMS, diff --git a/src/plugins/data/common/search/aggs/metrics/bucket_avg.ts b/src/plugins/data/common/search/aggs/metrics/bucket_avg.ts index c38d3fcfb0413..01ca65e43f131 100644 --- a/src/plugins/data/common/search/aggs/metrics/bucket_avg.ts +++ b/src/plugins/data/common/search/aggs/metrics/bucket_avg.ts @@ -13,13 +13,18 @@ import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsBucketAvg extends BaseAggParams { +export interface AggParamsBucketAvgSerialized extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } +export interface AggParamsBucketAvg extends BaseAggParams { + customMetric?: IAggConfig; + customBucket?: IAggConfig; +} + const overallAverageLabel = i18n.translate('data.search.aggs.metrics.overallAverageLabel', { defaultMessage: 'overall average', }); diff --git a/src/plugins/data/common/search/aggs/metrics/bucket_max.ts b/src/plugins/data/common/search/aggs/metrics/bucket_max.ts index 28b3990bd62c6..162109e49f424 100644 --- a/src/plugins/data/common/search/aggs/metrics/bucket_max.ts +++ b/src/plugins/data/common/search/aggs/metrics/bucket_max.ts @@ -12,13 +12,18 @@ import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsBucketMax extends BaseAggParams { +export interface AggParamsBucketMaxSerialized extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } +export interface AggParamsBucketMax extends BaseAggParams { + customMetric?: IAggConfig; + customBucket?: IAggConfig; +} + const overallMaxLabel = i18n.translate('data.search.aggs.metrics.overallMaxLabel', { defaultMessage: 'overall max', }); diff --git a/src/plugins/data/common/search/aggs/metrics/bucket_min.ts b/src/plugins/data/common/search/aggs/metrics/bucket_min.ts index 8fa5724dfddaf..8aa9d1d0d3799 100644 --- a/src/plugins/data/common/search/aggs/metrics/bucket_min.ts +++ b/src/plugins/data/common/search/aggs/metrics/bucket_min.ts @@ -12,13 +12,18 @@ import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsBucketMin extends BaseAggParams { +export interface AggParamsBucketMinSerialized extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } +export interface AggParamsBucketMin extends BaseAggParams { + customMetric?: IAggConfig; + customBucket?: IAggConfig; +} + const overallMinLabel = i18n.translate('data.search.aggs.metrics.overallMinLabel', { defaultMessage: 'overall min', }); diff --git a/src/plugins/data/common/search/aggs/metrics/bucket_sum.ts b/src/plugins/data/common/search/aggs/metrics/bucket_sum.ts index f249ef1ce0861..0ff737841b358 100644 --- a/src/plugins/data/common/search/aggs/metrics/bucket_sum.ts +++ b/src/plugins/data/common/search/aggs/metrics/bucket_sum.ts @@ -12,13 +12,18 @@ import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsBucketSum extends BaseAggParams { +export interface AggParamsBucketSumSerialized extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } +export interface AggParamsBucketSum extends BaseAggParams { + customMetric?: IAggConfig; + customBucket?: IAggConfig; +} + const overallSumLabel = i18n.translate('data.search.aggs.metrics.overallSumLabel', { defaultMessage: 'overall sum', }); diff --git a/src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts b/src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts index 496380dff4d1b..f74ac5663581a 100644 --- a/src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts +++ b/src/plugins/data/common/search/aggs/metrics/cumulative_sum.ts @@ -12,14 +12,21 @@ import { MetricAggType } from './metric_agg_type'; import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsCumulativeSum extends BaseAggParams { +export interface CommonAggParamsCumulativeSum extends BaseAggParams { buckets_path?: string; - customMetric?: AggConfigSerialized; metricAgg?: string; } +export interface AggParamsCumulativeSumSerialized extends CommonAggParamsCumulativeSum { + customMetric?: AggConfigSerialized; +} + +export interface AggParamsCumulativeSum extends CommonAggParamsCumulativeSum { + customMetric?: IAggConfig; +} + const cumulativeSumLabel = i18n.translate('data.search.aggs.metrics.cumulativeSumLabel', { defaultMessage: 'cumulative sum', }); diff --git a/src/plugins/data/common/search/aggs/metrics/derivative.ts b/src/plugins/data/common/search/aggs/metrics/derivative.ts index 2c6f3bd048bb9..e245b12a7d723 100644 --- a/src/plugins/data/common/search/aggs/metrics/derivative.ts +++ b/src/plugins/data/common/search/aggs/metrics/derivative.ts @@ -12,14 +12,21 @@ import { MetricAggType } from './metric_agg_type'; import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsDerivative extends BaseAggParams { +export interface CommonAggParamsDerivative extends BaseAggParams { buckets_path?: string; - customMetric?: AggConfigSerialized; metricAgg?: string; } +export interface AggParamsDerivativeSerialized extends CommonAggParamsDerivative { + customMetric?: AggConfigSerialized; +} + +export interface AggParamsDerivative extends CommonAggParamsDerivative { + customMetric?: IAggConfig; +} + const derivativeLabel = i18n.translate('data.search.aggs.metrics.derivativeLabel', { defaultMessage: 'derivative', }); diff --git a/src/plugins/data/common/search/aggs/metrics/filtered_metric.ts b/src/plugins/data/common/search/aggs/metrics/filtered_metric.ts index 22ae42b9130a5..abf882dd0466a 100644 --- a/src/plugins/data/common/search/aggs/metrics/filtered_metric.ts +++ b/src/plugins/data/common/search/aggs/metrics/filtered_metric.ts @@ -13,14 +13,19 @@ import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; import { aggFilteredMetricFnName } from './filtered_metric_fn'; -export interface AggParamsFilteredMetric extends BaseAggParams { +export interface AggParamsFilteredMetricSerialized extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } +export interface AggParamsFilteredMetric extends BaseAggParams { + customMetric?: IAggConfig; + customBucket?: IAggConfig; +} + const filteredMetricLabel = i18n.translate('data.search.aggs.metrics.filteredMetricLabel', { defaultMessage: 'filtered', }); diff --git a/src/plugins/data/common/search/aggs/metrics/moving_avg.ts b/src/plugins/data/common/search/aggs/metrics/moving_avg.ts index 29eb2d0ba75d3..942f813cbeac8 100644 --- a/src/plugins/data/common/search/aggs/metrics/moving_avg.ts +++ b/src/plugins/data/common/search/aggs/metrics/moving_avg.ts @@ -12,16 +12,23 @@ import { aggMovingAvgFnName } from './moving_avg_fn'; import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsMovingAvg extends BaseAggParams { +export interface CommonAggParamsMovingAvg extends BaseAggParams { buckets_path?: string; window?: number; script?: string; - customMetric?: AggConfigSerialized; metricAgg?: string; } +export interface AggParamsMovingAvgSerialized extends CommonAggParamsMovingAvg { + customMetric?: AggConfigSerialized; +} + +export interface AggParamsMovingAvg extends CommonAggParamsMovingAvg { + customMetric?: IAggConfig; +} + const movingAvgTitle = i18n.translate('data.search.aggs.metrics.movingAvgTitle', { defaultMessage: 'Moving Avg', }); diff --git a/src/plugins/data/common/search/aggs/metrics/serial_diff.ts b/src/plugins/data/common/search/aggs/metrics/serial_diff.ts index e3e62f56326e6..e40680adff930 100644 --- a/src/plugins/data/common/search/aggs/metrics/serial_diff.ts +++ b/src/plugins/data/common/search/aggs/metrics/serial_diff.ts @@ -12,14 +12,21 @@ import { aggSerialDiffFnName } from './serial_diff_fn'; import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; -import { AggConfigSerialized, BaseAggParams } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfig } from '../types'; -export interface AggParamsSerialDiff extends BaseAggParams { +export interface CommonAggParamsSerialDiff extends BaseAggParams { buckets_path?: string; - customMetric?: AggConfigSerialized; metricAgg?: string; } +export interface AggParamsSerialDiffSerialized extends CommonAggParamsSerialDiff { + customMetric?: AggConfigSerialized; +} + +export interface AggParamsSerialDiff extends CommonAggParamsSerialDiff { + customMetric?: IAggConfig; +} + const serialDiffTitle = i18n.translate('data.search.aggs.metrics.serialDiffTitle', { defaultMessage: 'Serial Diff', }); diff --git a/src/plugins/data/common/search/aggs/metrics/top_hit.ts b/src/plugins/data/common/search/aggs/metrics/top_hit.ts index fee74bade2aa1..367e16c15a2f1 100644 --- a/src/plugins/data/common/search/aggs/metrics/top_hit.ts +++ b/src/plugins/data/common/search/aggs/metrics/top_hit.ts @@ -8,18 +8,30 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; +import { DataViewField } from '@kbn/data-views-plugin/common'; import { aggTopHitFnName } from './top_hit_fn'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { flattenHit, KBN_FIELD_TYPES } from '../../..'; import { BaseAggParams } from '../types'; -export interface AggParamsTopHit extends BaseAggParams { +export interface BaseAggParamsTopHit extends BaseAggParams { field: string; aggregate: 'min' | 'max' | 'sum' | 'average' | 'concat'; - sortField?: string; size?: number; +} + +export interface AggParamsTopHitSerialized extends BaseAggParamsTopHit { sortOrder?: 'desc' | 'asc'; + sortField?: string; +} + +export interface AggParamsTopHit extends BaseAggParamsTopHit { + sortOrder?: { + value: 'desc' | 'asc'; + text: string; + }; + sortField?: DataViewField; } const isNumericFieldSelected = (agg: IMetricAggConfig) => { diff --git a/src/plugins/data/common/search/aggs/metrics/top_metrics.ts b/src/plugins/data/common/search/aggs/metrics/top_metrics.ts index df90186bbd746..354e0c6207d50 100644 --- a/src/plugins/data/common/search/aggs/metrics/top_metrics.ts +++ b/src/plugins/data/common/search/aggs/metrics/top_metrics.ts @@ -12,16 +12,27 @@ import { i18n } from '@kbn/i18n'; import { aggTopMetricsFnName } from './top_metrics_fn'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; -import { KBN_FIELD_TYPES } from '../../..'; +import { DataViewField, KBN_FIELD_TYPES } from '../../..'; import { BaseAggParams } from '../types'; -export interface AggParamsTopMetrics extends BaseAggParams { +export interface BaseAggParamsTopMetrics extends BaseAggParams { field: string; - sortField?: string; - sortOrder?: 'desc' | 'asc'; size?: number; } +export interface AggParamsTopMetricsSerialized extends BaseAggParamsTopMetrics { + sortOrder?: 'desc' | 'asc'; + sortField?: string; +} + +export interface AggParamsTopMetrics extends BaseAggParamsTopMetrics { + sortOrder?: { + value: 'desc' | 'asc'; + text: string; + }; + sortField?: DataViewField; +} + export const getTopMetricsMetricAgg = () => { return new MetricAggType({ name: METRIC_TYPES.TOP_METRICS, diff --git a/src/plugins/data/common/search/aggs/types.ts b/src/plugins/data/common/search/aggs/types.ts index 16fac531fad94..bc35e46d8da7a 100644 --- a/src/plugins/data/common/search/aggs/types.ts +++ b/src/plugins/data/common/search/aggs/types.ts @@ -37,13 +37,18 @@ import { aggMovingAvg, AggParamsAvg, AggParamsBucketAvg, + AggParamsBucketAvgSerialized, AggParamsBucketMax, + AggParamsBucketMaxSerialized, AggParamsBucketMin, + AggParamsBucketMinSerialized, AggParamsBucketSum, + AggParamsBucketSumSerialized, AggParamsFilteredMetric, AggParamsCardinality, AggParamsValueCount, AggParamsCumulativeSum, + AggParamsCumulativeSumSerialized, AggParamsDateHistogram, AggParamsDateRange, AggParamsDerivative, @@ -69,9 +74,13 @@ import { AggParamsStdDeviation, AggParamsSum, AggParamsTerms, + AggParamsTermsSerialized, AggParamsMultiTerms, + AggParamsMultiTermsSerialized, AggParamsRareTerms, AggParamsTopHit, + AggParamsTopMetrics, + AggParamsTopMetricsSerialized, aggPercentileRanks, aggPercentiles, aggRange, @@ -94,13 +103,17 @@ import { aggSinglePercentile, aggSinglePercentileRank, AggConfigsOptions, + AggParamsCount, + AggParamsDerivativeSerialized, + AggParamsFilteredMetricSerialized, + AggParamsMovingAvgSerialized, + AggParamsSerialDiffSerialized, + AggParamsTopHitSerialized, } from '.'; import { AggParamsSampler } from './buckets/sampler'; import { AggParamsDiversifiedSampler } from './buckets/diversified_sampler'; import { AggParamsSignificantText } from './buckets/significant_text'; -import { AggParamsTopMetrics } from './metrics/top_metrics'; import { aggTopMetrics } from './metrics/top_metrics_fn'; -import { AggParamsCount } from './metrics'; export type { IAggConfig, AggConfigSerialized } from './agg_config'; export type { CreateAggConfigParams, IAggConfigs, AggConfigsOptions } from './agg_configs'; @@ -146,8 +159,8 @@ export interface AggExpressionType { } /** @internal */ -export type AggExpressionFunctionArgs = - AggParamsMapping[Name] & Pick; +export type AggExpressionFunctionArgs = + SerializedAggParamsMapping[Name] & Pick; /** * A global list of the param interfaces for each agg type. @@ -156,6 +169,51 @@ export type AggExpressionFunctionArgs = * * @internal */ +interface SerializedAggParamsMapping { + [BUCKET_TYPES.RANGE]: AggParamsRange; + [BUCKET_TYPES.IP_RANGE]: AggParamsIpRange; + [BUCKET_TYPES.DATE_RANGE]: AggParamsDateRange; + [BUCKET_TYPES.FILTER]: AggParamsFilter; + [BUCKET_TYPES.FILTERS]: AggParamsFilters; + [BUCKET_TYPES.SIGNIFICANT_TERMS]: AggParamsSignificantTerms; + [BUCKET_TYPES.SIGNIFICANT_TEXT]: AggParamsSignificantText; + [BUCKET_TYPES.GEOTILE_GRID]: AggParamsGeoTile; + [BUCKET_TYPES.GEOHASH_GRID]: AggParamsGeoHash; + [BUCKET_TYPES.HISTOGRAM]: AggParamsHistogram; + [BUCKET_TYPES.DATE_HISTOGRAM]: AggParamsDateHistogram; + [BUCKET_TYPES.TERMS]: AggParamsTermsSerialized; + [BUCKET_TYPES.MULTI_TERMS]: AggParamsMultiTermsSerialized; + [BUCKET_TYPES.RARE_TERMS]: AggParamsRareTerms; + [BUCKET_TYPES.SAMPLER]: AggParamsSampler; + [BUCKET_TYPES.DIVERSIFIED_SAMPLER]: AggParamsDiversifiedSampler; + [METRIC_TYPES.AVG]: AggParamsAvg; + [METRIC_TYPES.CARDINALITY]: AggParamsCardinality; + [METRIC_TYPES.COUNT]: AggParamsCount; + [METRIC_TYPES.VALUE_COUNT]: AggParamsValueCount; + [METRIC_TYPES.GEO_BOUNDS]: AggParamsGeoBounds; + [METRIC_TYPES.GEO_CENTROID]: AggParamsGeoCentroid; + [METRIC_TYPES.MAX]: AggParamsMax; + [METRIC_TYPES.MEDIAN]: AggParamsMedian; + [METRIC_TYPES.SINGLE_PERCENTILE]: AggParamsSinglePercentile; + [METRIC_TYPES.SINGLE_PERCENTILE_RANK]: AggParamsSinglePercentileRank; + [METRIC_TYPES.MIN]: AggParamsMin; + [METRIC_TYPES.STD_DEV]: AggParamsStdDeviation; + [METRIC_TYPES.SUM]: AggParamsSum; + [METRIC_TYPES.AVG_BUCKET]: AggParamsBucketAvgSerialized; + [METRIC_TYPES.MAX_BUCKET]: AggParamsBucketMaxSerialized; + [METRIC_TYPES.MIN_BUCKET]: AggParamsBucketMinSerialized; + [METRIC_TYPES.SUM_BUCKET]: AggParamsBucketSumSerialized; + [METRIC_TYPES.FILTERED_METRIC]: AggParamsFilteredMetricSerialized; + [METRIC_TYPES.CUMULATIVE_SUM]: AggParamsCumulativeSumSerialized; + [METRIC_TYPES.DERIVATIVE]: AggParamsDerivativeSerialized; + [METRIC_TYPES.MOVING_FN]: AggParamsMovingAvgSerialized; + [METRIC_TYPES.PERCENTILE_RANKS]: AggParamsPercentileRanks; + [METRIC_TYPES.PERCENTILES]: AggParamsPercentiles; + [METRIC_TYPES.SERIAL_DIFF]: AggParamsSerialDiffSerialized; + [METRIC_TYPES.TOP_HITS]: AggParamsTopHitSerialized; + [METRIC_TYPES.TOP_METRICS]: AggParamsTopMetricsSerialized; +} + export interface AggParamsMapping { [BUCKET_TYPES.RANGE]: AggParamsRange; [BUCKET_TYPES.IP_RANGE]: AggParamsIpRange; @@ -200,7 +258,6 @@ export interface AggParamsMapping { [METRIC_TYPES.TOP_HITS]: AggParamsTopHit; [METRIC_TYPES.TOP_METRICS]: AggParamsTopMetrics; } - /** * A global list of the expression function definitions for each agg type function. */ diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index c8eefbdd92c6e..fa545d7648df1 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -139,6 +139,8 @@ export type { ParsedInterval, // expressions ExecutionContextSearch, + ExpressionFunctionKql, + ExpressionFunctionLucene, ExpressionFunctionKibana, ExpressionFunctionKibanaContext, ExpressionValueSearchContext, diff --git a/src/plugins/data_views/server/rest_api_routes/update_data_view.ts b/src/plugins/data_views/server/rest_api_routes/update_data_view.ts index 22598a8251096..1ac504ac652b8 100644 --- a/src/plugins/data_views/server/rest_api_routes/update_data_view.ts +++ b/src/plugins/data_views/server/rest_api_routes/update_data_view.ts @@ -9,7 +9,7 @@ import { schema } from '@kbn/config-schema'; import { UsageCounter } from '@kbn/usage-collection-plugin/server'; import { IRouter, StartServicesAccessor } from '@kbn/core/server'; -import { DataViewsService } from '../../common/data_views'; +import { DataViewsService, DataView } from '../../common/data_views'; import { DataViewSpec } from '../../common/types'; import { handleErrors } from './util/handle_errors'; import { fieldSpecSchema, runtimeFieldSchema, serializedFieldFormatSchema } from './util/schemas'; @@ -37,6 +37,7 @@ const indexPatternUpdateSchema = schema.object({ fields: schema.maybe(schema.recordOf(schema.string(), fieldSpecSchema)), allowNoIndex: schema.maybe(schema.boolean()), runtimeFieldMap: schema.maybe(schema.recordOf(schema.string(), runtimeFieldSchema)), + name: schema.maybe(schema.string()), }); interface UpdateDataViewArgs { @@ -67,43 +68,49 @@ export const updateDataView = async ({ typeMeta, fields, runtimeFieldMap, + name, } = spec; - let changeCount = 0; + let isChanged = false; let doRefreshFields = false; if (title !== undefined && title !== dataView.title) { - changeCount++; + isChanged = true; dataView.title = title; } if (timeFieldName !== undefined && timeFieldName !== dataView.timeFieldName) { - changeCount++; + isChanged = true; dataView.timeFieldName = timeFieldName; } if (sourceFilters !== undefined) { - changeCount++; + isChanged = true; dataView.sourceFilters = sourceFilters; } if (fieldFormats !== undefined) { - changeCount++; + isChanged = true; dataView.fieldFormatMap = fieldFormats; } if (type !== undefined) { - changeCount++; + isChanged = true; dataView.type = type; } if (typeMeta !== undefined) { - changeCount++; + isChanged = true; dataView.typeMeta = typeMeta; } + if (name !== undefined) { + isChanged = true; + dataView.name = name; + } + if (fields !== undefined) { - changeCount++; + isChanged = true; doRefreshFields = true; dataView.fields.replaceAll( Object.values(fields || {}).map((field) => ({ @@ -115,19 +122,19 @@ export const updateDataView = async ({ } if (runtimeFieldMap !== undefined) { - changeCount++; + isChanged = true; dataView.replaceAllRuntimeFields(runtimeFieldMap); } - if (changeCount < 1) { - throw new Error('Index pattern change set is empty.'); - } + if (isChanged) { + const result = (await dataViewsService.updateSavedObject(dataView)) as DataView; - await dataViewsService.updateSavedObject(dataView); - - if (doRefreshFields && refreshFields) { - await dataViewsService.refreshFields(dataView); + if (doRefreshFields && refreshFields) { + await dataViewsService.refreshFields(dataView); + } + return result; } + return dataView; }; diff --git a/src/plugins/discover/public/application/main/hooks/use_discover_state.ts b/src/plugins/discover/public/application/main/hooks/use_discover_state.ts index 8ad0d7ff7b590..1c530f475f0b1 100644 --- a/src/plugins/discover/public/application/main/hooks/use_discover_state.ts +++ b/src/plugins/discover/public/application/main/hooks/use_discover_state.ts @@ -16,7 +16,7 @@ import { useUrlTracking } from './use_url_tracking'; import { getState } from '../services/discover_state'; import { getStateDefaults } from '../utils/get_state_defaults'; import { DiscoverServices } from '../../../build_services'; -import { loadDataView } from '../utils/resolve_data_view'; +import { loadDataView, resolveDataView } from '../utils/resolve_data_view'; import { useSavedSearch as useSavedSearchData } from './use_saved_search'; import { MODIFY_COLUMNS_ON_SWITCH, @@ -67,7 +67,7 @@ export function useDiscoverState({ [history, savedSearch, services] ); - const { appStateContainer } = stateContainer; + const { appStateContainer, replaceUrlAppState } = stateContainer; const [state, setState] = useState(appStateContainer.getState()); @@ -190,13 +190,25 @@ export function useDiscoverState({ * That's because appState is updated before savedSearchData$ * The following line of code catches this, but should be improved */ - const nextDataView = await loadDataView( + const nextDataViewData = await loadDataView( services.dataViews, services.uiSettings, nextState.index ); - savedSearch.searchSource.setField('index', nextDataView.loaded); + const nextDataView = resolveDataView( + nextDataViewData, + savedSearch.searchSource, + services.toastNotifications + ); + + // If the requested data view is not found, don't try to load it, + // and instead reset the app state to the fallback data view + if (!nextDataViewData.stateValFound) { + replaceUrlAppState({ index: nextDataView.id }); + return; + } + savedSearch.searchSource.setField('index', nextDataView); reset(); } @@ -206,7 +218,16 @@ export function useDiscoverState({ setState(nextState); }); return () => unsubscribe(); - }, [services, appStateContainer, state, refetch$, data$, reset, savedSearch.searchSource]); + }, [ + services, + appStateContainer, + state, + refetch$, + data$, + reset, + savedSearch.searchSource, + replaceUrlAppState, + ]); /** * function to revert any changes to a given saved search diff --git a/src/plugins/discover/public/application/main/utils/fetch_sql.ts b/src/plugins/discover/public/application/main/utils/fetch_sql.ts index 2faa821bc66ec..057ddc5886da5 100644 --- a/src/plugins/discover/public/application/main/utils/fetch_sql.ts +++ b/src/plugins/discover/public/application/main/utils/fetch_sql.ts @@ -12,7 +12,7 @@ import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { ExpressionsStart } from '@kbn/expressions-plugin/public'; import type { Datatable } from '@kbn/expressions-plugin/public'; import type { DataViewsContract } from '@kbn/data-views-plugin/common'; -import { queryStateToExpressionAst } from '@kbn/data-plugin/common'; +import { textBasedQueryStateToAstWithValidation } from '@kbn/data-plugin/common'; import { DataTableRecord } from '../../../types'; interface SQLErrorResponse { @@ -31,7 +31,7 @@ export function fetchSql( inputQuery?: Query ) { const timeRange = data.query.timefilter.timefilter.getTime(); - return queryStateToExpressionAst({ + return textBasedQueryStateToAstWithValidation({ filters, query, time: timeRange, diff --git a/src/plugins/discover/public/application/main/utils/resolve_data_view.ts b/src/plugins/discover/public/application/main/utils/resolve_data_view.ts index 7baede8101851..094e1ec837e3c 100644 --- a/src/plugins/discover/public/application/main/utils/resolve_data_view.ts +++ b/src/plugins/discover/public/application/main/utils/resolve_data_view.ts @@ -166,6 +166,7 @@ export function resolveDataView( ownDataViewId: ownDataView.id, }, }), + 'data-test-subj': 'dscDataViewNotFoundShowSavedWarning', }); return ownDataView; } @@ -180,6 +181,7 @@ export function resolveDataView( loadedDataViewId: loadedDataView.id, }, }), + 'data-test-subj': 'dscDataViewNotFoundShowDefaultWarning', }); } diff --git a/src/plugins/discover/server/ui_settings.ts b/src/plugins/discover/server/ui_settings.ts index 3f7ddf34331ca..3c0fe05348324 100644 --- a/src/plugins/discover/server/ui_settings.ts +++ b/src/plugins/discover/server/ui_settings.ts @@ -329,7 +329,7 @@ export const getUiSettings: (docLinks: DocLinksServiceSetup) => Record` + diff --git a/src/plugins/expressions/common/execution/execution.test.ts b/src/plugins/expressions/common/execution/execution.test.ts index 75a95035bb89f..a5e03084a6977 100644 --- a/src/plugins/expressions/common/execution/execution.test.ts +++ b/src/plugins/expressions/common/execution/execution.test.ts @@ -488,6 +488,63 @@ describe('Execution', () => { expect(spy.fn).toHaveBeenCalledTimes(0); }); + + test('continues execution when error state is gone', async () => { + testScheduler.run(({ cold, expectObservable, flush }) => { + const a = 1; + const b = 2; + const c = 3; + const observable$ = cold('abc|', { a, b, c }); + const flakyFn = jest + .fn() + .mockImplementationOnce((value) => value) + .mockImplementationOnce(() => { + throw new Error('Some error.'); + }) + .mockImplementationOnce((value) => value); + const spyFn = jest.fn((value) => value); + + const executor = createUnitTestExecutor(); + executor.registerFunction({ + name: 'observable', + args: {}, + help: '', + fn: () => observable$, + }); + executor.registerFunction({ + name: 'flaky', + args: {}, + help: '', + fn: (value) => flakyFn(value), + }); + executor.registerFunction({ + name: 'spy', + args: {}, + help: '', + fn: (value) => spyFn(value), + }); + + const result = executor.run('observable | flaky | spy', null, {}); + + expectObservable(result).toBe('abc|', { + a: { partial: true, result: a }, + b: { + partial: true, + result: { + type: 'error', + error: expect.objectContaining({ message: '[flaky] > Some error.' }), + }, + }, + c: { partial: false, result: c }, + }); + + flush(); + + expect(spyFn).toHaveBeenCalledTimes(2); + expect(spyFn).toHaveBeenNthCalledWith(1, a); + expect(spyFn).toHaveBeenNthCalledWith(2, c); + }); + }); }); describe('state', () => { diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index b4ef83389ce28..68cebaa65569b 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -295,87 +295,86 @@ export class Execution< } invokeChain( - chainArr: ExpressionAstFunction[], + [head, ...tail]: ExpressionAstFunction[], input: unknown - ): Observable { + ): Observable { + if (!head) { + return of(input as ChainOutput); + } + return of(input).pipe( - ...(chainArr.map((link) => - switchMap((currentInput) => { - const { function: fnName, arguments: fnArgs } = link; - const fn = getByAlias( - this.state.get().functions, - fnName, - this.execution.params.namespace - ); + switchMap((currentInput) => { + const { function: fnName, arguments: fnArgs } = head; + const fn = getByAlias(this.state.get().functions, fnName, this.execution.params.namespace); + + if (!fn) { + throw createError({ + name: 'fn not found', + message: i18n.translate('expressions.execution.functionNotFound', { + defaultMessage: `Function {fnName} could not be found.`, + values: { + fnName, + }, + }), + }); + } - if (!fn) { - throw createError({ - name: 'fn not found', - message: i18n.translate('expressions.execution.functionNotFound', { - defaultMessage: `Function {fnName} could not be found.`, - values: { - fnName, - }, - }), - }); - } + if (fn.disabled) { + throw createError({ + name: 'fn is disabled', + message: i18n.translate('expressions.execution.functionDisabled', { + defaultMessage: `Function {fnName} is disabled.`, + values: { + fnName, + }, + }), + }); + } - if (fn.disabled) { - throw createError({ - name: 'fn is disabled', - message: i18n.translate('expressions.execution.functionDisabled', { - defaultMessage: `Function {fnName} is disabled.`, - values: { - fnName, - }, - }), - }); - } + if (fn.deprecated) { + this.logger?.warn(`Function '${fnName}' is deprecated`); + } - if (fn.deprecated) { - this.logger?.warn(`Function '${fnName}' is deprecated`); - } + if (this.execution.params.debug) { + head.debug = { + args: {}, + duration: 0, + fn: fn.name, + input: currentInput, + success: true, + }; + } - if (this.execution.params.debug) { - link.debug = { - args: {}, - duration: 0, - fn: fn.name, - input: currentInput, - success: true, - }; - } + const timeStart = this.execution.params.debug ? now() : 0; + + // `resolveArgs` returns an object because the arguments themselves might + // actually have `then` or `subscribe` methods which would be treated as a `Promise` + // or an `Observable` accordingly. + return this.resolveArgs(fn, currentInput, fnArgs).pipe( + tap((args) => this.execution.params.debug && Object.assign(head.debug, { args })), + switchMap((args) => this.invokeFunction(fn, currentInput, args)), + switchMap((output) => (getType(output) === 'error' ? throwError(output) : of(output))), + tap((output) => this.execution.params.debug && Object.assign(head.debug, { output })), + switchMap((output) => this.invokeChain(tail, output)), + catchError((rawError) => { + const error = createError(rawError); + error.error.message = `[${fnName}] > ${error.error.message}`; + + if (this.execution.params.debug) { + Object.assign(head.debug, { error, rawError, success: false }); + } - const timeStart = this.execution.params.debug ? now() : 0; - - // `resolveArgs` returns an object because the arguments themselves might - // actually have `then` or `subscribe` methods which would be treated as a `Promise` - // or an `Observable` accordingly. - return this.resolveArgs(fn, currentInput, fnArgs).pipe( - tap((args) => this.execution.params.debug && Object.assign(link.debug, { args })), - switchMap((args) => this.invokeFunction(fn, currentInput, args)), - switchMap((output) => (getType(output) === 'error' ? throwError(output) : of(output))), - tap((output) => this.execution.params.debug && Object.assign(link.debug, { output })), - catchError((rawError) => { - const error = createError(rawError); - error.error.message = `[${fnName}] > ${error.error.message}`; - - if (this.execution.params.debug) { - Object.assign(link.debug, { error, rawError, success: false }); - } - - return throwError(error); - }), - finalize(() => { - if (this.execution.params.debug) { - Object.assign(link.debug, { duration: now() - timeStart }); - } - }) - ); - }) - ) as Parameters['pipe']>), + return of(error); + }), + finalize(() => { + if (this.execution.params.debug) { + Object.assign(head.debug, { duration: now() - timeStart }); + } + }) + ); + }), catchError((error) => of(error)) - ) as Observable; + ); } invokeFunction( diff --git a/src/plugins/guided_onboarding/public/constants/search.ts b/src/plugins/guided_onboarding/public/constants/search.ts index b4c3c151aca0c..1f2a26b5f0b93 100644 --- a/src/plugins/guided_onboarding/public/constants/search.ts +++ b/src/plugins/guided_onboarding/public/constants/search.ts @@ -39,7 +39,7 @@ export const searchConfig: GuideConfig = { ], location: { appID: 'guidedOnboardingExample', - path: 'stepTwo?showTour=true', + path: 'stepTwo', }, }, { diff --git a/src/plugins/unified_search/public/dataview_picker/change_dataview.test.tsx b/src/plugins/unified_search/public/dataview_picker/change_dataview.test.tsx index 376cbf267a738..8497b599650b2 100644 --- a/src/plugins/unified_search/public/dataview_picker/change_dataview.test.tsx +++ b/src/plugins/unified_search/public/dataview_picker/change_dataview.test.tsx @@ -105,7 +105,7 @@ describe('DataView component', () => { expect(addFieldSpy).toHaveBeenCalled(); }); - it('should not render the add datavuew menu if onDataViewCreated is not given', async () => { + it('should not render the add dataview menu if onDataViewCreated is not given', async () => { await act(async () => { const component = mount(wrapDataViewComponentInContext(props, true)); findTestSubject(component, 'dataview-trigger').simulate('click'); @@ -113,7 +113,7 @@ describe('DataView component', () => { }); }); - it('should render the add datavuew menu if onDataViewCreated is given', async () => { + it('should render the add dataview menu if onDataViewCreated is given', async () => { const addDataViewSpy = jest.fn(); const component = mount( wrapDataViewComponentInContext({ ...props, onDataViewCreated: addDataViewSpy }, false) @@ -141,4 +141,21 @@ describe('DataView component', () => { const text = component.find('[data-test-subj="select-text-based-language-panel"]'); expect(text.length).not.toBe(0); }); + + it('should cleanup the query is on text based mode and add new dataview', async () => { + const component = mount( + wrapDataViewComponentInContext( + { + ...props, + onDataViewCreated: jest.fn(), + textBasedLanguages: [TextBasedLanguages.ESQL, TextBasedLanguages.SQL], + textBasedLanguage: TextBasedLanguages.SQL, + }, + false + ) + ); + findTestSubject(component, 'dataview-trigger').simulate('click'); + component.find('[data-test-subj="dataview-create-new"]').first().simulate('click'); + expect(props.onTextLangQuerySubmit).toHaveBeenCalled(); + }); }); diff --git a/src/plugins/unified_search/public/dataview_picker/change_dataview.tsx b/src/plugins/unified_search/public/dataview_picker/change_dataview.tsx index 94c869bb54a1c..2f641cd2d4e28 100644 --- a/src/plugins/unified_search/public/dataview_picker/change_dataview.tsx +++ b/src/plugins/unified_search/public/dataview_picker/change_dataview.tsx @@ -235,6 +235,16 @@ export function ChangeDataView({ onClick={() => { setPopoverIsOpen(false); onDataViewCreated(); + // go to dataview mode + if (isTextBasedLangSelected) { + setIsTextBasedLangSelected(false); + // clean up the Text based language query + onTextLangQuerySubmit?.({ + language: 'kuery', + query: '', + }); + setTriggerLabel(trigger.label); + } }} size="xs" iconType="plusInCircleFilled" @@ -262,7 +272,7 @@ export function ChangeDataView({ setIsTextBasedLangSelected(false); // clean up the Text based language query onTextLangQuerySubmit?.({ - language: 'kql', + language: 'kuery', query: '', }); onChangeDataView(newId); @@ -335,7 +345,7 @@ export function ChangeDataView({ setIsTextBasedLangSelected(false); // clean up the Text based language query onTextLangQuerySubmit?.({ - language: 'kql', + language: 'kuery', query: '', }); if (selectedDataViewId) { diff --git a/src/plugins/unified_search/public/dataview_picker/text_languages_transition_modal.tsx b/src/plugins/unified_search/public/dataview_picker/text_languages_transition_modal.tsx index 12f5414b92b9e..f7e8b11671556 100644 --- a/src/plugins/unified_search/public/dataview_picker/text_languages_transition_modal.tsx +++ b/src/plugins/unified_search/public/dataview_picker/text_languages_transition_modal.tsx @@ -86,6 +86,7 @@ export default function TextBasedLanguagesTransitionModal({ onClick={() => closeModal(dismissModalChecked)} color="warning" iconType="merge" + data-test-subj="unifiedSearch_switch_noSave" > {i18n.translate( 'unifiedSearch.query.queryBar.indexPattern.textBasedLanguagesTransitionModalCloseButton', @@ -101,6 +102,7 @@ export default function TextBasedLanguagesTransitionModal({ fill color="success" iconType="save" + data-test-subj="unifiedSearch_switch_andSave" > {i18n.translate( 'unifiedSearch.query.queryBar.indexPattern.textBasedLanguagesTransitionModalSaveButton', diff --git a/src/plugins/unified_search/public/search_bar/search_bar.tsx b/src/plugins/unified_search/public/search_bar/search_bar.tsx index b58c53dea73a0..76746d8a86979 100644 --- a/src/plugins/unified_search/public/search_bar/search_bar.tsx +++ b/src/plugins/unified_search/public/search_bar/search_bar.tsx @@ -353,7 +353,7 @@ class SearchBarUI extends C () => { if (this.props.onQuerySubmit) { this.props.onQuerySubmit({ - query: this.state.query, + query: query as QT, dateRange: { from: this.state.dateRangeFrom, to: this.state.dateRangeTo, diff --git a/src/plugins/vis_types/heatmap/public/sample_vis.test.mocks.ts b/src/plugins/vis_types/heatmap/public/sample_vis.test.mocks.ts index 04eac5c64de29..55a8aaa218837 100644 --- a/src/plugins/vis_types/heatmap/public/sample_vis.test.mocks.ts +++ b/src/plugins/vis_types/heatmap/public/sample_vis.test.mocks.ts @@ -1717,7 +1717,7 @@ export const sampleAreaVis = { { id: '1', enabled: true, - type: 'sum', + type: { name: 'sum' }, params: { field: 'total_quantity', }, @@ -1736,7 +1736,7 @@ export const sampleAreaVis = { { id: '2', enabled: true, - type: 'date_histogram', + type: { name: 'date_histogram' }, params: { field: 'order_date', timeRange: { @@ -1759,7 +1759,7 @@ export const sampleAreaVis = { { id: '3', enabled: true, - type: 'terms', + type: { name: 'terms' }, params: { field: 'category.keyword', orderBy: '1', diff --git a/src/plugins/vis_types/pie/kibana.json b/src/plugins/vis_types/pie/kibana.json index abed576cc6732..4c5ee6b50579e 100644 --- a/src/plugins/vis_types/pie/kibana.json +++ b/src/plugins/vis_types/pie/kibana.json @@ -3,8 +3,8 @@ "version": "kibana", "ui": true, "server": true, - "requiredPlugins": ["charts", "data", "expressions", "visualizations", "usageCollection", "expressionPartitionVis"], - "requiredBundles": ["visDefaultEditor"], + "requiredPlugins": ["charts", "data", "expressions", "visualizations", "usageCollection", "expressionPartitionVis", "dataViews"], + "requiredBundles": ["visDefaultEditor", "kibanaUtils"], "extraPublicDirs": ["common/index"], "owner": { "name": "Vis Editors", diff --git a/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.test.ts b/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.test.ts new file mode 100644 index 0000000000000..0a10a5bd7c0c0 --- /dev/null +++ b/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { getConfiguration } from '.'; +import { samplePieVis } from '../../sample_vis.test.mocks'; + +describe('getConfiguration', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('should return correct configuration', () => { + samplePieVis.uiState.get.mockReturnValueOnce(undefined); + expect( + getConfiguration('test1', samplePieVis as any, { + metrics: ['metric-1'], + buckets: ['bucket-1'], + }) + ).toEqual({ + layers: [ + { + categoryDisplay: undefined, + emptySizeRatio: undefined, + layerId: 'test1', + layerType: 'data', + legendDisplay: 'show', + legendMaxLines: 1, + legendPosition: 'right', + legendSize: 'large', + metric: 'metric-1', + nestedLegend: true, + numberDisplay: 'percent', + percentDecimals: 2, + primaryGroups: ['bucket-1'], + secondaryGroups: [], + showValuesInLegend: true, + truncateLegend: true, + }, + ], + shape: 'donut', + palette: undefined, + }); + }); + + test('should return legendDisplay = show if uiState contains truthy value', () => { + samplePieVis.uiState.get.mockReturnValueOnce(true); + expect( + getConfiguration( + 'test1', + { ...samplePieVis, params: { ...samplePieVis.params, legendDisplay: 'hide' } } as any, + { + metrics: ['metric-1'], + buckets: ['bucket-1'], + } + ) + ).toEqual({ + layers: [expect.objectContaining({ legendDisplay: 'show' })], + shape: 'donut', + palette: undefined, + }); + }); + + test('should return legendDisplay = hide if uiState contains falsy value', () => { + samplePieVis.uiState.get.mockReturnValueOnce(false); + expect( + getConfiguration( + 'test1', + { ...samplePieVis, params: { ...samplePieVis.params, legendDisplay: 'show' } } as any, + { + metrics: ['metric-1'], + buckets: ['bucket-1'], + } + ) + ).toEqual({ + layers: [expect.objectContaining({ legendDisplay: 'hide' })], + shape: 'donut', + palette: undefined, + }); + }); + + test('should return value of legendDisplay if uiState contains undefined value', () => { + samplePieVis.uiState.get.mockReturnValueOnce(undefined); + const legendDisplay = 'show'; + expect( + getConfiguration( + 'test1', + { ...samplePieVis, params: { ...samplePieVis.params, legendDisplay } } as any, + { + metrics: ['metric-1'], + buckets: ['bucket-1'], + } + ) + ).toEqual({ + layers: [expect.objectContaining({ legendDisplay })], + shape: 'donut', + palette: undefined, + }); + }); +}); diff --git a/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.ts b/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.ts new file mode 100644 index 0000000000000..9a3420581c1fd --- /dev/null +++ b/src/plugins/vis_types/pie/public/convert_to_lens/configurations/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { LegendDisplay, PartitionVisParams } from '@kbn/expression-partition-vis-plugin/common'; +import { + CategoryDisplayTypes, + NumberDisplayTypes, + PartitionVisConfiguration, +} from '@kbn/visualizations-plugin/common/convert_to_lens'; +import { Vis } from '@kbn/visualizations-plugin/public'; + +const getLayers = ( + layerId: string, + vis: Vis, + metrics: string[], + buckets: string[] +): PartitionVisConfiguration['layers'] => { + const legendOpen = vis.uiState.get('vis.legendOpen'); + const legendDisplayFromUiState = + legendOpen !== undefined ? (legendOpen ? LegendDisplay.SHOW : LegendDisplay.HIDE) : undefined; + + const showValuesInLegend = + vis.params.labels.values ?? + vis.params.showValuesInLegend ?? + vis.type.visConfig.defaults.showValuesInLegend; + + return [ + { + layerId, + layerType: 'data' as const, + primaryGroups: buckets, + secondaryGroups: [], + metric: metrics[0], + numberDisplay: + showValuesInLegend === false + ? NumberDisplayTypes.HIDDEN + : vis.params.labels.valuesFormat ?? vis.type.visConfig.defaults.labels.valuesFormat, + categoryDisplay: vis.params.labels.show + ? vis.params.labels.position ?? vis.type.visConfig.defaults.labels.position + : CategoryDisplayTypes.HIDE, + legendDisplay: + legendDisplayFromUiState ?? + vis.params.legendDisplay ?? + vis.type.visConfig.defaults.legendDisplay, + legendPosition: vis.params.legendPosition ?? vis.type.visConfig.defaults.legendPosition, + showValuesInLegend, + nestedLegend: vis.params.nestedLegend ?? vis.type.visConfig.defaults.nestedLegend, + percentDecimals: + vis.params.labels.percentDecimals ?? vis.type.visConfig.defaults.labels.percentDecimals, + emptySizeRatio: vis.params.emptySizeRatio ?? vis.type.visConfig.defaults.emptySizeRatio, + legendMaxLines: vis.params.maxLegendLines ?? vis.type.visConfig.defaults.maxLegendLines, + legendSize: vis.params.legendSize ?? vis.type.visConfig.defaults.legendSize, + truncateLegend: vis.params.truncateLegend ?? vis.type.visConfig.defaults.truncateLegend, + }, + ]; +}; + +export const getConfiguration = ( + layerId: string, + vis: Vis, + { + metrics, + buckets, + }: { + metrics: string[]; + buckets: string[]; + } +): PartitionVisConfiguration => { + return { + shape: vis.params.isDonut ? 'donut' : 'pie', + layers: getLayers(layerId, vis, metrics, buckets), + palette: vis.params.palette, + }; +}; diff --git a/src/plugins/vis_types/pie/public/convert_to_lens/index.test.ts b/src/plugins/vis_types/pie/public/convert_to_lens/index.test.ts new file mode 100644 index 0000000000000..c1e39d741f84d --- /dev/null +++ b/src/plugins/vis_types/pie/public/convert_to_lens/index.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { convertToLens } from '.'; +import { samplePieVis } from '../sample_vis.test.mocks'; + +const mockGetColumnsFromVis = jest.fn(); +const mockGetConfiguration = jest.fn().mockReturnValue({}); + +jest.mock('../services', () => ({ + getDataViewsStart: jest.fn(() => ({ get: () => ({}), getDefault: () => ({}) })), +})); + +jest.mock('@kbn/visualizations-plugin/public', () => ({ + convertToLensModule: Promise.resolve({ + getColumnsFromVis: jest.fn(() => mockGetColumnsFromVis()), + }), + getDataViewByIndexPatternId: jest.fn(() => ({ id: 'index-pattern' })), +})); + +jest.mock('./configurations', () => ({ + getConfiguration: jest.fn(() => mockGetConfiguration()), +})); + +describe('convertToLens', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + test('should return null if getColumnsFromVis returns null', async () => { + mockGetColumnsFromVis.mockReturnValue(null); + const result = await convertToLens(samplePieVis as any, {} as any); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(result).toBeNull(); + }); + + test('should return null if more than three split slice levels', async () => { + mockGetColumnsFromVis.mockReturnValue({ + buckets: ['1', '2', '3', '4'], + }); + const result = await convertToLens(samplePieVis as any, {} as any); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(result).toBeNull(); + }); + + test('should return null if no one split slices', async () => { + mockGetColumnsFromVis.mockReturnValue({ + buckets: [], + }); + const result = await convertToLens(samplePieVis as any, {} as any); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(result).toBeNull(); + }); + + test('should state for valid vis', async () => { + mockGetColumnsFromVis.mockReturnValue({ + buckets: ['2'], + columns: [{ columnId: '2' }, { columnId: '1' }], + }); + const result = await convertToLens(samplePieVis as any, {} as any); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(mockGetConfiguration).toBeCalledTimes(1); + expect(result?.type).toEqual('lnsPie'); + expect(result?.layers.length).toEqual(1); + expect(result?.layers[0]).toEqual( + expect.objectContaining({ + columnOrder: [], + columns: [{ columnId: '2' }, { columnId: '1' }], + }) + ); + }); +}); diff --git a/src/plugins/vis_types/pie/public/convert_to_lens/index.ts b/src/plugins/vis_types/pie/public/convert_to_lens/index.ts new file mode 100644 index 0000000000000..5b1973507c7df --- /dev/null +++ b/src/plugins/vis_types/pie/public/convert_to_lens/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Column, ColumnWithMeta } from '@kbn/visualizations-plugin/common'; +import { + convertToLensModule, + getDataViewByIndexPatternId, +} from '@kbn/visualizations-plugin/public'; +import uuid from 'uuid'; +import { getDataViewsStart } from '../services'; +import { getConfiguration } from './configurations'; +import { ConvertPieToLensVisualization } from './types'; + +export const isColumnWithMeta = (column: Column): column is ColumnWithMeta => { + if ((column as ColumnWithMeta).meta) { + return true; + } + return false; +}; + +export const excludeMetaFromColumn = (column: Column) => { + if (isColumnWithMeta(column)) { + const { meta, ...rest } = column; + return rest; + } + return column; +}; + +export const convertToLens: ConvertPieToLensVisualization = async (vis, timefilter) => { + if (!timefilter) { + return null; + } + + const dataViews = getDataViewsStart(); + const dataView = await getDataViewByIndexPatternId(vis.data.indexPattern?.id, dataViews); + + if (!dataView) { + return null; + } + + const { getColumnsFromVis } = await convertToLensModule; + const result = getColumnsFromVis(vis, timefilter, dataView, { + buckets: [], + splits: ['segment'], + unsupported: ['split_row', 'split_column'], + }); + + if (result === null) { + return null; + } + + // doesn't support more than three split slice levels + // doesn't support pie without at least one split slice + if (result.buckets.length > 3 || !result.buckets.length) { + return null; + } + + const layerId = uuid(); + + const indexPatternId = dataView.id!; + return { + type: 'lnsPie', + layers: [ + { + indexPatternId, + layerId, + columns: result.columns.map(excludeMetaFromColumn), + columnOrder: [], + }, + ], + configuration: getConfiguration(layerId, vis, result), + indexPatternIds: [indexPatternId], + }; +}; diff --git a/src/plugins/vis_types/pie/public/convert_to_lens/types.ts b/src/plugins/vis_types/pie/public/convert_to_lens/types.ts new file mode 100644 index 0000000000000..b190a4c891304 --- /dev/null +++ b/src/plugins/vis_types/pie/public/convert_to_lens/types.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { TimefilterContract } from '@kbn/data-plugin/public'; +import { PartitionVisParams } from '@kbn/expression-partition-vis-plugin/common'; +import { + NavigateToLensContext, + PartitionVisConfiguration, +} from '@kbn/visualizations-plugin/common'; +import { Vis } from '@kbn/visualizations-plugin/public'; + +export type ConvertPieToLensVisualization = ( + vis: Vis, + timefilter?: TimefilterContract +) => Promise | null>; diff --git a/src/plugins/vis_types/pie/public/plugin.ts b/src/plugins/vis_types/pie/public/plugin.ts index 480cf0c49db63..b4a8c0e3a2a69 100644 --- a/src/plugins/vis_types/pie/public/plugin.ts +++ b/src/plugins/vis_types/pie/public/plugin.ts @@ -6,13 +6,15 @@ * Side Public License, v 1. */ -import { CoreSetup, DocLinksStart, ThemeServiceStart } from '@kbn/core/public'; +import { CoreSetup, CoreStart, DocLinksStart, ThemeServiceStart } from '@kbn/core/public'; import { VisualizationsSetup } from '@kbn/visualizations-plugin/public'; import { ChartsPluginSetup } from '@kbn/charts-plugin/public'; import { UsageCollectionSetup } from '@kbn/usage-collection-plugin/public'; +import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; import { DataPublicPluginStart } from '@kbn/data-plugin/public'; import { LEGACY_PIE_CHARTS_LIBRARY } from '../common'; import { pieVisType } from './vis_type'; +import { setDataViewsStart } from './services'; /** @internal */ export interface VisTypePieSetupDependencies { @@ -21,6 +23,11 @@ export interface VisTypePieSetupDependencies { usageCollection: UsageCollectionSetup; } +/** @internal */ +export interface VisTypePieStartDependencies { + dataViews: DataViewsPublicPluginStart; +} + /** @internal */ export interface VisTypePiePluginStartDependencies { data: DataPublicPluginStart; @@ -53,5 +60,7 @@ export class VisTypePiePlugin { return {}; } - start() {} + start(core: CoreStart, { dataViews }: VisTypePieStartDependencies) { + setDataViewsStart(dataViews); + } } diff --git a/src/plugins/vis_types/pie/public/sample_vis.test.mocks.ts b/src/plugins/vis_types/pie/public/sample_vis.test.mocks.ts index e71bb7250dd1a..035432de9ad23 100644 --- a/src/plugins/vis_types/pie/public/sample_vis.test.mocks.ts +++ b/src/plugins/vis_types/pie/public/sample_vis.test.mocks.ts @@ -9,6 +9,8 @@ import { LegendDisplay } from '@kbn/expression-partition-vis-plugin/common'; import { LegendSize } from '@kbn/visualizations-plugin/common'; +const mockUiStateGet = jest.fn().mockReturnValue(() => false); + export const samplePieVis = { type: { name: 'pie', @@ -1308,7 +1310,7 @@ export const samplePieVis = { { id: '1', enabled: true, - type: 'count', + type: { name: 'count' }, params: {}, schema: 'metric', toSerializedFieldFormat: () => ({ @@ -1318,7 +1320,7 @@ export const samplePieVis = { { id: '2', enabled: true, - type: 'terms', + type: { name: 'terms' }, params: { field: 'Carrier', orderBy: '1', @@ -1353,5 +1355,6 @@ export const samplePieVis = { vis: { legendOpen: false, }, + get: mockUiStateGet, }, }; diff --git a/src/plugins/vis_types/pie/public/services.ts b/src/plugins/vis_types/pie/public/services.ts new file mode 100644 index 0000000000000..736ad70d49419 --- /dev/null +++ b/src/plugins/vis_types/pie/public/services.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { createGetterSetter } from '@kbn/kibana-utils-plugin/public'; +import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; + +export const [getDataViewsStart, setDataViewsStart] = + createGetterSetter('dataViews'); diff --git a/src/plugins/vis_types/pie/public/vis_type/pie.ts b/src/plugins/vis_types/pie/public/vis_type/pie.ts index 6d48507cf47a3..8d4b7b6828e39 100644 --- a/src/plugins/vis_types/pie/public/vis_type/pie.ts +++ b/src/plugins/vis_types/pie/public/vis_type/pie.ts @@ -21,6 +21,7 @@ import { DEFAULT_PERCENT_DECIMALS } from '../../common'; import { PieTypeProps } from '../types'; import { toExpressionAst } from '../to_ast'; import { getPieOptions } from '../editor/components'; +import { convertToLens } from '../convert_to_lens'; export const getPieVisTypeDefinition = ({ showElasticChartsOptions = false, @@ -123,4 +124,10 @@ export const getPieVisTypeDefinition = ({ }, hierarchicalData: true, requiresSearch: true, + navigateToLens: async (vis, timefilter) => (vis ? convertToLens(vis, timefilter) : null), + getExpressionVariables: async (vis, timeFilter) => { + return { + canNavigateToLens: Boolean(vis?.params ? await convertToLens(vis, timeFilter) : null), + }; + }, }); diff --git a/src/plugins/vis_types/table/kibana.json b/src/plugins/vis_types/table/kibana.json index 0d5d6066643ad..d0ab6489ae61e 100644 --- a/src/plugins/vis_types/table/kibana.json +++ b/src/plugins/vis_types/table/kibana.json @@ -7,6 +7,7 @@ "expressions", "visualizations", "fieldFormats", + "dataViews", "usageCollection" ], "requiredBundles": [ diff --git a/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap b/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap index 1a2badbd26634..a2032429c385e 100644 --- a/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap +++ b/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap @@ -25,6 +25,7 @@ Object { "as": "table_vis", "type": "render", "value": Object { + "canNavigateToLens": undefined, "visConfig": Object { "autoFitRowToContent": false, "buckets": Array [], diff --git a/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.test.ts b/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.test.ts new file mode 100644 index 0000000000000..4393ec86c2271 --- /dev/null +++ b/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.test.ts @@ -0,0 +1,76 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggTypes } from '../../../common'; +import { getConfiguration } from '.'; + +const params = { + perPage: 20, + percentageCol: 'Count', + showLabel: false, + showMetricsAtAllLevels: true, + showPartialRows: true, + showTotal: true, + showToolbar: false, + totalFunc: AggTypes.SUM, +}; + +describe('getConfiguration', () => { + test('should return correct configuration', () => { + expect( + getConfiguration('test1', params, { + metrics: ['metric-1'], + buckets: ['bucket-1'], + columnsWithoutReferenced: [ + { + columnId: 'metric-1', + operationType: 'count', + isBucketed: false, + isSplit: false, + sourceField: 'document', + params: {}, + dataType: 'number', + }, + { + columnId: 'bucket-1', + operationType: 'date_histogram', + isBucketed: true, + isSplit: false, + sourceField: 'date-field', + dataType: 'date', + params: { + interval: '1h', + }, + }, + ], + bucketCollapseFn: { 'bucket-1': 'sum' }, + }) + ).toEqual({ + columns: [ + { + alignment: 'left', + columnId: 'metric-1', + summaryRow: 'sum', + }, + { + alignment: 'left', + collapseFn: 'sum', + columnId: 'bucket-1', + }, + ], + headerRowHeight: 'single', + rowHeight: 'single', + layerId: 'test1', + layerType: 'data', + paging: { + enabled: true, + size: 20, + }, + }); + }); +}); diff --git a/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.ts b/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.ts new file mode 100644 index 0000000000000..d98cb917b40ac --- /dev/null +++ b/src/plugins/vis_types/table/public/convert_to_lens/configurations/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Column, PagingState, TableVisConfiguration } from '@kbn/visualizations-plugin/common'; +import { TableVisParams } from '../../../common'; + +const getColumns = ( + params: TableVisParams, + metrics: string[], + buckets: string[], + columns: Column[], + bucketCollapseFn?: Record +) => { + const { showTotal, totalFunc } = params; + return columns.map(({ columnId }) => ({ + columnId, + alignment: 'left' as const, + ...(showTotal && metrics.includes(columnId) ? { summaryRow: totalFunc } : {}), + ...(bucketCollapseFn && bucketCollapseFn[columnId] + ? { collapseFn: bucketCollapseFn[columnId] } + : {}), + })); +}; + +const getPagination = ({ perPage }: TableVisParams): PagingState => { + return { + enabled: perPage !== '', + size: perPage !== '' ? perPage : 0, + }; +}; + +const getRowHeight = ( + params: TableVisParams +): Pick => { + const { autoFitRowToContent } = params; + return { + rowHeight: autoFitRowToContent ? 'auto' : 'single', + headerRowHeight: autoFitRowToContent ? 'auto' : 'single', + }; +}; + +export const getConfiguration = ( + layerId: string, + params: TableVisParams, + { + metrics, + buckets, + columnsWithoutReferenced, + bucketCollapseFn, + }: { + metrics: string[]; + buckets: string[]; + columnsWithoutReferenced: Column[]; + bucketCollapseFn?: Record; + } +): TableVisConfiguration => { + return { + layerId, + layerType: 'data', + columns: getColumns(params, metrics, buckets, columnsWithoutReferenced, bucketCollapseFn), + paging: getPagination(params), + ...getRowHeight(params), + }; +}; diff --git a/src/plugins/vis_types/table/public/convert_to_lens/index.test.ts b/src/plugins/vis_types/table/public/convert_to_lens/index.test.ts new file mode 100644 index 0000000000000..5c1ad0578be11 --- /dev/null +++ b/src/plugins/vis_types/table/public/convert_to_lens/index.test.ts @@ -0,0 +1,111 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { convertToLens } from '.'; + +const mockGetColumnsFromVis = jest.fn(); +const mockGetPercentageColumnFormulaColumn = jest.fn(); +const mockGetVisSchemas = jest.fn(); +const mockGetConfiguration = jest.fn().mockReturnValue({}); + +jest.mock('../services', () => ({ + getDataViewsStart: jest.fn(() => ({ get: () => ({}), getDefault: () => ({}) })), +})); + +jest.mock('@kbn/visualizations-plugin/public', () => ({ + convertToLensModule: Promise.resolve({ + getColumnsFromVis: jest.fn(() => mockGetColumnsFromVis()), + getPercentageColumnFormulaColumn: jest.fn(() => mockGetPercentageColumnFormulaColumn()), + }), + getVisSchemas: jest.fn(() => mockGetVisSchemas()), + getDataViewByIndexPatternId: jest.fn(() => ({ id: 'index-pattern' })), +})); + +jest.mock('./configurations', () => ({ + getConfiguration: jest.fn(() => mockGetConfiguration()), +})); + +const vis = { + isHierarchical: () => false, + type: {}, + params: { + perPage: 20, + percentageCol: 'Count', + showLabel: false, + showMetricsAtAllLevels: true, + showPartialRows: true, + showTotal: true, + showToolbar: false, + totalFunc: 'sum', + }, + data: {}, +} as any; + +const timefilter = { + getAbsoluteTime: () => {}, +} as any; + +describe('convertToLens', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + test('should return null if getColumnsFromVis returns null', async () => { + mockGetColumnsFromVis.mockReturnValue(null); + const result = await convertToLens(vis, timefilter); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(result).toBeNull(); + }); + + test('should return null if can not build percentage column', async () => { + mockGetColumnsFromVis.mockReturnValue({ + buckets: ['2'], + columns: [{ columnId: '2' }, { columnId: '1' }], + columnsWithoutReferenced: [ + { columnId: '1', meta: { aggId: 'agg-1' } }, + { columnId: '2', meta: { aggId: 'agg-2' } }, + ], + }); + mockGetVisSchemas.mockReturnValue({ + metric: [{ label: 'Count', aggId: 'agg-1' }], + }); + mockGetPercentageColumnFormulaColumn.mockReturnValue(null); + const result = await convertToLens(vis, timefilter); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockGetPercentageColumnFormulaColumn).toBeCalledTimes(1); + expect(result).toBeNull(); + }); + + test('should return correct state for valid vis', async () => { + mockGetColumnsFromVis.mockReturnValue({ + buckets: ['2'], + columns: [{ columnId: '2' }, { columnId: '1' }], + columnsWithoutReferenced: [ + { columnId: '1', meta: { aggId: 'agg-1' } }, + { columnId: '2', meta: { aggId: 'agg-2' } }, + ], + }); + mockGetVisSchemas.mockReturnValue({ + metric: [{ label: 'Count', aggId: 'agg-1' }], + }); + mockGetPercentageColumnFormulaColumn.mockReturnValue({ columnId: 'percentage-column-1' }); + const result = await convertToLens(vis, timefilter); + expect(mockGetColumnsFromVis).toBeCalledTimes(1); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockGetPercentageColumnFormulaColumn).toBeCalledTimes(1); + expect(result?.type).toEqual('lnsDatatable'); + expect(result?.layers.length).toEqual(1); + expect(result?.layers[0]).toEqual( + expect.objectContaining({ + columnOrder: [], + columns: [{ columnId: '2' }, { columnId: 'percentage-column-1' }, { columnId: '1' }], + }) + ); + }); +}); diff --git a/src/plugins/vis_types/table/public/convert_to_lens/index.ts b/src/plugins/vis_types/table/public/convert_to_lens/index.ts new file mode 100644 index 0000000000000..e236c36e82a10 --- /dev/null +++ b/src/plugins/vis_types/table/public/convert_to_lens/index.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { Column, ColumnWithMeta, SchemaConfig } from '@kbn/visualizations-plugin/common'; +import { + convertToLensModule, + getVisSchemas, + getDataViewByIndexPatternId, +} from '@kbn/visualizations-plugin/public'; +import uuid from 'uuid'; +import { getDataViewsStart } from '../services'; +import { getConfiguration } from './configurations'; +import { ConvertTableToLensVisualization } from './types'; + +export const isColumnWithMeta = (column: Column): column is ColumnWithMeta => { + if ((column as ColumnWithMeta).meta) { + return true; + } + return false; +}; + +export const excludeMetaFromColumn = (column: Column) => { + if (isColumnWithMeta(column)) { + const { meta, ...rest } = column; + return rest; + } + return column; +}; + +export const convertToLens: ConvertTableToLensVisualization = async (vis, timefilter) => { + if (!timefilter) { + return null; + } + + const dataViews = getDataViewsStart(); + const dataView = await getDataViewByIndexPatternId(vis.data.indexPattern?.id, dataViews); + + if (!dataView) { + return null; + } + + const { getColumnsFromVis, getPercentageColumnFormulaColumn } = await convertToLensModule; + const result = getColumnsFromVis( + vis, + timefilter, + dataView, + { + buckets: ['bucket'], + splits: ['split_row', 'split_column'], + }, + { dropEmptyRowsInDateHistogram: true } + ); + + if (result === null) { + return null; + } + + if (vis.params.percentageCol) { + const visSchemas = getVisSchemas(vis, { + timefilter, + timeRange: timefilter.getAbsoluteTime(), + }); + const metricAgg = visSchemas.metric.find((m) => m.label === vis.params.percentageCol); + if (!metricAgg) { + return null; + } + const percentageColumn = getPercentageColumnFormulaColumn({ + agg: metricAgg as SchemaConfig, + dataView, + aggs: visSchemas.metric as Array>, + }); + if (!percentageColumn) { + return null; + } + result.columns.splice( + result.columnsWithoutReferenced.findIndex((c) => c.meta.aggId === metricAgg.aggId) + 1, + 0, + percentageColumn + ); + result.columnsWithoutReferenced.push(percentageColumn); + } + + const layerId = uuid(); + const indexPatternId = dataView.id!; + return { + type: 'lnsDatatable', + layers: [ + { + indexPatternId, + layerId, + columns: result.columns.map(excludeMetaFromColumn), + columnOrder: [], + }, + ], + configuration: getConfiguration(layerId, vis.params, result), + indexPatternIds: [indexPatternId], + }; +}; diff --git a/src/plugins/vis_types/table/public/convert_to_lens/types.ts b/src/plugins/vis_types/table/public/convert_to_lens/types.ts new file mode 100644 index 0000000000000..12aacce959c14 --- /dev/null +++ b/src/plugins/vis_types/table/public/convert_to_lens/types.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { TimefilterContract } from '@kbn/data-plugin/public'; +import { NavigateToLensContext, TableVisConfiguration } from '@kbn/visualizations-plugin/common'; +import { Vis } from '@kbn/visualizations-plugin/public'; +import { TableVisParams } from '../../common'; + +export type ConvertTableToLensVisualization = ( + vis: Vis, + timefilter?: TimefilterContract +) => Promise | null>; diff --git a/src/plugins/vis_types/table/public/plugin.ts b/src/plugins/vis_types/table/public/plugin.ts index 9e246448eb044..8e5769e2ef86a 100644 --- a/src/plugins/vis_types/table/public/plugin.ts +++ b/src/plugins/vis_types/table/public/plugin.ts @@ -12,7 +12,8 @@ import type { VisualizationsSetup } from '@kbn/visualizations-plugin/public'; import type { UsageCollectionStart } from '@kbn/usage-collection-plugin/public'; import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; -import { setFormatService } from './services'; +import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import { setDataViewsStart, setFormatService } from './services'; import { registerTableVis } from './register_vis'; /** @internal */ @@ -24,6 +25,7 @@ export interface TablePluginSetupDependencies { /** @internal */ export interface TablePluginStartDependencies { fieldFormats: FieldFormatsStart; + dataViews: DataViewsPublicPluginStart; usageCollection: UsageCollectionStart; } @@ -35,7 +37,8 @@ export class TableVisPlugin registerTableVis(core, deps); } - public start(core: CoreStart, { fieldFormats }: TablePluginStartDependencies) { + public start(core: CoreStart, { fieldFormats, dataViews }: TablePluginStartDependencies) { setFormatService(fieldFormats); + setDataViewsStart(dataViews); } } diff --git a/src/plugins/vis_types/table/public/services.ts b/src/plugins/vis_types/table/public/services.ts index edc6969e389ed..d6789deb70aaf 100644 --- a/src/plugins/vis_types/table/public/services.ts +++ b/src/plugins/vis_types/table/public/services.ts @@ -8,6 +8,14 @@ import { createGetterSetter } from '@kbn/kibana-utils-plugin/public'; import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; +import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import { UsageCollectionStart } from '@kbn/usage-collection-plugin/public'; export const [getFormatService, setFormatService] = createGetterSetter('FieldFormats'); + +export const [getUsageCollectionStart, setUsageCollectionStart] = + createGetterSetter('UsageCollection', false); + +export const [getDataViewsStart, setDataViewsStart] = + createGetterSetter('dataViews'); diff --git a/src/plugins/vis_types/table/public/table_vis_fn.ts b/src/plugins/vis_types/table/public/table_vis_fn.ts index 77996423d2c43..43bdec2b10de9 100644 --- a/src/plugins/vis_types/table/public/table_vis_fn.ts +++ b/src/plugins/vis_types/table/public/table_vis_fn.ts @@ -17,6 +17,7 @@ export interface TableVisRenderValue { visData: TableVisData; visType: typeof VIS_TYPE_TABLE; visConfig: TableVisConfig; + canNavigateToLens: boolean; } export type TableExpressionFunctionDefinition = ExpressionFunctionDefinition< @@ -177,6 +178,7 @@ export const createTableVisFn = (): TableExpressionFunctionDefinition => ({ ...args, title: (handlers.variables.embeddableTitle as string) ?? args.title, }, + canNavigateToLens: handlers.variables.canNavigateToLens as boolean, }, }; }, diff --git a/src/plugins/vis_types/table/public/table_vis_renderer.tsx b/src/plugins/vis_types/table/public/table_vis_renderer.tsx index 783cf49d06311..ab40c5f567c2d 100644 --- a/src/plugins/vis_types/table/public/table_vis_renderer.tsx +++ b/src/plugins/vis_types/table/public/table_vis_renderer.tsx @@ -39,7 +39,7 @@ export const getTableVisRenderer: ( ) => ExpressionRenderDefinition = (core, usageCollection) => ({ name: 'table_vis', reuseDomNode: true, - render: async (domNode, { visData, visConfig }, handlers) => { + render: async (domNode, { visData, visConfig, canNavigateToLens }, handlers) => { handlers.onDestroy(() => { unmountComponentAtNode(domNode); }); @@ -55,6 +55,7 @@ export const getTableVisRenderer: ( const counterEvents = [ `render_${visualizationType}_table`, !visData.table ? `render_${visualizationType}_table_split` : undefined, + canNavigateToLens ? `render_${visualizationType}_table_convertable` : undefined, ].filter(Boolean) as string[]; usageCollection.reportUiCounter(containerType, METRIC_TYPE.COUNT, counterEvents); diff --git a/src/plugins/vis_types/table/public/table_vis_type.ts b/src/plugins/vis_types/table/public/table_vis_type.ts index 8bd20fb6a0c81..27479d23b99de 100644 --- a/src/plugins/vis_types/table/public/table_vis_type.ts +++ b/src/plugins/vis_types/table/public/table_vis_type.ts @@ -13,6 +13,7 @@ import { VIS_EVENT_TO_TRIGGER, VisTypeDefinition } from '@kbn/visualizations-plu import { TableVisParams, VIS_TYPE_TABLE } from '../common'; import { TableOptions } from './components/table_vis_options_lazy'; import { toExpressionAst } from './to_ast'; +import { convertToLens } from './convert_to_lens'; export const tableVisTypeDefinition: VisTypeDefinition = { name: VIS_TYPE_TABLE, @@ -102,4 +103,10 @@ export const tableVisTypeDefinition: VisTypeDefinition = { hasPartialRows: (vis) => vis.params.showPartialRows, hierarchicalData: (vis) => vis.params.showPartialRows || vis.params.showMetricsAtAllLevels, requiresSearch: true, + navigateToLens: async (vis, timefilter) => (vis ? convertToLens(vis, timefilter) : null), + getExpressionVariables: async (vis, timeFilter) => { + return { + canNavigateToLens: Boolean(vis?.params ? await convertToLens(vis, timeFilter) : null), + }; + }, }; diff --git a/src/plugins/vis_types/table/tsconfig.json b/src/plugins/vis_types/table/tsconfig.json index 6df0a83853142..892c5691c8f04 100644 --- a/src/plugins/vis_types/table/tsconfig.json +++ b/src/plugins/vis_types/table/tsconfig.json @@ -17,6 +17,7 @@ { "path": "../../data/tsconfig.json" }, { "path": "../../visualizations/tsconfig.json" }, { "path": "../../share/tsconfig.json" }, + { "path": "../../data_views/tsconfig.json" }, { "path": "../../expressions/tsconfig.json" }, { "path": "../../kibana_utils/tsconfig.json" }, { "path": "../../kibana_react/tsconfig.json" }, diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/index.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/index.test.ts index 435335fe9dd25..309f066b18f29 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/index.test.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/index.test.ts @@ -40,7 +40,7 @@ describe('convertTSVBtoLensConfiguration', () => { test('should return null for a not supported chart', async () => { const metricModel = { ...model, - type: 'metric', + type: 'markdown', } as Panel; const triggerOptions = await convertTSVBtoLensConfiguration(metricModel); expect(triggerOptions).toBeNull(); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/index.ts index 5b92c0ab21668..a64118a1cb507 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/index.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/index.ts @@ -21,6 +21,10 @@ const getConvertFnByType = (type: PANEL_TYPES) => { const { convertToLens } = await import('./top_n'); return convertToLens; }, + [PANEL_TYPES.METRIC]: async () => { + const { convertToLens } = await import('./metric'); + return convertToLens; + }, }; return convertionFns[type]?.(); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/index.ts new file mode 100644 index 0000000000000..d1f24485d7646 --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/index.ts @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { MetricVisConfiguration } from '@kbn/visualizations-plugin/common'; +import { Metric, Panel, Series } from '../../../../../common/types'; +import { Column, Layer } from '../../convert'; +import { getSeriesAgg } from '../../series'; +import { getPalette } from './palette'; + +const getMetricWithCollapseFn = (series: Series | undefined) => { + if (!series) { + return; + } + const { metrics, seriesAgg } = getSeriesAgg(series.metrics); + const visibleMetric = metrics[metrics.length - 1]; + return { metric: visibleMetric, collapseFn: seriesAgg }; +}; + +const findMetricColumn = (metric: Metric | undefined, columns: Column[]) => { + if (!metric) { + return; + } + + return columns.find((column) => 'meta' in column && column.meta.metricId === metric.id); +}; + +export const getConfigurationForMetric = ( + model: Panel, + layer: Layer, + bucket?: Column +): MetricVisConfiguration | null => { + const [primarySeries, secondarySeries] = model.series.filter(({ hidden }) => !hidden); + + const primaryMetricWithCollapseFn = getMetricWithCollapseFn(primarySeries); + + if (!primaryMetricWithCollapseFn || !primaryMetricWithCollapseFn.metric) { + return null; + } + + const secondaryMetricWithCollapseFn = getMetricWithCollapseFn(secondarySeries); + const primaryColumn = findMetricColumn(primaryMetricWithCollapseFn.metric, layer.columns); + const secondaryColumn = findMetricColumn(secondaryMetricWithCollapseFn?.metric, layer.columns); + + if (primaryMetricWithCollapseFn.collapseFn && secondaryMetricWithCollapseFn?.collapseFn) { + return null; + } + + const palette = getPalette(model.background_color_rules ?? []); + if (palette === null) { + return null; + } + + return { + layerId: layer.layerId, + layerType: 'data', + metricAccessor: primaryColumn?.columnId, + secondaryMetricAccessor: secondaryColumn?.columnId, + breakdownByAccessor: bucket?.columnId, + palette, + collapseFn: primaryMetricWithCollapseFn.collapseFn ?? secondaryMetricWithCollapseFn?.collapseFn, + }; +}; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.test.ts new file mode 100644 index 0000000000000..827dc15ff171b --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.test.ts @@ -0,0 +1,177 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { getPalette } from './palette'; + +describe('getPalette', () => { + const invalidRules = [ + { id: 'some-id-0' }, + { id: 'some-id-1', value: 10 }, + { id: 'some-id-2', operator: 'gte' }, + { id: 'some-id-3', color: '#000' }, + { id: 'some-id-4', background_color: '#000' }, + ]; + test('should return undefined if no filled rules was provided', () => { + expect(getPalette([])).toBeUndefined(); + expect(getPalette(invalidRules)).toBeUndefined(); + }); + + test('should return undefined if only one valid rule is provided and it is not lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'gt', value: 100, background_color: '#000' }, + ]) + ).toBeUndefined(); + }); + + test('should return custom palette if only one valid rule is provided and it is lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'lte', value: 100, background_color: '#000' }, + ]) + ).toEqual({ + name: 'custom', + params: { + colorStops: [{ color: '#000000', stop: 100 }], + continuity: 'below', + maxSteps: 5, + name: 'custom', + progression: 'fixed', + rangeMax: 100, + rangeMin: -Infinity, + rangeType: 'number', + reverse: false, + steps: 1, + stops: [{ color: '#000000', stop: 100 }], + }, + type: 'palette', + }); + }); + + test('should return undefined if more than two types of rules', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'lte', value: 100, background_color: '#000' }, + { id: 'some-id-6', operator: 'gte', value: 150, background_color: '#000' }, + { id: 'some-id-7', operator: 'lt', value: 200, background_color: '#000' }, + ]) + ).toBeUndefined(); + }); + + test('should return undefined if two types of rules and last rule is not lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'gte', value: 100, background_color: '#000' }, + { id: 'some-id-7', operator: 'lt', value: 200, background_color: '#000' }, + { id: 'some-id-6', operator: 'gte', value: 150, background_color: '#000' }, + ]) + ).toBeUndefined(); + }); + + test('should return undefined if all rules are lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'lte', value: 100, background_color: '#000' }, + { id: 'some-id-7', operator: 'lte', value: 200, background_color: '#000' }, + { id: 'some-id-6', operator: 'lte', value: 150, background_color: '#000' }, + ]) + ).toBeUndefined(); + }); + + test('should return undefined if two types of rules and all except last one are lt and last one is not lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'lt', value: 100, background_color: '#000' }, + { id: 'some-id-7', operator: 'gte', value: 200, background_color: '#000' }, + { id: 'some-id-6', operator: 'lt', value: 150, background_color: '#000' }, + ]) + ).toBeUndefined(); + }); + + test('should return custom palette if two types of rules and all except last one is lt and last one is lte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'lt', value: 100, background_color: '#000' }, + { id: 'some-id-7', operator: 'lte', value: 200, background_color: '#000' }, + { id: 'some-id-6', operator: 'lt', value: 150, background_color: '#000' }, + ]) + ).toEqual({ + name: 'custom', + params: { + colorStops: [ + { color: '#000000', stop: -Infinity }, + { color: '#000000', stop: 100 }, + { color: '#000000', stop: 150 }, + ], + continuity: 'below', + maxSteps: 5, + name: 'custom', + progression: 'fixed', + rangeMax: 200, + rangeMin: -Infinity, + rangeType: 'number', + reverse: false, + steps: 4, + stops: [ + { color: '#000000', stop: 100 }, + { color: '#000000', stop: 150 }, + { color: '#000000', stop: 200 }, + ], + }, + type: 'palette', + }); + }); + + test('should return custom palette if last one is lte and all previous are gte', () => { + expect(getPalette([])).toBeUndefined(); + expect( + getPalette([ + ...invalidRules, + { id: 'some-id-5', operator: 'gte', value: 100, background_color: '#000' }, + { id: 'some-id-7', operator: 'lte', value: 200, background_color: '#000' }, + { id: 'some-id-6', operator: 'gte', value: 150, background_color: '#000' }, + ]) + ).toEqual({ + name: 'custom', + params: { + colorStops: [ + { color: '#000000', stop: 100 }, + { color: '#000000', stop: 150 }, + ], + continuity: 'none', + maxSteps: 5, + name: 'custom', + progression: 'fixed', + rangeMax: 200, + rangeMin: 100, + rangeType: 'number', + reverse: false, + steps: 2, + stops: [ + { color: '#000000', stop: 150 }, + { color: '#000000', stop: 200 }, + ], + }, + type: 'palette', + }); + }); +}); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.ts new file mode 100644 index 0000000000000..55741c57595e7 --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/metric/palette.ts @@ -0,0 +1,214 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import color from 'color'; +import { ColorStop, CustomPaletteParams, PaletteOutput } from '@kbn/coloring'; +import { uniqBy } from 'lodash'; +import { Panel } from '../../../../../common/types'; + +const Operators = { + GTE: 'gte', + GT: 'gt', + LTE: 'lte', + LT: 'lt', +} as const; + +type ColorStopsWithMinMax = Pick< + CustomPaletteParams, + 'colorStops' | 'stops' | 'steps' | 'rangeMax' | 'rangeMin' | 'continuity' +>; + +const getColorStopsWithMinMaxForAllGteOrWithLte = ( + rules: Exclude, + tailOperator: string +): ColorStopsWithMinMax => { + const lastRule = rules[rules.length - 1]; + const lastRuleColor = (lastRule.background_color ?? lastRule.color)!; + + const colorStops = rules.reduce((colors, rule, index, rulesArr) => { + const rgbColor = (rule.background_color ?? rule.color)!; + if (index === rulesArr.length - 1 && tailOperator === Operators.LTE) { + return colors; + } + // if last operation is LTE, color of gte should be replaced by lte + if (index === rulesArr.length - 2 && tailOperator === Operators.LTE) { + return [ + ...colors, + { + color: color(lastRuleColor).hex(), + stop: rule.value!, + }, + ]; + } + return [ + ...colors, + { + color: color(rgbColor).hex(), + stop: rule.value!, + }, + ]; + }, []); + + const stops = colorStops.reduce((prevStops, colorStop, index, colorStopsArr) => { + if (index === colorStopsArr.length - 1) { + return [ + ...prevStops, + { + color: colorStop.color, + stop: tailOperator === Operators.LTE ? lastRule.value! : colorStop.stop + 1, + }, + ]; + } + return [...prevStops, { color: colorStop.color, stop: colorStopsArr[index + 1].stop }]; + }, []); + + const [rule] = rules; + return { + rangeMin: rule.value, + rangeMax: tailOperator === Operators.LTE ? lastRule.value : Infinity, + colorStops, + stops, + steps: colorStops.length, + continuity: tailOperator === Operators.LTE ? 'none' : 'above', + }; +}; + +const getColorStopsWithMinMaxForLtWithLte = ( + rules: Exclude +): ColorStopsWithMinMax => { + const lastRule = rules[rules.length - 1]; + const colorStops = rules.reduce((colors, rule, index, rulesArr) => { + if (index === 0) { + return [{ color: color((rule.background_color ?? rule.color)!).hex(), stop: -Infinity }]; + } + const rgbColor = (rule.background_color ?? rule.color)!; + return [ + ...colors, + { + color: color(rgbColor).hex(), + stop: rulesArr[index - 1].value!, + }, + ]; + }, []); + + const stops = colorStops.reduce((prevStops, colorStop, index, colorStopsArr) => { + if (index === colorStopsArr.length - 1) { + return [ + ...prevStops, + { + color: colorStop.color, + stop: lastRule.value!, + }, + ]; + } + return [...prevStops, { color: colorStop.color, stop: colorStopsArr[index + 1].stop }]; + }, []); + + return { + rangeMin: -Infinity, + rangeMax: lastRule.value, + colorStops, + stops, + steps: colorStops.length + 1, + continuity: 'below', + }; +}; + +const getColorStopWithMinMaxForLte = ( + rule: Exclude[number] +): ColorStopsWithMinMax => { + const colorStop = { + color: color((rule.background_color ?? rule.color)!).hex(), + stop: rule.value!, + }; + return { + rangeMin: -Infinity, + rangeMax: rule.value!, + colorStops: [colorStop], + stops: [colorStop], + steps: 1, + continuity: 'below', + }; +}; + +const getCustomPalette = ( + colorStopsWithMinMax: ColorStopsWithMinMax +): PaletteOutput => { + return { + name: 'custom', + params: { + continuity: 'all', + maxSteps: 5, + name: 'custom', + progression: 'fixed', + rangeMax: Infinity, + rangeMin: -Infinity, + rangeType: 'number', + reverse: false, + ...colorStopsWithMinMax, + }, + type: 'palette', + }; +}; + +export const getPalette = ( + rules: Exclude +): PaletteOutput | null | undefined => { + const validRules = + rules.filter( + ({ operator, color: textColor, value, background_color: bColor }) => + operator && (bColor ?? textColor) && value !== undefined + ) ?? []; + + validRules.sort((rule1, rule2) => { + return rule1.value! - rule2.value!; + }); + + const kindOfRules = uniqBy(validRules, 'operator'); + + if (!kindOfRules.length) { + return; + } + + // lnsMetric is supporting lte only, if one rule is defined + if (validRules.length === 1) { + if (validRules[0].operator !== Operators.LTE) { + return; + } + return getCustomPalette(getColorStopWithMinMaxForLte(validRules[0])); + } + + const headRules = validRules.slice(0, -1); + const tailRule = validRules[validRules.length - 1]; + const kindOfHeadRules = uniqBy(headRules, 'operator'); + + if ( + kindOfHeadRules.length > 1 || + (kindOfHeadRules[0].operator !== tailRule.operator && tailRule.operator !== Operators.LTE) + ) { + return; + } + + const [rule] = kindOfHeadRules; + + if (rule.operator === Operators.LTE) { + return; + } + + if (rule.operator === Operators.LT) { + if (tailRule.operator !== Operators.LTE) { + return; + } + return getCustomPalette(getColorStopsWithMinMaxForLtWithLte(validRules)); + } + + if (rule.operator === Operators.GTE) { + return getCustomPalette( + getColorStopsWithMinMaxForAllGteOrWithLte(validRules, tailRule.operator!) + ); + } +}; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/xy/layers.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/xy/layers.ts index 064471e9fcfaf..6815e278e0f30 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/xy/layers.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/configurations/xy/layers.ts @@ -69,7 +69,7 @@ export const getLayers = async ( dataSourceLayers: Record, model: Panel, dataViews: DataViewsPublicPluginStart -): Promise => { +): Promise => { const nonAnnotationsLayers: XYLayerConfig[] = Object.keys(dataSourceLayers).map((key) => { const series = model.series[parseInt(key, 10)]; const { metrics, seriesAgg } = getSeriesAgg(series.metrics); @@ -136,30 +136,34 @@ export const getLayers = async ( (a) => typeof a.index_pattern === 'object' && 'id' in a.index_pattern && a.index_pattern.id ); - const annotationsLayers: Array = await Promise.all( - Object.entries(annotationsByIndexPattern).map(async ([indexPatternId, annotations]) => { - const convertedAnnotations: EventAnnotationConfig[] = []; - const { indexPattern } = (await fetchIndexPattern({ id: indexPatternId }, dataViews)) || {}; + try { + const annotationsLayers: Array = await Promise.all( + Object.entries(annotationsByIndexPattern).map(async ([indexPatternId, annotations]) => { + const convertedAnnotations: EventAnnotationConfig[] = []; + const { indexPattern } = (await fetchIndexPattern({ id: indexPatternId }, dataViews)) || {}; - if (indexPattern) { - annotations.forEach((a: Annotation) => { - const lensAnnotation = convertAnnotation(a, indexPattern); - if (lensAnnotation) { - convertedAnnotations.push(lensAnnotation); - } - }); - return { - layerId: v4(), - layerType: 'annotations', - ignoreGlobalFilters: true, - annotations: convertedAnnotations, - indexPatternId, - }; - } - }) - ); + if (indexPattern) { + annotations.forEach((a: Annotation) => { + const lensAnnotation = convertAnnotation(a, indexPattern); + if (lensAnnotation) { + convertedAnnotations.push(lensAnnotation); + } + }); + return { + layerId: v4(), + layerType: 'annotations', + ignoreGlobalFilters: true, + annotations: convertedAnnotations, + indexPatternId, + }; + } + }) + ); - return nonAnnotationsLayers.concat(...annotationsLayers.filter(nonNullable)); + return nonAnnotationsLayers.concat(...annotationsLayers.filter(nonNullable)); + } catch (e) { + return null; + } }; const convertAnnotation = ( diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/column.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/column.ts index 3bcd219f22676..bd0a9d572f192 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/column.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/column.ts @@ -11,7 +11,7 @@ import { BaseColumn, Operation, DataType, - ColumnWithMeta as GenericColumnWithMeta, + GenericColumnWithMeta, FormatParams, } from '@kbn/visualizations-plugin/common/convert_to_lens'; import uuid from 'uuid'; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/index.ts index 36f05c440bdc2..e03701e6ea153 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/index.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/index.ts @@ -17,7 +17,7 @@ export { export { convertToCumulativeSumColumns } from './cumulative_sum'; export { convertFilterRatioToFormulaColumn } from './filter_ratio'; export { convertToLastValueColumn } from './last_value'; -export { convertToStaticValueColumn } from './static_value'; +export { convertToStaticValueColumn, convertStaticValueToFormulaColumn } from './static_value'; export { convertToFiltersColumn } from './filters'; export { convertToDateHistogramColumn } from './date_histogram'; export { convertToTermsColumn } from './terms'; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/static_value.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/static_value.ts index c4400f72b289b..e03a9d7821364 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/static_value.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/static_value.ts @@ -7,9 +7,10 @@ */ import { StaticValueParams } from '@kbn/visualizations-plugin/common/convert_to_lens'; -import { CommonColumnsConverterArgs, StaticValueColumn } from './types'; +import { CommonColumnsConverterArgs, FormulaColumn, StaticValueColumn } from './types'; import type { Metric } from '../../../../common/types'; import { createColumn, getFormat } from './column'; +import { createFormulaColumn } from './formula'; export const convertToStaticValueParams = ({ value }: Metric): StaticValueParams => ({ value, @@ -37,3 +38,22 @@ export const convertToStaticValueColumn = ( }, }; }; + +export const convertStaticValueToFormulaColumn = ( + { series, metrics, dataView }: CommonColumnsConverterArgs, + { + visibleSeriesCount = 0, + reducedTimeRange, + }: { visibleSeriesCount?: number; reducedTimeRange?: string } = {} +): FormulaColumn | null => { + // Lens support reference lines only when at least one layer data exists + if (visibleSeriesCount === 1) { + return null; + } + const currentMetric = metrics[metrics.length - 1]; + return createFormulaColumn(currentMetric.value ?? '', { + series, + metric: currentMetric, + dataView, + }); +}; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/types.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/types.ts index 2b8e831d3f5c3..e5b862a0fe70f 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/types.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/convert/types.ts @@ -10,7 +10,7 @@ import type { DataView } from '@kbn/data-views-plugin/common'; import { Layer as BaseLayer, Column as BaseColumn, - ColumnWithMeta as GenericColumnWithMeta, + GenericColumnWithMeta, PercentileColumn as BasePercentileColumn, PercentileRanksColumn as BasePercentileRanksColumn, FiltersColumn, @@ -85,7 +85,7 @@ export type MovingAverageColumn = GenericColumnWithMeta; export type StaticValueColumn = GenericColumnWithMeta; -type ColumnsWithoutMeta = FiltersColumn | TermsColumn | DateHistogramColumn; +export type ColumnsWithoutMeta = FiltersColumn | TermsColumn | DateHistogramColumn; export type AnyColumnWithReferences = GenericColumnWithMeta; type CommonColumns = Exclude; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.test.ts index 5033d1470147d..975acfbbbcbb6 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.test.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.test.ts @@ -33,7 +33,7 @@ describe('getDataSourceInfo', () => { }); test('should return the default dataview if model_indexpattern is string', async () => { - const { indexPatternId, timeField } = await getDataSourceInfo( + const datasourceInfo = await getDataSourceInfo( 'test', undefined, false, @@ -41,12 +41,13 @@ describe('getDataSourceInfo', () => { undefined, dataViews ); + const { indexPatternId, timeField } = datasourceInfo!; expect(indexPatternId).toBe('12345'); expect(timeField).toBe('@timestamp'); }); test('should return the correct dataview if model_indexpattern is object', async () => { - const { indexPatternId, timeField } = await getDataSourceInfo( + const datasourceInfo = await getDataSourceInfo( { id: 'dataview-1-id' }, 'timeField-1', false, @@ -54,12 +55,14 @@ describe('getDataSourceInfo', () => { undefined, dataViews ); + const { indexPatternId, timeField } = datasourceInfo!; + expect(indexPatternId).toBe('dataview-1-id'); expect(timeField).toBe('timeField-1'); }); test('should fetch the correct data if overwritten dataview is provided', async () => { - const { indexPatternId, timeField } = await getDataSourceInfo( + const datasourceInfo = await getDataSourceInfo( { id: 'dataview-1-id' }, 'timeField-1', true, @@ -67,6 +70,8 @@ describe('getDataSourceInfo', () => { undefined, dataViews ); + const { indexPatternId, timeField } = datasourceInfo!; + expect(indexPatternId).toBe('test2'); expect(timeField).toBe('timeField2'); }); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.ts index 8f7fbd3670f4e..615e1595c8529 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/datasource/get_datasource_info.ts @@ -20,36 +20,40 @@ export const getDataSourceInfo = async ( seriesTimeField: string | undefined, dataViews: DataViewsPublicPluginStart ) => { - let indexPatternId = - modelIndexPattern && !isStringTypeIndexPattern(modelIndexPattern) ? modelIndexPattern.id : ''; + try { + let indexPatternId = + modelIndexPattern && !isStringTypeIndexPattern(modelIndexPattern) ? modelIndexPattern.id : ''; - let timeField = modelTimeField; - let indexPattern: DataView | null | undefined; - // handle override index pattern - if (isOverwritten) { - const fetchedIndexPattern = await fetchIndexPattern(overwrittenIndexPattern, dataViews); - indexPattern = fetchedIndexPattern.indexPattern; + let timeField = modelTimeField; + let indexPattern: DataView | null | undefined; + // handle override index pattern + if (isOverwritten) { + const fetchedIndexPattern = await fetchIndexPattern(overwrittenIndexPattern, dataViews); + indexPattern = fetchedIndexPattern.indexPattern; - if (indexPattern) { - indexPatternId = indexPattern.id ?? ''; - timeField = seriesTimeField ?? indexPattern.timeFieldName; + if (indexPattern) { + indexPatternId = indexPattern.id ?? ''; + timeField = seriesTimeField ?? indexPattern.timeFieldName; + } } - } - if (!indexPatternId) { - indexPattern = await dataViews.getDefault(); - indexPatternId = indexPattern?.id ?? ''; - timeField = indexPattern?.timeFieldName; - } else { - indexPattern = await dataViews.get(indexPatternId); - if (!timeField) { - timeField = indexPattern.timeFieldName; + if (!indexPatternId) { + indexPattern = await dataViews.getDefault(); + indexPatternId = indexPattern?.id ?? ''; + timeField = indexPattern?.timeFieldName; + } else { + indexPattern = await dataViews.get(indexPatternId); + if (!timeField) { + timeField = indexPattern.timeFieldName; + } } - } - return { - indexPatternId, - timeField, - indexPattern, - }; + return { + indexPatternId, + timeField, + indexPattern, + }; + } catch (e) { + return null; + } }; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/metrics/supported_metrics.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/metrics/supported_metrics.ts index 736037a3eb67c..76d15793f4516 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/metrics/supported_metrics.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/metrics/supported_metrics.ts @@ -22,8 +22,8 @@ interface AggWithFormula { export type AggOptions = { isFullReference: boolean; isFieldRequired: boolean; - supportedPanelTypes: PANEL_TYPES[]; - supportedTimeRangeModes: TIME_RANGE_DATA_MODES[]; + supportedPanelTypes: readonly PANEL_TYPES[]; + supportedTimeRangeModes: readonly TIME_RANGE_DATA_MODES[]; } & (T extends Exclude ? Agg : AggWithFormula); // list of supported TSVB aggregation types in Lens @@ -62,8 +62,13 @@ export type SupportedMetrics = LocalSupportedMetrics & { [Key in UnsupportedSupportedMetrics]?: null; }; -const supportedPanelTypes: PANEL_TYPES[] = [PANEL_TYPES.TIMESERIES, PANEL_TYPES.TOP_N]; -const supportedTimeRangeModes: TIME_RANGE_DATA_MODES[] = [ +const supportedPanelTypes: readonly PANEL_TYPES[] = [ + PANEL_TYPES.TIMESERIES, + PANEL_TYPES.TOP_N, + PANEL_TYPES.METRIC, +]; + +const supportedTimeRangeModes: readonly TIME_RANGE_DATA_MODES[] = [ TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE, TIME_RANGE_DATA_MODES.LAST_VALUE, ]; @@ -94,29 +99,29 @@ export const SUPPORTED_METRICS: SupportedMetrics = { name: 'counter_rate', isFullReference: true, isFieldRequired: true, - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, supportedTimeRangeModes, }, moving_average: { name: 'moving_average', isFullReference: true, isFieldRequired: true, - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, derivative: { name: 'differences', isFullReference: true, isFieldRequired: true, - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, cumulative_sum: { name: 'cumulative_sum', isFullReference: true, isFieldRequired: true, - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, avg_bucket: { name: 'formula', @@ -124,8 +129,8 @@ export const SUPPORTED_METRICS: SupportedMetrics = { isFieldRequired: true, isFormula: true, formula: 'overall_average', - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, max_bucket: { name: 'formula', @@ -133,8 +138,8 @@ export const SUPPORTED_METRICS: SupportedMetrics = { isFieldRequired: true, isFormula: true, formula: 'overall_max', - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, min_bucket: { name: 'formula', @@ -142,8 +147,8 @@ export const SUPPORTED_METRICS: SupportedMetrics = { isFieldRequired: true, isFormula: true, formula: 'overall_min', - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, sum_bucket: { name: 'formula', @@ -151,8 +156,8 @@ export const SUPPORTED_METRICS: SupportedMetrics = { isFieldRequired: true, isFormula: true, formula: 'overall_sum', - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, max: { name: 'max', @@ -220,8 +225,8 @@ export const SUPPORTED_METRICS: SupportedMetrics = { isFieldRequired: true, isFormula: true, formula: 'pick_max', - supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as PANEL_TYPES[], - supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as TIME_RANGE_DATA_MODES[], + supportedPanelTypes: [PANEL_TYPES.TIMESERIES] as const, + supportedTimeRangeModes: [TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE] as const, }, static: { name: 'static_value', diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.test.ts index 5ca1fe71a0ada..4461072c8df62 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.test.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.test.ts @@ -20,6 +20,7 @@ const mockConvertToCounterRateColumn = jest.fn(); const mockConvertOtherAggsToFormulaColumn = jest.fn(); const mockConvertToLastValueColumn = jest.fn(); const mockConvertToStaticValueColumn = jest.fn(); +const mockConvertStaticValueToFormulaColumn = jest.fn(); const mockConvertToStandartDeviationColumn = jest.fn(); const mockConvertMetricAggregationColumnWithoutSpecialParams = jest.fn(); @@ -32,6 +33,7 @@ jest.mock('../convert', () => ({ convertOtherAggsToFormulaColumn: jest.fn(() => mockConvertOtherAggsToFormulaColumn()), convertToLastValueColumn: jest.fn(() => mockConvertToLastValueColumn()), convertToStaticValueColumn: jest.fn(() => mockConvertToStaticValueColumn()), + convertStaticValueToFormulaColumn: jest.fn(() => mockConvertStaticValueToFormulaColumn()), convertToStandartDeviationColumn: jest.fn(() => mockConvertToStandartDeviationColumn()), convertMetricAggregationColumnWithoutSpecialParams: jest.fn(() => mockConvertMetricAggregationColumnWithoutSpecialParams() @@ -138,8 +140,18 @@ describe('getMetricsColumns', () => { mockConvertToLastValueColumn, ], [ - 'call convertToStaticValueColumn if metric type is static', + 'call convertStaticValueToFormulaColumn if metric type is static', [createSeries({ metrics: [{ type: TSVB_METRIC_TYPES.STATIC, id: '1' }] }), dataView, 1], + mockConvertStaticValueToFormulaColumn, + ], + [ + 'call convertToStaticValueColumn if metric type is static and isStaticValueColumnSupported is true', + [ + createSeries({ metrics: [{ type: TSVB_METRIC_TYPES.STATIC, id: '1' }] }), + dataView, + 1, + { isStaticValueColumnSupported: true }, + ], mockConvertToStaticValueColumn, ], [ diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.ts index 07294a3a61aaa..8f7d4ded0d076 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/lib/series/metrics_columns.ts @@ -21,6 +21,7 @@ import { convertFilterRatioToFormulaColumn, convertToLastValueColumn, convertToStaticValueColumn, + convertStaticValueToFormulaColumn, convertMetricAggregationColumnWithoutSpecialParams, convertToCounterRateColumn, convertToStandartDeviationColumn, @@ -31,7 +32,10 @@ export const getMetricsColumns = ( series: Series, dataView: DataView, visibleSeriesCount: number, - reducedTimeRange?: string + { + isStaticValueColumnSupported = false, + reducedTimeRange, + }: { reducedTimeRange?: string; isStaticValueColumnSupported?: boolean } = {} ): Column[] | null => { const { metrics: validMetrics, seriesAgg } = getSeriesAgg( series.metrics as [Metric, ...Metric[]] @@ -117,10 +121,12 @@ export const getMetricsColumns = ( return getValidColumns(column); } case 'static': { - const column = convertToStaticValueColumn(columnsConverterArgs, { - visibleSeriesCount, - reducedTimeRange, - }); + const column = isStaticValueColumnSupported + ? convertToStaticValueColumn(columnsConverterArgs, { + visibleSeriesCount, + reducedTimeRange, + }) + : convertStaticValueToFormulaColumn(columnsConverterArgs); return getValidColumns(column); } case 'std_deviation': { diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.test.ts new file mode 100644 index 0000000000000..9407599573d9d --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.test.ts @@ -0,0 +1,272 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/public'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { convertToLens } from '.'; +import { createPanel, createSeries } from '../lib/__mocks__'; + +const mockGetMetricsColumns = jest.fn(); +const mockGetBucketsColumns = jest.fn(); +const mockGetConfigurationForMetric = jest.fn(); +const mockIsValidMetrics = jest.fn(); +const mockGetDatasourceValue = jest + .fn() + .mockImplementation(() => Promise.resolve(stubLogstashDataView)); +const mockGetDataSourceInfo = jest.fn(); + +jest.mock('../../services', () => ({ + getDataViewsStart: jest.fn(() => mockGetDatasourceValue), +})); + +jest.mock('../lib/series', () => ({ + getMetricsColumns: jest.fn(() => mockGetMetricsColumns()), + getBucketsColumns: jest.fn(() => mockGetBucketsColumns()), +})); + +jest.mock('../lib/configurations/metric', () => ({ + getConfigurationForMetric: jest.fn(() => mockGetConfigurationForMetric()), +})); + +jest.mock('../lib/metrics', () => ({ + isValidMetrics: jest.fn(() => mockIsValidMetrics()), + getReducedTimeRange: jest.fn().mockReturnValue('10'), +})); + +jest.mock('../lib/datasource', () => ({ + getDataSourceInfo: jest.fn(() => mockGetDataSourceInfo()), +})); + +describe('convertToLens', () => { + const model = createPanel({ + series: [ + createSeries({ + metrics: [ + { id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }, + { id: 'some-id-1', type: METRIC_TYPES.COUNT }, + ], + }), + ], + }); + + const bucket = { + isBucketed: true, + isSplit: true, + operationType: 'terms', + params: { + exclude: [], + excludeIsRegex: true, + include: [], + includeIsRegex: true, + orderAgg: { + columnId: 'some-id-0', + dataType: 'number', + isBucketed: true, + isSplit: false, + operationType: 'average', + params: {}, + sourceField: 'bytes', + }, + orderBy: { columnId: 'some-id-0', type: 'column' }, + orderDirection: 'asc', + otherBucket: false, + parentFormat: { id: 'terms' }, + secondaryFields: [], + size: 3, + }, + sourceField: 'bytes', + }; + + const bucket2 = { + isBucketed: true, + isSplit: true, + operationType: 'terms', + params: { + exclude: [], + excludeIsRegex: true, + include: [], + includeIsRegex: true, + orderAgg: { + columnId: 'some-id-1', + dataType: 'number', + isBucketed: true, + isSplit: false, + operationType: 'average', + params: {}, + sourceField: 'bytes', + }, + orderBy: { columnId: 'some-id-1', type: 'column' }, + orderDirection: 'desc', + otherBucket: false, + parentFormat: { id: 'terms' }, + secondaryFields: [], + size: 10, + }, + sourceField: 'bytes', + }; + + const metric = { + meta: { metricId: 'some-id-0' }, + operationType: 'last_value', + params: { showArrayValues: false, sortField: '@timestamp' }, + reducedTimeRange: '10m', + }; + + beforeEach(() => { + mockIsValidMetrics.mockReturnValue(true); + mockGetDataSourceInfo.mockReturnValue({ + indexPatternId: 'test-index-pattern', + timeField: 'timeField', + indexPattern: { id: 'test-index-pattern' }, + }); + mockGetMetricsColumns.mockReturnValue([{}]); + mockGetBucketsColumns.mockReturnValue([{}]); + mockGetConfigurationForMetric.mockReturnValue({}); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test('should return null for invalid metrics', async () => { + mockIsValidMetrics.mockReturnValue(null); + const result = await convertToLens(model); + expect(result).toBeNull(); + expect(mockIsValidMetrics).toBeCalledTimes(1); + }); + + test('should return null for invalid or unsupported metrics', async () => { + mockGetMetricsColumns.mockReturnValue(null); + const result = await convertToLens(model); + expect(result).toBeNull(); + expect(mockGetMetricsColumns).toBeCalledTimes(1); + }); + + test('should return null for invalid or unsupported buckets', async () => { + mockGetBucketsColumns.mockReturnValue(null); + const result = await convertToLens(model); + expect(result).toBeNull(); + expect(mockGetBucketsColumns).toBeCalledTimes(1); + }); + + test('should return state for valid model', async () => { + const result = await convertToLens(model); + expect(result).toBeDefined(); + expect(result?.type).toBe('lnsMetric'); + expect(mockGetBucketsColumns).toBeCalledTimes(model.series.length); + expect(mockGetConfigurationForMetric).toBeCalledTimes(1); + }); + + test('should skip hidden series', async () => { + const result = await convertToLens( + createPanel({ + series: [ + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: true, + }), + ], + }) + ); + expect(result).toBeDefined(); + expect(result?.type).toBe('lnsMetric'); + expect(mockIsValidMetrics).toBeCalledTimes(0); + }); + + test('should return null if multiple indexPatterns are provided', async () => { + mockGetDataSourceInfo.mockReturnValueOnce({ + indexPatternId: 'test-index-pattern-1', + timeField: 'timeField', + indexPattern: { id: 'test-index-pattern-1' }, + }); + + const result = await convertToLens( + createPanel({ + series: [ + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + ], + }) + ); + expect(result).toBeNull(); + }); + + test('should return null if visible series is 2 and bucket is 1', async () => { + mockGetBucketsColumns.mockReturnValueOnce([bucket]); + mockGetBucketsColumns.mockReturnValueOnce([]); + mockGetMetricsColumns.mockReturnValueOnce([metric]); + + const result = await convertToLens( + createPanel({ + series: [ + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + ], + }) + ); + expect(result).toBeNull(); + }); + + test('should return null if visible series is 2 and two not unique buckets', async () => { + mockGetBucketsColumns.mockReturnValueOnce([bucket]); + mockGetBucketsColumns.mockReturnValueOnce([bucket2]); + mockGetMetricsColumns.mockReturnValueOnce([metric]); + + const result = await convertToLens( + createPanel({ + series: [ + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + ], + }) + ); + expect(result).toBeNull(); + }); + + test('should return state if visible series is 2 and two unique buckets', async () => { + mockGetBucketsColumns.mockReturnValueOnce([bucket]); + mockGetBucketsColumns.mockReturnValueOnce([bucket]); + mockGetMetricsColumns.mockReturnValueOnce([metric]); + + const result = await convertToLens( + createPanel({ + series: [ + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + createSeries({ + metrics: [{ id: 'some-id', type: METRIC_TYPES.AVG, field: 'test-field' }], + hidden: false, + }), + ], + }) + ); + expect(result).toBeDefined(); + expect(result?.type).toBe('lnsMetric'); + expect(mockGetConfigurationForMetric).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.ts new file mode 100644 index 0000000000000..25f55b5a1c44c --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/index.ts @@ -0,0 +1,130 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import uuid from 'uuid'; +import { DataView, parseTimeShift } from '@kbn/data-plugin/common'; +import { getIndexPatternIds } from '@kbn/visualizations-plugin/common/convert_to_lens'; +import { PANEL_TYPES } from '../../../common/enums'; +import { getDataViewsStart } from '../../services'; +import { getDataSourceInfo } from '../lib/datasource'; +import { getMetricsColumns, getBucketsColumns } from '../lib/series'; +import { getConfigurationForMetric as getConfiguration } from '../lib/configurations/metric'; +import { getReducedTimeRange, isValidMetrics } from '../lib/metrics'; +import { ConvertTsvbToLensVisualization } from '../types'; +import { ColumnsWithoutMeta, Layer as ExtendedLayer } from '../lib/convert'; +import { excludeMetaFromLayers, getUniqueBuckets } from './utils'; + +const MAX_SERIES = 2; +const MAX_BUCKETS = 2; + +export const convertToLens: ConvertTsvbToLensVisualization = async (model, timeRange) => { + const dataViews = getDataViewsStart(); + const seriesNum = model.series.filter((series) => !series.hidden).length; + + const indexPatternIds = new Set(); + const visibleSeries = model.series.filter(({ hidden }) => !hidden); + let currentIndexPattern: DataView | null = null; + for (const series of visibleSeries) { + const datasourceInfo = await getDataSourceInfo( + model.index_pattern, + model.time_field, + Boolean(series.override_index_pattern), + series.series_index_pattern, + series.series_time_field, + dataViews + ); + + if (!datasourceInfo) { + return null; + } + + const { indexPatternId, indexPattern } = datasourceInfo; + indexPatternIds.add(indexPatternId); + currentIndexPattern = indexPattern; + } + + if (indexPatternIds.size > 1) { + return null; + } + + const [indexPatternId] = indexPatternIds.values(); + + const buckets = []; + const metrics = []; + + // handle multiple layers/series + for (const series of visibleSeries) { + // not valid time shift + if (series.offset_time && parseTimeShift(series.offset_time) === 'invalid') { + return null; + } + + if (!isValidMetrics(series.metrics, PANEL_TYPES.METRIC, series.time_range_mode)) { + return null; + } + + const reducedTimeRange = getReducedTimeRange(model, series, timeRange); + + // handle multiple metrics + const metricsColumns = getMetricsColumns(series, currentIndexPattern!, seriesNum, { + reducedTimeRange, + }); + if (metricsColumns === null) { + return null; + } + + const bucketsColumns = getBucketsColumns( + model, + series, + metricsColumns, + currentIndexPattern!, + false + ); + + if (bucketsColumns === null) { + return null; + } + + buckets.push(...bucketsColumns); + metrics.push(...metricsColumns); + } + + let uniqueBuckets = buckets; + if (visibleSeries.length === MAX_SERIES && buckets.length) { + if (buckets.length !== MAX_BUCKETS) { + return null; + } + + uniqueBuckets = getUniqueBuckets(buckets as ColumnsWithoutMeta[]); + if (uniqueBuckets.length !== 1) { + return null; + } + } + + const [bucket] = uniqueBuckets; + + const extendedLayer: ExtendedLayer = { + indexPatternId: indexPatternId as string, + layerId: uuid(), + columns: [...metrics, ...(bucket ? [bucket] : [])], + columnOrder: [], + }; + + const configuration = getConfiguration(model, extendedLayer, bucket); + if (!configuration) { + return null; + } + + const layers = Object.values(excludeMetaFromLayers({ 0: extendedLayer })); + return { + type: 'lnsMetric', + layers, + configuration, + indexPatternIds: getIndexPatternIds(layers), + }; +}; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.test.ts new file mode 100644 index 0000000000000..8f880dfe95c5e --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Column, DateHistogramColumn, TermsColumn } from '../lib/convert'; +import { getUniqueBuckets } from './utils'; + +describe('getUniqueBuckets', () => { + const bucket2: TermsColumn = { + columnId: '12', + dataType: 'string', + isBucketed: true, + isSplit: true, + operationType: 'terms', + params: { + exclude: [], + excludeIsRegex: true, + include: [], + includeIsRegex: true, + orderAgg: { + columnId: 'some-id-1', + dataType: 'number', + isBucketed: true, + isSplit: false, + operationType: 'average', + params: {}, + sourceField: 'bytes', + }, + orderBy: { columnId: 'some-id-1', type: 'column' }, + orderDirection: 'desc', + otherBucket: false, + parentFormat: { id: 'terms' }, + secondaryFields: [], + size: 10, + }, + sourceField: 'bytes', + }; + + it('should return unique buckets', () => { + expect(getUniqueBuckets([bucket2, bucket2])).toEqual([bucket2]); + }); + + it('should ignore columnIds', () => { + const bucketWithOtherColumnIds = { + ...bucket2, + columnId: '22', + params: { + ...bucket2.params, + orderAgg: { ...bucket2.params.orderAgg, columnId: '---1' } as Column, + orderBy: { ...bucket2.params.orderBy, columnId: '---2' } as { + type: 'column'; + columnId: string; + }, + }, + }; + expect(getUniqueBuckets([bucket2, bucketWithOtherColumnIds])).toEqual([bucket2]); + }); + + it('should respect differences of terms', () => { + const bucketWithOtherColumnIds = { + ...bucket2, + columnId: '22', + params: { + ...bucket2.params, + orderAgg: { ...bucket2.params.orderAgg, columnId: '---1' } as Column, + orderBy: { ...bucket2.params.orderBy, columnId: '---2' } as { + type: 'column'; + columnId: string; + }, + }, + sourceField: 'name', + }; + expect(getUniqueBuckets([bucket2, bucketWithOtherColumnIds])).toEqual([ + bucket2, + bucketWithOtherColumnIds, + ]); + }); + + it('should respect differences of other buckets', () => { + const bucket: DateHistogramColumn = { + dataType: 'number', + isBucketed: true, + isSplit: false, + operationType: 'date_histogram', + params: { dropPartials: false, includeEmptyRows: true, interval: 'auto' }, + sourceField: 'field1', + columnId: '1', + }; + const bucket1 = { + ...bucket, + columnId: '22', + }; + expect(getUniqueBuckets([bucket, bucket1])).toEqual([bucket]); + const bucket3 = { + ...bucket, + field: 'some-other-field', + }; + expect(getUniqueBuckets([bucket, bucket3])).toEqual([bucket, bucket3]); + }); +}); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.ts new file mode 100644 index 0000000000000..8df1b0f40f8be --- /dev/null +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/metric/utils.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { uniqWith } from 'lodash'; +import deepEqual from 'react-fast-compare'; +import { Layer, Operations, TermsColumn } from '@kbn/visualizations-plugin/common/convert_to_lens'; +import { Layer as ExtendedLayer, excludeMetaFromColumn, ColumnsWithoutMeta } from '../lib/convert'; + +export const excludeMetaFromLayers = ( + layers: Record +): Record => { + const newLayers: Record = {}; + Object.entries(layers).forEach(([layerId, layer]) => { + const columns = layer.columns.map(excludeMetaFromColumn); + newLayers[layerId] = { ...layer, columns }; + }); + + return newLayers; +}; + +const excludeColumnIdsFromBucket = (bucket: ColumnsWithoutMeta) => { + const { columnId, ...restBucket } = bucket; + if (bucket.operationType === Operations.TERMS) { + const { orderBy, orderAgg, ...restParams } = bucket.params; + let orderByWithoutColumn: Omit = orderBy; + if ('columnId' in orderBy) { + const { columnId: orderByColumnId, ...restOrderBy } = orderBy; + orderByWithoutColumn = restOrderBy; + } + + let orderAggWithoutColumn: Omit | undefined = + orderAgg; + if (orderAgg) { + const { columnId: cId, ...restOrderAgg } = orderAgg; + orderAggWithoutColumn = restOrderAgg; + } + + return { + ...restBucket, + params: { + ...restParams, + orderBy: orderByWithoutColumn, + orderAgg: orderAggWithoutColumn, + }, + }; + } + return restBucket; +}; + +export const getUniqueBuckets = (buckets: ColumnsWithoutMeta[]) => + uniqWith(buckets, (bucket1, bucket2) => { + if (bucket1.operationType !== bucket2.operationType) { + return false; + } + + const bucketWithoutColumnIds1 = excludeColumnIdsFromBucket(bucket1); + const bucketWithoutColumnIds2 = excludeColumnIdsFromBucket(bucket2); + + return deepEqual(bucketWithoutColumnIds1, bucketWithoutColumnIds2); + }); diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.test.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.test.ts index a6460e2917ba9..50aa1a6c6f7f4 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.test.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.test.ts @@ -70,7 +70,7 @@ describe('convertToLens', () => { mockConvertToDateHistogramColumn.mockReturnValue({}); mockGetMetricsColumns.mockReturnValue([{}]); mockGetBucketsColumns.mockReturnValue([{}]); - mockGetConfigurationForTimeseries.mockReturnValue({}); + mockGetConfigurationForTimeseries.mockReturnValue({ layers: [] }); }); afterEach(() => { diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.ts index 25cd1fa962d0d..8cbbbf0f9e739 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/timeseries/index.ts @@ -7,7 +7,11 @@ */ import { parseTimeShift } from '@kbn/data-plugin/common'; -import { Layer } from '@kbn/visualizations-plugin/common/convert_to_lens'; +import { + getIndexPatternIds, + isAnnotationsLayer, + Layer, +} from '@kbn/visualizations-plugin/common/convert_to_lens'; import uuid from 'uuid'; import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; import { Panel } from '../../../common/types'; @@ -57,7 +61,7 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model: Panel return null; } - const { indexPatternId, indexPattern, timeField } = await getDataSourceInfo( + const datasourceInfo = await getDataSourceInfo( model.index_pattern, model.time_field, Boolean(series.override_index_pattern), @@ -65,7 +69,11 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model: Panel series.series_time_field, dataViews ); + if (!datasourceInfo) { + return null; + } + const { indexPatternId, indexPattern, timeField } = datasourceInfo; if (!timeField) { return null; } @@ -78,7 +86,9 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model: Panel return null; } // handle multiple metrics - const metricsColumns = getMetricsColumns(series, indexPattern!, seriesNum); + const metricsColumns = getMetricsColumns(series, indexPattern!, seriesNum, { + isStaticValueColumnSupported: true, + }); if (metricsColumns === null) { return null; } @@ -98,10 +108,23 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model: Panel } const configLayers = await getLayers(extendedLayers, model, dataViews); + if (configLayers === null) { + return null; + } + + const configuration = getConfiguration(model, configLayers); + const layers = Object.values(excludeMetaFromLayers(extendedLayers)); + const annotationIndexPatterns = configuration.layers.reduce((acc, layer) => { + if (isAnnotationsLayer(layer)) { + return [...acc, layer.indexPatternId]; + } + return acc; + }, []); return { type: 'lnsXY', - layers: Object.values(excludeMetaFromLayers(extendedLayers)), - configuration: getConfiguration(model, configLayers), + layers, + configuration, + indexPatternIds: [...getIndexPatternIds(layers), ...annotationIndexPatterns], }; }; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/top_n/index.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/top_n/index.ts index 2622fadf5e753..020aaec28f573 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/top_n/index.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/top_n/index.ts @@ -8,7 +8,7 @@ import uuid from 'uuid'; import { parseTimeShift } from '@kbn/data-plugin/common'; -import { Layer } from '@kbn/visualizations-plugin/common/convert_to_lens'; +import { getIndexPatternIds, Layer } from '@kbn/visualizations-plugin/common/convert_to_lens'; import { PANEL_TYPES } from '../../../common/enums'; import { getDataViewsStart } from '../../services'; import { getDataSourceInfo } from '../lib/datasource'; @@ -48,7 +48,7 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model, timeR return null; } - const { indexPatternId, indexPattern } = await getDataSourceInfo( + const datasourceInfo = await getDataSourceInfo( model.index_pattern, model.time_field, Boolean(series.override_index_pattern), @@ -57,10 +57,17 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model, timeR dataViews ); + if (!datasourceInfo) { + return null; + } + + const { indexPatternId, indexPattern } = datasourceInfo; const reducedTimeRange = getReducedTimeRange(model, series, timeRange); // handle multiple metrics - const metricsColumns = getMetricsColumns(series, indexPattern!, seriesNum, reducedTimeRange); + const metricsColumns = getMetricsColumns(series, indexPattern!, seriesNum, { + reducedTimeRange, + }); if (!metricsColumns) { return null; } @@ -80,10 +87,15 @@ export const convertToLens: ConvertTsvbToLensVisualization = async (model, timeR } const configLayers = await getLayers(extendedLayers, model, dataViews); + if (configLayers === null) { + return null; + } + const layers = Object.values(excludeMetaFromLayers(extendedLayers)); return { type: 'lnsXY', - layers: Object.values(excludeMetaFromLayers(extendedLayers)), + layers, configuration: getConfiguration(model, configLayers), + indexPatternIds: getIndexPatternIds(layers), }; }; diff --git a/src/plugins/vis_types/timeseries/public/convert_to_lens/types.ts b/src/plugins/vis_types/timeseries/public/convert_to_lens/types.ts index acee3c2a1e83a..69a90c7864eb3 100644 --- a/src/plugins/vis_types/timeseries/public/convert_to_lens/types.ts +++ b/src/plugins/vis_types/timeseries/public/convert_to_lens/types.ts @@ -6,14 +6,18 @@ * Side Public License, v 1. */ -import { NavigateToLensContext, XYConfiguration } from '@kbn/visualizations-plugin/common'; +import { + MetricVisConfiguration, + NavigateToLensContext, + XYConfiguration, +} from '@kbn/visualizations-plugin/common'; import { TimeRange } from '@kbn/data-plugin/common'; import type { Panel } from '../../common/types'; export type ConvertTsvbToLensVisualization = ( model: Panel, timeRange?: TimeRange -) => Promise | null>; +) => Promise | null>; export interface Filter { kql?: string | { [key: string]: any } | undefined; diff --git a/src/plugins/vis_types/timeseries/public/metrics_fn.ts b/src/plugins/vis_types/timeseries/public/metrics_fn.ts index 9562e19f3f0ec..e6e2814b6e08b 100644 --- a/src/plugins/vis_types/timeseries/public/metrics_fn.ts +++ b/src/plugins/vis_types/timeseries/public/metrics_fn.ts @@ -27,6 +27,7 @@ export interface TimeseriesRenderValue { visParams: TimeseriesVisParams; syncColors: boolean; syncTooltips: boolean; + canNavigateToLens?: boolean; } export type TimeseriesExpressionFunctionDefinition = ExpressionFunctionDefinition< @@ -65,6 +66,7 @@ export const createMetricsFn = (): TimeseriesExpressionFunctionDefinition => ({ getExecutionContext, inspectorAdapters, abortSignal: expressionAbortSignal, + variables, } ) { const visParams: TimeseriesVisParams = JSON.parse(args.params); @@ -90,6 +92,7 @@ export const createMetricsFn = (): TimeseriesExpressionFunctionDefinition => ({ visData: response, syncColors, syncTooltips, + canNavigateToLens: variables.canNavigateToLens as boolean, }, }; }, diff --git a/src/plugins/vis_types/timeseries/public/metrics_type.ts b/src/plugins/vis_types/timeseries/public/metrics_type.ts index 012bdd35115f2..2e18e9c0af48e 100644 --- a/src/plugins/vis_types/timeseries/public/metrics_type.ts +++ b/src/plugins/vis_types/timeseries/public/metrics_type.ts @@ -9,7 +9,6 @@ import { i18n } from '@kbn/i18n'; import uuid from 'uuid/v4'; import type { DataViewsContract, DataView } from '@kbn/data-views-plugin/public'; -import { TimeRange } from '@kbn/data-plugin/common'; import { Vis, VIS_EVENT_TO_TRIGGER, @@ -169,8 +168,19 @@ export const metricsVisDefinition: VisTypeDefinition< } return []; }, - navigateToLens: async (params?: VisParams, timeRange?: TimeRange) => - params ? await convertTSVBtoLensConfiguration(params as Panel, timeRange) : null, + getExpressionVariables: async (vis, timeFilter) => { + return { + canNavigateToLens: Boolean( + vis?.params + ? await convertTSVBtoLensConfiguration(vis.params as Panel, timeFilter?.getAbsoluteTime()) + : null + ), + }; + }, + navigateToLens: async (vis, timeFilter) => + vis?.params + ? await convertTSVBtoLensConfiguration(vis?.params as Panel, timeFilter?.getAbsoluteTime()) + : null, inspectorAdapters: () => ({ requests: new RequestAdapter(), diff --git a/src/plugins/vis_types/timeseries/public/timeseries_vis_renderer.tsx b/src/plugins/vis_types/timeseries/public/timeseries_vis_renderer.tsx index 60b651f2df21b..4d64e46356c0d 100644 --- a/src/plugins/vis_types/timeseries/public/timeseries_vis_renderer.tsx +++ b/src/plugins/vis_types/timeseries/public/timeseries_vis_renderer.tsx @@ -62,12 +62,9 @@ export const getTimeseriesVisRenderer: (deps: { handlers.onDestroy(() => { unmountComponentAtNode(domNode); }); - const { visParams: model, visData, syncColors, syncTooltips } = config; + const { visParams: model, visData, syncColors, syncTooltips, canNavigateToLens } = config; const showNoResult = !checkIfDataExists(visData, model); - const { convertTSVBtoLensConfiguration } = await import('./convert_to_lens'); - const canNavigateToLens = await convertTSVBtoLensConfiguration(model); - const renderComplete = () => { const usageCollection = getUsageCollectionStart(); const containerType = extractContainerType(handlers.getExecutionContext()); diff --git a/src/plugins/vis_types/vislib/public/__snapshots__/to_ast.test.ts.snap b/src/plugins/vis_types/vislib/public/__snapshots__/to_ast.test.ts.snap index 6d20088dbff32..a3566ff97e799 100644 --- a/src/plugins/vis_types/vislib/public/__snapshots__/to_ast.test.ts.snap +++ b/src/plugins/vis_types/vislib/public/__snapshots__/to_ast.test.ts.snap @@ -8,7 +8,7 @@ Object { "area", ], "visConfig": Array [ - "{\\"type\\":\\"area\\",\\"grid\\":{\\"categoryLines\\":false,\\"style\\":{\\"color\\":\\"#eee\\"}},\\"categoryAxes\\":[{\\"id\\":\\"CategoryAxis-1\\",\\"type\\":\\"category\\",\\"position\\":\\"bottom\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\"},\\"labels\\":{\\"show\\":true,\\"truncate\\":100},\\"title\\":{}}],\\"valueAxes\\":[{\\"id\\":\\"ValueAxis-1\\",\\"name\\":\\"LeftAxis-1\\",\\"type\\":\\"value\\",\\"position\\":\\"left\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\",\\"mode\\":\\"normal\\"},\\"labels\\":{\\"show\\":true,\\"rotate\\":0,\\"filter\\":false,\\"truncate\\":100},\\"title\\":{\\"text\\":\\"Sum of total_quantity\\"}}],\\"seriesParams\\":[{\\"show\\":\\"true\\",\\"type\\":\\"area\\",\\"mode\\":\\"stacked\\",\\"data\\":{\\"label\\":\\"Sum of total_quantity\\",\\"id\\":\\"1\\"},\\"drawLinesBetweenPoints\\":true,\\"showCircles\\":true,\\"circlesRadius\\":5,\\"interpolate\\":\\"linear\\",\\"valueAxis\\":\\"ValueAxis-1\\"}],\\"addTooltip\\":true,\\"addLegend\\":true,\\"legendPosition\\":\\"top\\",\\"legendSize\\":\\"small\\",\\"times\\":[],\\"addTimeMarker\\":false,\\"truncateLegend\\":true,\\"maxLegendLines\\":1,\\"thresholdLine\\":{\\"show\\":false,\\"value\\":10,\\"width\\":1,\\"style\\":\\"full\\",\\"color\\":\\"#E7664C\\"},\\"palette\\":{\\"name\\":\\"default\\"},\\"labels\\":{},\\"dimensions\\":{\\"x\\":{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"date\\",\\"params\\":{\\"pattern\\":\\"HH:mm:ss.SSS\\"}},\\"params\\":{}},\\"y\\":[{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\",\\"params\\":{\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}],\\"series\\":[{\\"accessor\\":2,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}]}}", + "{\\"type\\":\\"area\\",\\"grid\\":{\\"categoryLines\\":false,\\"style\\":{\\"color\\":\\"#eee\\"}},\\"categoryAxes\\":[{\\"id\\":\\"CategoryAxis-1\\",\\"type\\":\\"category\\",\\"position\\":\\"bottom\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\"},\\"labels\\":{\\"show\\":true,\\"truncate\\":100},\\"title\\":{}}],\\"valueAxes\\":[{\\"id\\":\\"ValueAxis-1\\",\\"name\\":\\"LeftAxis-1\\",\\"type\\":\\"value\\",\\"position\\":\\"left\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\",\\"mode\\":\\"normal\\"},\\"labels\\":{\\"show\\":true,\\"rotate\\":0,\\"filter\\":false,\\"truncate\\":100},\\"title\\":{\\"text\\":\\"Sum of total_quantity\\"}}],\\"seriesParams\\":[{\\"show\\":\\"true\\",\\"type\\":\\"area\\",\\"mode\\":\\"stacked\\",\\"data\\":{\\"label\\":\\"Sum of total_quantity\\",\\"id\\":\\"1\\"},\\"drawLinesBetweenPoints\\":true,\\"showCircles\\":true,\\"circlesRadius\\":5,\\"interpolate\\":\\"linear\\",\\"valueAxis\\":\\"ValueAxis-1\\"}],\\"addTooltip\\":true,\\"addLegend\\":true,\\"legendPosition\\":\\"top\\",\\"legendSize\\":\\"small\\",\\"times\\":[],\\"addTimeMarker\\":false,\\"truncateLegend\\":true,\\"maxLegendLines\\":1,\\"thresholdLine\\":{\\"show\\":false,\\"value\\":10,\\"width\\":1,\\"style\\":\\"full\\",\\"color\\":\\"#E7664C\\"},\\"palette\\":{\\"name\\":\\"default\\"},\\"labels\\":{},\\"dimensions\\":{\\"x\\":{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"date\\",\\"params\\":{\\"pattern\\":\\"HH:mm:ss.SSS\\"}},\\"params\\":{\\"date\\":true,\\"intervalESUnit\\":\\"h\\",\\"intervalESValue\\":\\"1\\",\\"interval\\":3600000,\\"format\\":{},\\"bounds\\":{}},\\"aggType\\":\\"date_histogram\\",\\"aggId\\":\\"2\\",\\"aggParams\\":{\\"field\\":\\"order_date\\",\\"timeRange\\":{},\\"useNormalizedEsInterval\\":true,\\"scaleMetricValues\\":false,\\"interval\\":\\"auto\\",\\"drop_partials\\":false,\\"min_doc_count\\":1,\\"extended_bounds\\":{}}},\\"y\\":[{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\",\\"params\\":{\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{},\\"aggType\\":\\"sum\\",\\"aggId\\":\\"1\\",\\"aggParams\\":{\\"field\\":\\"total_quantity\\"}}],\\"series\\":[{\\"accessor\\":2,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{},\\"aggType\\":\\"terms\\",\\"aggId\\":\\"3\\",\\"aggParams\\":{\\"field\\":\\"category.keyword\\",\\"orderBy\\":\\"1\\",\\"order\\":\\"desc\\",\\"size\\":5,\\"otherBucket\\":false,\\"otherBucketLabel\\":\\"Other\\",\\"missingBucket\\":false,\\"missingBucketLabel\\":\\"Missing\\"}}]}}", ], }, "getArgument": [Function], diff --git a/src/plugins/vis_types/vislib/public/__snapshots__/to_ast_pie.test.ts.snap b/src/plugins/vis_types/vislib/public/__snapshots__/to_ast_pie.test.ts.snap index 80e52d95be5c9..cf9e9aad3a0c4 100644 --- a/src/plugins/vis_types/vislib/public/__snapshots__/to_ast_pie.test.ts.snap +++ b/src/plugins/vis_types/vislib/public/__snapshots__/to_ast_pie.test.ts.snap @@ -5,7 +5,7 @@ Object { "addArgument": [Function], "arguments": Object { "visConfig": Array [ - "{\\"type\\":\\"pie\\",\\"addTooltip\\":true,\\"legendDisplay\\":\\"show\\",\\"legendPosition\\":\\"right\\",\\"legendSize\\":\\"large\\",\\"isDonut\\":true,\\"labels\\":{\\"show\\":true,\\"values\\":true,\\"last_level\\":true,\\"truncate\\":100},\\"dimensions\\":{\\"metric\\":{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\"},\\"params\\":{}},\\"buckets\\":[{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}]}}", + "{\\"type\\":\\"pie\\",\\"addTooltip\\":true,\\"legendDisplay\\":\\"show\\",\\"legendPosition\\":\\"right\\",\\"legendSize\\":\\"large\\",\\"isDonut\\":true,\\"labels\\":{\\"show\\":true,\\"values\\":true,\\"last_level\\":true,\\"truncate\\":100},\\"dimensions\\":{\\"metric\\":{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\"},\\"params\\":{},\\"aggType\\":\\"count\\",\\"aggId\\":\\"1\\",\\"aggParams\\":{}},\\"buckets\\":[{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{},\\"aggType\\":\\"terms\\",\\"aggId\\":\\"2\\",\\"aggParams\\":{\\"field\\":\\"Carrier\\",\\"orderBy\\":\\"1\\",\\"order\\":\\"desc\\",\\"size\\":5,\\"otherBucket\\":false,\\"otherBucketLabel\\":\\"Other\\",\\"missingBucket\\":false,\\"missingBucketLabel\\":\\"Missing\\"}}]}}", ], }, "getArgument": [Function], diff --git a/src/plugins/vis_types/xy/public/sample_vis.test.mocks.ts b/src/plugins/vis_types/xy/public/sample_vis.test.mocks.ts index d1e4af6b4b6c8..e55debd7c77ba 100644 --- a/src/plugins/vis_types/xy/public/sample_vis.test.mocks.ts +++ b/src/plugins/vis_types/xy/public/sample_vis.test.mocks.ts @@ -1838,7 +1838,7 @@ export const sampleAreaVis = { { id: '1', enabled: true, - type: 'sum', + type: { name: 'sum' }, params: { field: 'total_quantity', }, @@ -1857,7 +1857,7 @@ export const sampleAreaVis = { { id: '2', enabled: true, - type: 'date_histogram', + type: { name: 'date_histogram' }, params: { field: 'order_date', timeRange: { @@ -1872,6 +1872,14 @@ export const sampleAreaVis = { extended_bounds: {}, }, schema: 'segment', + buckets: { + getInterval: () => ({ esUnit: 'h', esValue: '1' }), + getScaledDateFormat: () => ({}), + getBounds: () => ({}), + setBounds: () => {}, + setInterval: () => {}, + }, + fieldIsTimeField: () => false, toSerializedFieldFormat: () => ({ id: 'date', params: { pattern: 'HH:mm:ss.SSS' }, @@ -1880,7 +1888,7 @@ export const sampleAreaVis = { { id: '3', enabled: true, - type: 'terms', + type: { name: 'terms' }, params: { field: 'category.keyword', orderBy: '1', diff --git a/src/plugins/visualizations/common/constants.ts b/src/plugins/visualizations/common/constants.ts index ea695e6bdca02..5fd21e426da8d 100644 --- a/src/plugins/visualizations/common/constants.ts +++ b/src/plugins/visualizations/common/constants.ts @@ -6,6 +6,8 @@ * Side Public License, v 1. */ +import { METRIC_TYPES, BUCKET_TYPES } from '@kbn/data-plugin/common'; + export const VISUALIZE_ENABLE_LABS_SETTING = 'visualize:enableLabs'; export const SAVED_OBJECTS_LIMIT_SETTING = 'savedObjects:listingLimit'; export const SAVED_OBJECTS_PER_PAGE_SETTING = 'savedObjects:perPage'; @@ -44,3 +46,8 @@ export const LegendSizeToPixels = { } as const; export const DEFAULT_LEGEND_SIZE = LegendSize.MEDIUM; + +export const SUPPORTED_AGGREGATIONS = [ + ...Object.values(METRIC_TYPES), + ...Object.values(BUCKET_TYPES), +] as const; diff --git a/src/plugins/visualizations/common/convert_to_lens/constants.ts b/src/plugins/visualizations/common/convert_to_lens/constants.ts index bd312129c9779..12ed815bc7247 100644 --- a/src/plugins/visualizations/common/convert_to_lens/constants.ts +++ b/src/plugins/visualizations/common/convert_to_lens/constants.ts @@ -35,3 +35,72 @@ export const OperationsWithReferences = { } as const; export const Operations = { ...OperationsWithSourceField, ...OperationsWithReferences } as const; + +export const PartitionChartTypes = { + PIE: 'pie', + DONUT: 'donut', + TREEMAP: 'treemap', + MOSAIC: 'mosaic', + WAFFLE: 'waffle', +} as const; + +export const CategoryDisplayTypes = { + DEFAULT: 'default', + INSIDE: 'inside', + HIDE: 'hide', +} as const; + +export const NumberDisplayTypes = { + HIDDEN: 'hidden', + PERCENT: 'percent', + VALUE: 'value', +} as const; + +export const LegendDisplayTypes = { + DEFAULT: 'default', + SHOW: 'show', + HIDE: 'hide', +} as const; + +export const LayerTypes = { + DATA: 'data', + REFERENCELINE: 'referenceLine', + ANNOTATIONS: 'annotations', +} as const; + +export const XYCurveTypes = { + LINEAR: 'LINEAR', + CURVE_MONOTONE_X: 'CURVE_MONOTONE_X', + CURVE_STEP_AFTER: 'CURVE_STEP_AFTER', +} as const; + +export const YAxisModes = { + AUTO: 'auto', + LEFT: 'left', + RIGHT: 'right', + BOTTOM: 'bottom', +} as const; + +export const SeriesTypes = { + BAR: 'bar', + LINE: 'line', + AREA: 'area', + BAR_STACKED: 'bar_stacked', + AREA_STACKED: 'area_stacked', + BAR_HORIZONTAL: 'bar_horizontal', + BAR_PERCENTAGE_STACKED: 'bar_percentage_stacked', + BAR_HORIZONTAL_STACKED: 'bar_horizontal_stacked', + AREA_PERCENTAGE_STACKED: 'area_percentage_stacked', + BAR_HORIZONTAL_PERCENTAGE_STACKED: 'bar_horizontal_percentage_stacked', +} as const; + +export const FillTypes = { + NONE: 'none', + ABOVE: 'above', + BELOW: 'below', +} as const; + +export const RANGE_MODES = { + Range: 'range', + Histogram: 'histogram', +} as const; diff --git a/src/plugins/visualizations/common/convert_to_lens/index.ts b/src/plugins/visualizations/common/convert_to_lens/index.ts index d336872cff6bb..16e1ad990e31b 100644 --- a/src/plugins/visualizations/common/convert_to_lens/index.ts +++ b/src/plugins/visualizations/common/convert_to_lens/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +export type { AggBasedColumn } from './lib/convert/types'; export * from './types'; export * from './constants'; export * from './utils'; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.test.ts new file mode 100644 index 0000000000000..f0a8e4d32f7c3 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.test.ts @@ -0,0 +1,267 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { BUCKET_TYPES, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { convertBucketToColumns } from '.'; +import { DateHistogramColumn, FiltersColumn, RangeColumn, TermsColumn } from '../../types'; +import { AggBasedColumn, SchemaConfig } from '../../..'; + +const mockConvertToDateHistogramColumn = jest.fn(); +const mockConvertToFiltersColumn = jest.fn(); +const mockConvertToTermsColumn = jest.fn(); +const mockConvertToRangeColumn = jest.fn(); + +jest.mock('../convert', () => ({ + convertToDateHistogramColumn: jest.fn(() => mockConvertToDateHistogramColumn()), + convertToFiltersColumn: jest.fn(() => mockConvertToFiltersColumn()), + convertToTermsColumn: jest.fn(() => mockConvertToTermsColumn()), + convertToRangeColumn: jest.fn(() => mockConvertToRangeColumn()), +})); + +describe('convertBucketToColumns', () => { + const field = stubLogstashDataView.fields[0].name; + const dateField = stubLogstashDataView.fields.find((f) => f.type === 'date')!.name; + const bucketAggs: SchemaConfig[] = [ + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.FILTERS, + aggParams: { + filters: [], + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.DATE_HISTOGRAM, + aggParams: { + field, + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.TERMS, + aggParams: { + field, + orderBy: '_key', + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.TERMS, + aggParams: { + field: dateField, + orderBy: '_key', + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.HISTOGRAM, + aggParams: { + field, + interval: '1h', + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.RANGE, + aggParams: { + field, + }, + }, + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: BUCKET_TYPES.DATE_RANGE, + aggParams: { + field, + }, + }, + ]; + const aggs: Array> = [ + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + }, + ]; + const metricColumns: AggBasedColumn[] = [ + { + columnId: 'column-1', + operationType: 'average', + isBucketed: false, + isSplit: false, + sourceField: field, + dataType: 'number', + params: {}, + meta: { + aggId: '1', + }, + }, + ]; + + afterEach(() => { + jest.clearAllMocks(); + }); + + test.each< + [ + string, + Parameters, + () => void, + Partial | null + ] + >([ + [ + 'null if bucket agg type is not supported', + [{ dataView: stubLogstashDataView, agg: bucketAggs[6], aggs, metricColumns }], + () => {}, + null, + ], + [ + 'null if bucket agg does not have aggParams', + [ + { + dataView: stubLogstashDataView, + agg: { ...bucketAggs[0], aggParams: undefined }, + aggs, + metricColumns, + }, + ], + () => {}, + null, + ], + [ + 'filters column if bucket agg is valid filters agg', + [{ dataView: stubLogstashDataView, agg: bucketAggs[0], aggs, metricColumns }], + () => { + mockConvertToFiltersColumn.mockReturnValue({ + operationType: 'filters', + }); + }, + { + operationType: 'filters', + }, + ], + [ + 'date histogram column if bucket agg is valid date histogram agg', + [{ dataView: stubLogstashDataView, agg: bucketAggs[1], aggs, metricColumns }], + () => { + mockConvertToDateHistogramColumn.mockReturnValue({ + operationType: 'date_histogram', + }); + }, + { + operationType: 'date_histogram', + }, + ], + [ + 'date histogram column if bucket agg is valid terms agg with date field', + [{ dataView: stubLogstashDataView, agg: bucketAggs[3], aggs, metricColumns }], + () => { + mockConvertToDateHistogramColumn.mockReturnValue({ + operationType: 'date_histogram', + }); + }, + { + operationType: 'date_histogram', + }, + ], + [ + 'terms column if bucket agg is valid terms agg with no date field', + [{ dataView: stubLogstashDataView, agg: bucketAggs[2], aggs, metricColumns }], + () => { + mockConvertToTermsColumn.mockReturnValue({ + operationType: 'terms', + }); + }, + { + operationType: 'terms', + }, + ], + [ + 'range column if bucket agg is valid histogram agg', + [{ dataView: stubLogstashDataView, agg: bucketAggs[4], aggs, metricColumns }], + () => { + mockConvertToRangeColumn.mockReturnValue({ + operationType: 'range', + }); + }, + { + operationType: 'range', + }, + ], + [ + 'range column if bucket agg is valid range agg', + [{ dataView: stubLogstashDataView, agg: bucketAggs[5], aggs, metricColumns }], + () => { + mockConvertToRangeColumn.mockReturnValue({ + operationType: 'range', + }); + }, + { + operationType: 'range', + }, + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(convertBucketToColumns(...input)).toBeNull(); + } else { + expect(convertBucketToColumns(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.ts b/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.ts new file mode 100644 index 0000000000000..0f929189f3369 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/buckets/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { BUCKET_TYPES, IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import type { DataView } from '@kbn/data-views-plugin/common'; +import { convertToSchemaConfig } from '../../../vis_schemas'; +import { SchemaConfig } from '../../..'; +import { + AggBasedColumn, + CommonBucketConverterArgs, + convertToDateHistogramColumn, + convertToFiltersColumn, + convertToTermsColumn, + convertToRangeColumn, +} from '../convert'; +import { getFieldNameFromField, getLabel, isSchemaConfig } from '../utils'; + +export type BucketAggs = + | BUCKET_TYPES.TERMS + | BUCKET_TYPES.DATE_HISTOGRAM + | BUCKET_TYPES.FILTERS + | BUCKET_TYPES.RANGE + | BUCKET_TYPES.HISTOGRAM; +const SUPPORTED_BUCKETS: string[] = [ + BUCKET_TYPES.TERMS, + BUCKET_TYPES.DATE_HISTOGRAM, + BUCKET_TYPES.FILTERS, + BUCKET_TYPES.RANGE, + BUCKET_TYPES.HISTOGRAM, +]; + +const isSupportedBucketAgg = (agg: SchemaConfig): agg is SchemaConfig => { + return SUPPORTED_BUCKETS.includes(agg.aggType); +}; + +export const getBucketColumns = ( + { agg, dataView, metricColumns, aggs }: CommonBucketConverterArgs, + { + label, + isSplit = false, + dropEmptyRowsInDateHistogram = false, + }: { label: string; isSplit: boolean; dropEmptyRowsInDateHistogram: boolean } +) => { + if (!agg.aggParams) { + return null; + } + switch (agg.aggType) { + case BUCKET_TYPES.DATE_HISTOGRAM: + return convertToDateHistogramColumn( + agg.aggId ?? '', + agg.aggParams, + dataView, + isSplit, + dropEmptyRowsInDateHistogram + ); + case BUCKET_TYPES.FILTERS: + return convertToFiltersColumn(agg.aggId ?? '', agg.aggParams, isSplit); + case BUCKET_TYPES.RANGE: + case BUCKET_TYPES.HISTOGRAM: + return convertToRangeColumn(agg.aggId ?? '', agg.aggParams, label, dataView, isSplit); + case BUCKET_TYPES.TERMS: + const fieldName = getFieldNameFromField(agg.aggParams.field); + if (!fieldName) { + return null; + } + const field = dataView.getFieldByName(fieldName); + + if (!field) { + return null; + } + if (field.type !== 'date') { + return convertToTermsColumn( + agg.aggId ?? '', + { agg, dataView, metricColumns, aggs }, + label, + isSplit + ); + } else { + return convertToDateHistogramColumn( + agg.aggId ?? '', + { + field: fieldName, + }, + dataView, + isSplit, + dropEmptyRowsInDateHistogram + ); + } + } + + return null; +}; + +export const convertBucketToColumns = ( + { + agg, + dataView, + metricColumns, + aggs, + }: { + agg: SchemaConfig | IAggConfig; + dataView: DataView; + metricColumns: AggBasedColumn[]; + aggs: Array>; + }, + isSplit: boolean = false, + dropEmptyRowsInDateHistogram: boolean = false +) => { + const currentAgg = isSchemaConfig(agg) ? agg : convertToSchemaConfig(agg); + if (!currentAgg.aggParams || !isSupportedBucketAgg(currentAgg)) { + return null; + } + return getBucketColumns( + { agg: currentAgg, dataView, metricColumns, aggs }, + { + label: getLabel(currentAgg), + isSplit, + dropEmptyRowsInDateHistogram, + } + ); +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.test.ts new file mode 100644 index 0000000000000..74e9f2a57a9fe --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/public'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { createColumn } from './column'; +import { GeneralColumnWithMeta } from './types'; + +describe('createColumn', () => { + const field = stubLogstashDataView.fields[0]; + const aggId = `some-id`; + const customLabel = 'some-custom-label'; + const label = 'some label'; + const timeShift = '1h'; + + const agg: SchemaConfig = { + accessor: 0, + label, + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggId, + aggParams: { + field: field.name, + }, + }; + + const aggWithCustomLabel: SchemaConfig = { + ...agg, + aggParams: { + field: field.name, + customLabel, + }, + }; + + const aggWithTimeShift: SchemaConfig = { + ...agg, + aggParams: { + field: field.name, + timeShift, + }, + }; + + const extraColumnFields = { isBucketed: true, isSplit: true, reducedTimeRange: '1m' }; + + test.each<[string, Parameters, Partial]>([ + [ + 'with default params', + [agg, field], + { + dataType: 'number', + isBucketed: false, + isSplit: false, + label, + meta: { aggId }, + }, + ], + [ + 'with custom label', + [aggWithCustomLabel, field], + { + dataType: 'number', + isBucketed: false, + isSplit: false, + label: customLabel, + meta: { aggId }, + }, + ], + [ + 'with timeShift', + [aggWithTimeShift, field], + { + dataType: 'number', + isBucketed: false, + isSplit: false, + label, + meta: { aggId }, + timeShift, + }, + ], + [ + 'with extra column fields', + [agg, field, extraColumnFields], + { + dataType: 'number', + isBucketed: extraColumnFields.isBucketed, + isSplit: extraColumnFields.isSplit, + reducedTimeRange: extraColumnFields.reducedTimeRange, + label, + meta: { aggId }, + }, + ], + ])('should create column by agg %s', (_, input, expected) => { + expect(createColumn(...input)).toEqual(expect.objectContaining(expected)); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.ts new file mode 100644 index 0000000000000..b1ac46dd36a20 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/column.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import uuid from 'uuid'; +import type { DataViewField } from '@kbn/data-views-plugin/common'; +import { DataType, FormatParams } from '../../types'; +import { SchemaConfig } from '../../../types'; +import { AggId, ExtraColumnFields, GeneralColumnWithMeta } from './types'; +import { getLabel } from '../utils'; + +export const createAggregationId = (agg: SchemaConfig): AggId => `${agg.aggId}`; + +export const getFormat = (): FormatParams => { + return {}; +}; + +export const createColumn = ( + agg: SchemaConfig, + field?: DataViewField, + { isBucketed = false, isSplit = false, reducedTimeRange }: ExtraColumnFields = {} +): GeneralColumnWithMeta => ({ + columnId: uuid(), + dataType: (field?.type as DataType) ?? undefined, + label: getLabel(agg), + isBucketed, + isSplit, + reducedTimeRange, + timeShift: agg.aggParams?.timeShift, + meta: { aggId: createAggregationId(agg) }, +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/constants.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/constants.ts new file mode 100644 index 0000000000000..b44a2e2f243e4 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/constants.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; + +export const PARENT_PIPELINE_AGGS: string[] = [ + METRIC_TYPES.CUMULATIVE_SUM, + METRIC_TYPES.DERIVATIVE, + METRIC_TYPES.MOVING_FN, +]; + +export const SIBLING_PIPELINE_AGGS: string[] = [ + METRIC_TYPES.AVG_BUCKET, + METRIC_TYPES.MAX_BUCKET, + METRIC_TYPES.MIN_BUCKET, + METRIC_TYPES.SUM_BUCKET, +]; + +export const PIPELINE_AGGS = [...PARENT_PIPELINE_AGGS, ...SIBLING_PIPELINE_AGGS]; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.test.ts new file mode 100644 index 0000000000000..897e5f876542b --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.test.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { AggParamsDateHistogram } from '@kbn/data-plugin/common'; +import { convertToDateHistogramColumn } from './date_histogram'; +import { DateHistogramColumn } from './types'; +import { DataType } from '../../types'; + +describe('convertToDateHistogramColumn', () => { + const aggId = `some-id`; + const timeShift = '1h'; + const aggParams: AggParamsDateHistogram = { + interval: '1d', + drop_partials: true, + field: stubLogstashDataView.fields[0].name, + }; + + test.each< + [string, Parameters, Partial | null] + >([ + [ + 'date histogram column if field is provided', + [aggId, aggParams, stubLogstashDataView, false, false], + { + dataType: stubLogstashDataView.fields[0].type as DataType, + isBucketed: true, + isSplit: false, + timeShift: undefined, + sourceField: stubLogstashDataView.fields[0].name, + meta: { aggId }, + params: { + interval: '1d', + includeEmptyRows: true, + dropPartials: true, + }, + }, + ], + [ + 'null if field is not provided', + [aggId, { interval: '1d', field: undefined }, stubLogstashDataView, false, false], + null, + ], + [ + 'date histogram column with isSplit and timeShift if specified', + [aggId, { ...aggParams, timeShift }, stubLogstashDataView, true, false], + { + dataType: stubLogstashDataView.fields[0].type as DataType, + isBucketed: true, + isSplit: true, + sourceField: stubLogstashDataView.fields[0].name, + timeShift, + meta: { aggId }, + params: { + interval: '1d', + includeEmptyRows: true, + dropPartials: true, + }, + }, + ], + [ + 'date histogram column with dropEmptyRowsInDateHistogram if specified', + [aggId, aggParams, stubLogstashDataView, true, true], + { + dataType: stubLogstashDataView.fields[0].type as DataType, + isBucketed: true, + isSplit: true, + sourceField: stubLogstashDataView.fields[0].name, + timeShift: undefined, + meta: { aggId }, + params: { + interval: '1d', + includeEmptyRows: false, + dropPartials: true, + }, + }, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToDateHistogramColumn(...input)).toBeNull(); + } else { + expect(convertToDateHistogramColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.ts new file mode 100644 index 0000000000000..5a00ebdd90aa3 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/date_histogram.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggParamsDateHistogram } from '@kbn/data-plugin/common'; +import type { DataView } from '@kbn/data-views-plugin/common'; +import uuid from 'uuid'; +import { DataType, DateHistogramParams } from '../../types'; +import { getFieldNameFromField } from '../utils'; +import { DateHistogramColumn } from './types'; + +export const getLabel = (aggParams: AggParamsDateHistogram, fieldName: string) => { + return aggParams && 'customLabel' in aggParams ? aggParams.customLabel ?? fieldName : fieldName; +}; + +export const convertToDateHistogramParams = ( + aggParams: AggParamsDateHistogram, + dropEmptyRowsInDateHistogram: boolean +): DateHistogramParams => { + return { + interval: aggParams.interval ?? 'auto', + dropPartials: aggParams.drop_partials, + includeEmptyRows: !dropEmptyRowsInDateHistogram, + }; +}; + +export const convertToDateHistogramColumn = ( + aggId: string, + aggParams: AggParamsDateHistogram, + dataView: DataView, + isSplit: boolean, + dropEmptyRowsInDateHistogram: boolean +): DateHistogramColumn | null => { + const dateFieldName = getFieldNameFromField(aggParams.field); + + if (!dateFieldName) { + return null; + } + + const dateField = dataView.getFieldByName(dateFieldName); + if (!dateField) { + return null; + } + + const params = convertToDateHistogramParams(aggParams, dropEmptyRowsInDateHistogram); + const label = getLabel(aggParams, dateFieldName); + + return { + columnId: uuid(), + label, + operationType: 'date_histogram', + dataType: dateField.type as DataType, + isBucketed: true, + isSplit, + sourceField: dateField.name, + params, + timeShift: aggParams.timeShift, + meta: { aggId }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.test.ts new file mode 100644 index 0000000000000..1de1dbc9b312d --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggParamsFilters } from '@kbn/data-plugin/common'; +import { convertToFiltersColumn } from './filters'; +import { FiltersColumn } from './types'; + +describe('convertToFiltersColumn', () => { + const aggId = `some-id`; + const timeShift = '1h'; + const filters = [{ input: { language: 'lucene', query: 'some other query' }, label: 'split' }]; + const aggParams: AggParamsFilters = { + filters, + }; + + test.each<[string, Parameters, Partial | null]>([ + [ + 'filters column if filters are provided', + [aggId, aggParams], + { + dataType: 'string', + isBucketed: true, + isSplit: false, + timeShift: undefined, + meta: { aggId }, + params: { filters: aggParams.filters! }, + }, + ], + ['null if filters are not provided', [aggId, {}], null], + [ + 'filters column with isSplit and timeShift if specified', + [aggId, { ...aggParams, timeShift }, true], + { + dataType: 'string', + isBucketed: true, + isSplit: true, + timeShift, + meta: { aggId }, + params: { filters: aggParams.filters! }, + }, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToFiltersColumn(...input)).toBeNull(); + } else { + expect(convertToFiltersColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.ts new file mode 100644 index 0000000000000..416efdc53a72d --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/filters.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggParamsFilters } from '@kbn/data-plugin/common'; +import uuid from 'uuid'; +import { FiltersColumn } from './types'; + +export const convertToFiltersColumn = ( + aggId: string, + aggParams: AggParamsFilters, + isSplit: boolean = false +): FiltersColumn | null => { + if (!aggParams.filters?.length) { + return null; + } + + return { + columnId: uuid(), + operationType: 'filters', + dataType: 'string', + isBucketed: true, + isSplit, + params: { + filters: aggParams.filters ?? [], + }, + timeShift: aggParams.timeShift, + meta: { aggId }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.test.ts new file mode 100644 index 0000000000000..bbde6a04f1a2f --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { createFormulaColumn } from './formula'; + +describe('createFormulaColumn', () => { + const aggId = `some-id`; + const label = 'some label'; + const agg: SchemaConfig = { + accessor: 0, + label, + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.CUMULATIVE_SUM, + aggId, + aggParams: { + customMetric: { + id: 'some-id-metric', + enabled: true, + type: { name: METRIC_TYPES.AVG }, + params: { + field: stubLogstashDataView.fields[0], + }, + } as IAggConfig, + }, + }; + test('should return formula column', () => { + expect(createFormulaColumn('test-formula', agg)).toEqual( + expect.objectContaining({ + isBucketed: false, + isSplit: false, + meta: { + aggId, + }, + operationType: 'formula', + params: { + formula: 'test-formula', + }, + references: [], + }) + ); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.ts new file mode 100644 index 0000000000000..0ad2a4072e19d --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/formula.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { SchemaConfig } from '../../..'; +import { FormulaParams } from '../../types'; +import { createAggregationId, createColumn, getFormat } from './column'; +import { FormulaColumn } from './types'; + +const convertToFormulaParams = (formula: string): FormulaParams => ({ + formula, +}); + +export const createFormulaColumn = (formula: string, agg: SchemaConfig): FormulaColumn | null => { + const params = convertToFormulaParams(formula); + return { + operationType: 'formula', + ...createColumn(agg), + references: [], + params: { ...params, ...getFormat() }, + timeShift: agg.aggParams?.timeShift, + meta: { aggId: createAggregationId(agg) }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/index.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/index.ts new file mode 100644 index 0000000000000..b77ea6b97209a --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/index.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export * from './column'; +export * from './date_histogram'; +export * from './filters'; +export * from './formula'; +export * from './metric'; +export * from './parent_pipeline'; +export * from './percentile_rank'; +export * from './percentile'; +export * from './sibling_pipeline'; +export * from './std_deviation'; +export * from './terms'; +export * from './types'; +export * from './last_value'; +export * from './range'; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.test.ts new file mode 100644 index 0000000000000..55ba1e8b5e09d --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.test.ts @@ -0,0 +1,120 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggParamsTopHit, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertToLastValueColumn } from './last_value'; +import { FiltersColumn } from './types'; + +const mockGetFieldNameFromField = jest.fn(); +const mockGetFieldByName = jest.fn(); +const mockGetLabel = jest.fn(); + +jest.mock('../utils', () => ({ + getFieldNameFromField: jest.fn(() => mockGetFieldNameFromField()), + getLabel: jest.fn(() => mockGetLabel()), +})); + +describe('convertToLastValueColumn', () => { + const dataView = stubLogstashDataView; + const sortField = dataView.fields[0]; + + const topHitAggParams: AggParamsTopHit = { + sortOrder: { + value: 'desc', + text: 'some text', + }, + sortField, + field: '', + aggregate: 'min', + size: 1, + }; + + const topHitAgg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.TOP_HITS, + aggParams: topHitAggParams, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockGetFieldNameFromField.mockReturnValue(dataView.fields[0]); + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + mockGetLabel.mockReturnValue('someLabel'); + dataView.getFieldByName = mockGetFieldByName; + }); + + test.each<[string, Parameters, Partial | null]>([ + [ + 'null if top hits size is more than 1', + [{ agg: { ...topHitAgg, aggParams: { ...topHitAgg.aggParams!, size: 2 } }, dataView }], + null, + ], + [ + 'null if top hits sord order is not desc', + [ + { + agg: { + ...topHitAgg, + aggParams: { + ...topHitAgg.aggParams!, + sortOrder: { ...topHitAgg.aggParams!.sortOrder!, value: 'asc' }, + }, + }, + dataView, + }, + ], + null, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToLastValueColumn(...input)).toBeNull(); + } else { + expect(convertToLastValueColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); + + test('should skip if top hit field is not specified', () => { + mockGetFieldNameFromField.mockReturnValue(null); + expect(convertToLastValueColumn({ agg: topHitAgg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(0); + }); + + test('should skip if top hit field is not present in index pattern', () => { + mockGetFieldByName.mockReturnValue(null); + dataView.getFieldByName = mockGetFieldByName; + + expect(convertToLastValueColumn({ agg: topHitAgg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + expect(mockGetLabel).toBeCalledTimes(0); + }); + + test('should return top hit column if top hit field is not present in index pattern', () => { + expect(convertToLastValueColumn({ agg: topHitAgg, dataView })).toEqual( + expect.objectContaining({ + dataType: 'number', + label: 'someLabel', + operationType: 'last_value', + params: { showArrayValues: true, sortField: 'bytes' }, + sourceField: 'bytes', + }) + ); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + expect(mockGetLabel).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.ts new file mode 100644 index 0000000000000..3162cf14e71c3 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/last_value.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig } from '../../..'; +import { LastValueParams } from '../../types'; +import { isFieldValid } from '../../utils'; +import { getFieldNameFromField } from '../utils'; +import { createColumn, getFormat } from './column'; +import { SUPPORTED_METRICS } from './supported_metrics'; +import { CommonColumnConverterArgs, LastValueColumn } from './types'; + +const convertToLastValueParams = ( + agg: SchemaConfig +): LastValueParams => { + return { + sortField: agg.aggParams!.sortField!.name, + showArrayValues: agg.aggType === METRIC_TYPES.TOP_HITS, + }; +}; + +export const convertToLastValueColumn = ( + { agg, dataView }: CommonColumnConverterArgs, + reducedTimeRange?: string +): LastValueColumn | null => { + const { aggParams } = agg; + + if ( + (aggParams?.size && Number(aggParams?.size) !== 1) || + aggParams?.sortOrder?.value !== 'desc' + ) { + return null; + } + + const fieldName = getFieldNameFromField(agg.aggParams!.field); + if (!fieldName) { + return null; + } + + const field = dataView.getFieldByName(fieldName); + if (!isFieldValid(field, SUPPORTED_METRICS[agg.aggType])) { + return null; + } + + if (!agg.aggParams?.sortField) { + return null; + } + + return { + operationType: 'last_value', + sourceField: field.name ?? 'document', + ...createColumn(agg, field, { reducedTimeRange }), + params: { + ...convertToLastValueParams(agg), + ...getFormat(), + }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.test.ts new file mode 100644 index 0000000000000..3be17abc46ac1 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.test.ts @@ -0,0 +1,92 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertMetricAggregationColumnWithoutSpecialParams } from './metric'; +import { SUPPORTED_METRICS } from './supported_metrics'; + +const mockGetFieldByName = jest.fn(); + +describe('convertToLastValueColumn', () => { + const dataView = stubLogstashDataView; + + const agg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggParams: { + field: dataView.fields[0].displayName, + }, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + dataView.getFieldByName = mockGetFieldByName; + }); + + test('should return null metric is not supported', () => { + expect( + convertMetricAggregationColumnWithoutSpecialParams(SUPPORTED_METRICS[METRIC_TYPES.TOP_HITS], { + agg, + dataView, + }) + ).toBeNull(); + }); + + test('should skip if field is not present and is required for the aggregation', () => { + mockGetFieldByName.mockReturnValue(null); + dataView.getFieldByName = mockGetFieldByName; + + expect( + convertMetricAggregationColumnWithoutSpecialParams(SUPPORTED_METRICS[METRIC_TYPES.AVG], { + agg, + dataView, + }) + ).toBeNull(); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return column if field is not present and is not required for the aggregation', () => { + mockGetFieldByName.mockReturnValue(null); + dataView.getFieldByName = mockGetFieldByName; + + expect( + convertMetricAggregationColumnWithoutSpecialParams(SUPPORTED_METRICS[METRIC_TYPES.COUNT], { + agg, + dataView, + }) + ).toEqual(expect.objectContaining({ operationType: 'count' })); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return column if field is present and is required for the aggregation', () => { + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + dataView.getFieldByName = mockGetFieldByName; + + expect( + convertMetricAggregationColumnWithoutSpecialParams(SUPPORTED_METRICS[METRIC_TYPES.AVG], { + agg, + dataView, + }) + ).toEqual( + expect.objectContaining({ + dataType: 'number', + operationType: 'average', + }) + ); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.ts new file mode 100644 index 0000000000000..f46adea9538dc --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/metric.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { Operations } from '../../constants'; +import { createColumn, getFormat } from './column'; +import { SupportedMetric } from './supported_metrics'; +import { CommonColumnConverterArgs, MetricsWithField } from './types'; +import { SchemaConfig } from '../../../types'; +import { + AvgColumn, + CardinalityColumn, + CountColumn, + MaxColumn, + MedianColumn, + MinColumn, + SumColumn, +} from './types'; +import { getFieldNameFromField } from '../utils'; +import { isFieldValid } from '../../utils'; + +type MetricAggregationWithoutParams = + | typeof Operations.AVERAGE + | typeof Operations.COUNT + | typeof Operations.UNIQUE_COUNT + | typeof Operations.COUNTER_RATE + | typeof Operations.MAX + | typeof Operations.MEDIAN + | typeof Operations.MIN + | typeof Operations.SUM; + +const SUPPORTED_METRICS_AGGS_WITHOUT_PARAMS: MetricAggregationWithoutParams[] = [ + Operations.AVERAGE, + Operations.COUNT, + Operations.UNIQUE_COUNT, + Operations.MAX, + Operations.MIN, + Operations.MEDIAN, + Operations.SUM, +]; + +export type MetricAggregationColumnWithoutSpecialParams = + | AvgColumn + | CountColumn + | CardinalityColumn + | MaxColumn + | MedianColumn + | MinColumn + | SumColumn; + +export type MetricsWithoutSpecialParams = + | METRIC_TYPES.AVG + | METRIC_TYPES.COUNT + | METRIC_TYPES.MAX + | METRIC_TYPES.MIN + | METRIC_TYPES.SUM + | METRIC_TYPES.MEDIAN + | METRIC_TYPES.CARDINALITY + | METRIC_TYPES.VALUE_COUNT; + +const isSupportedAggregationWithoutParams = ( + agg: string +): agg is MetricAggregationWithoutParams => { + return (SUPPORTED_METRICS_AGGS_WITHOUT_PARAMS as string[]).includes(agg); +}; + +export const isMetricWithField = ( + agg: CommonColumnConverterArgs['agg'] +): agg is SchemaConfig => { + return agg.aggType !== METRIC_TYPES.COUNT; +}; + +export const convertMetricAggregationColumnWithoutSpecialParams = ( + aggregation: SupportedMetric, + { agg, dataView }: CommonColumnConverterArgs, + reducedTimeRange?: string +): MetricAggregationColumnWithoutSpecialParams | null => { + if (!isSupportedAggregationWithoutParams(aggregation.name)) { + return null; + } + + let sourceField; + + if (isMetricWithField(agg)) { + sourceField = getFieldNameFromField(agg.aggParams?.field) ?? 'document'; + } else { + sourceField = 'document'; + } + + const field = dataView.getFieldByName(sourceField); + if (!isFieldValid(field, aggregation)) { + return null; + } + + return { + operationType: aggregation.name, + sourceField, + ...createColumn(agg, field, { + reducedTimeRange, + }), + params: { ...getFormat() }, + timeShift: agg.aggParams?.timeShift, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.test.ts new file mode 100644 index 0000000000000..c28324533c837 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.test.ts @@ -0,0 +1,438 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { FormulaColumn, AggBasedColumn } from './types'; +import { SchemaConfig } from '../../..'; +import { + convertToOtherParentPipelineAggColumns, + ParentPipelineAggColumn, + convertToCumulativeSumAggColumn, +} from './parent_pipeline'; + +const mockGetMetricFromParentPipelineAgg = jest.fn(); +const mockGetFormulaForPipelineAgg = jest.fn(); +const mockConvertMetricToColumns = jest.fn(); +const mockGetFieldByName = jest.fn(); +const mockConvertMetricAggregationColumnWithoutSpecialParams = jest.fn(); + +jest.mock('../utils', () => ({ + getMetricFromParentPipelineAgg: jest.fn(() => mockGetMetricFromParentPipelineAgg()), + getLabel: jest.fn(() => 'label'), + getFieldNameFromField: jest.fn(() => 'document'), +})); + +jest.mock('./metric', () => ({ + convertMetricAggregationColumnWithoutSpecialParams: jest.fn(() => + mockConvertMetricAggregationColumnWithoutSpecialParams() + ), +})); + +jest.mock('../metrics', () => ({ + getFormulaForPipelineAgg: jest.fn(() => mockGetFormulaForPipelineAgg()), + convertMetricToColumns: jest.fn(() => mockConvertMetricToColumns()), +})); + +describe('convertToOtherParentPipelineAggColumns', () => { + const field = stubLogstashDataView.fields[0].name; + const aggs: Array> = [ + { + aggId: '1', + aggType: METRIC_TYPES.AVG, + aggParams: { field }, + accessor: 0, + params: {}, + label: 'average', + format: {}, + }, + { + aggId: '1', + aggType: METRIC_TYPES.MOVING_FN, + aggParams: { metricAgg: '2' }, + accessor: 0, + params: {}, + label: 'Moving Average of Average', + format: {}, + }, + ]; + + afterEach(() => { + jest.clearAllMocks(); + }); + + test.each< + [ + string, + Parameters, + () => void, + Partial | [Partial, Partial] | null + ] + >([ + [ + 'null if getMetricFromParentPipelineAgg returns null', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'null if cutom metric of parent pipeline agg is not supported', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.GEO_BOUNDS, + }); + }, + null, + ], + [ + 'null if cutom metric of parent pipeline agg is sibling pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.AVG_BUCKET, + }); + }, + null, + ], + [ + 'null if cannot build formula if cutom metric of parent pipeline agg is parent pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.MOVING_FN, + }); + mockGetFormulaForPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'formula column if cutom metric of parent pipeline agg is valid parent pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.MOVING_FN, + }); + mockGetFormulaForPipelineAgg.mockReturnValue('test-formula'); + }, + { + operationType: 'formula', + params: { + formula: 'test-formula', + }, + }, + ], + [ + 'null if cutom metric of parent pipeline agg is invalid not pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.AVG, + }); + mockConvertMetricToColumns.mockReturnValue(null); + }, + null, + ], + [ + 'parent pipeline and metric columns if cutom metric of parent pipeline agg is valid not pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.AVG, + }); + mockConvertMetricToColumns.mockReturnValue([ + { + columnId: 'test-id-1', + operationType: 'average', + sourceField: field, + }, + ]); + }, + [ + { operationType: 'moving_average', references: ['test-id-1'] }, + { + columnId: 'test-id-1', + operationType: 'average', + sourceField: field, + }, + ], + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(convertToOtherParentPipelineAggColumns(...input)).toBeNull(); + } else if (Array.isArray(expected)) { + expect(convertToOtherParentPipelineAggColumns(...input)).toEqual( + expected.map(expect.objectContaining) + ); + } else { + expect(convertToOtherParentPipelineAggColumns(...input)).toEqual( + expect.objectContaining(expected) + ); + } + }); +}); + +describe('convertToCumulativeSumAggColumn', () => { + const field = stubLogstashDataView.fields[0].name; + const aggs: Array> = [ + { + aggId: '1', + aggType: METRIC_TYPES.AVG, + aggParams: { field }, + accessor: 0, + params: {}, + label: 'average', + format: {}, + }, + { + aggId: '1', + aggType: METRIC_TYPES.CUMULATIVE_SUM, + aggParams: { metricAgg: '2' }, + accessor: 0, + params: {}, + label: 'Moving Average of Average', + format: {}, + }, + ]; + + beforeEach(() => { + mockGetFieldByName.mockReturnValue({ + aggregatable: true, + type: 'number', + sourceField: 'bytes', + }); + + stubLogstashDataView.getFieldByName = mockGetFieldByName; + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test.each< + [ + string, + Parameters, + () => void, + Partial | [Partial, Partial] | null + ] + >([ + [ + 'null if cumulative sum does not have aggParams', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: { ...aggs[1], aggParams: undefined } as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'null if getMetricFromParentPipelineAgg returns null', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'null if cutom metric of parent pipeline agg is not supported', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.GEO_BOUNDS, + }); + }, + null, + ], + [ + 'null if cutom metric of parent pipeline agg is sibling pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.AVG_BUCKET, + }); + }, + null, + ], + [ + 'null if cannot build formula if cutom metric of parent pipeline agg is parent pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.MOVING_FN, + }); + mockGetFormulaForPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'formula column if cutom metric of parent pipeline agg is valid parent pipeline agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.MOVING_FN, + }); + mockGetFormulaForPipelineAgg.mockReturnValue('test-formula'); + }, + { + operationType: 'formula', + params: { + formula: 'test-formula', + }, + }, + ], + [ + 'null if cutom metric of parent pipeline agg is invalid sum or count agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.SUM, + }); + mockConvertMetricAggregationColumnWithoutSpecialParams.mockReturnValue(null); + }, + null, + ], + [ + 'cumulative sum and metric columns if cutom metric of parent pipeline agg is valid sum or count agg', + [ + { + dataView: stubLogstashDataView, + aggs, + agg: aggs[1] as SchemaConfig, + }, + ], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggId: '2-metric', + aggType: METRIC_TYPES.SUM, + }); + mockConvertMetricAggregationColumnWithoutSpecialParams.mockReturnValue({ + columnId: 'test-id-1', + operationType: 'sum', + sourceField: field, + }); + }, + [ + { operationType: 'cumulative_sum', references: ['test-id-1'] }, + { + columnId: 'test-id-1', + operationType: 'sum', + sourceField: field, + }, + ], + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(convertToCumulativeSumAggColumn(...input)).toBeNull(); + } else if (Array.isArray(expected)) { + expect(convertToCumulativeSumAggColumn(...input)).toEqual( + expected.map(expect.objectContaining) + ); + } else { + expect(convertToCumulativeSumAggColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.ts new file mode 100644 index 0000000000000..ab41ceb259adb --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/parent_pipeline.ts @@ -0,0 +1,154 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig } from '../../..'; +import { MovingAverageParams } from '../../types'; +import { convertMetricToColumns, getFormulaForPipelineAgg } from '../metrics'; +import { createColumn } from './column'; +import { createFormulaColumn } from './formula'; +import { + convertMetricAggregationColumnWithoutSpecialParams, + MetricAggregationColumnWithoutSpecialParams, +} from './metric'; +import { SUPPORTED_METRICS } from './supported_metrics'; +import { + MovingAverageColumn, + DerivativeColumn, + CumulativeSumColumn, + FormulaColumn, + ExtendedColumnConverterArgs, + OtherParentPipelineAggs, + AggBasedColumn, +} from './types'; +import { PIPELINE_AGGS, SIBLING_PIPELINE_AGGS } from './constants'; +import { getMetricFromParentPipelineAgg } from '../utils'; + +export type ParentPipelineAggColumn = MovingAverageColumn | DerivativeColumn | CumulativeSumColumn; + +export const convertToMovingAverageParams = ( + agg: SchemaConfig +): MovingAverageParams => ({ + window: agg.aggParams!.window ?? 0, +}); + +export const convertToOtherParentPipelineAggColumns = ( + { agg, dataView, aggs }: ExtendedColumnConverterArgs, + reducedTimeRange?: string +): FormulaColumn | [ParentPipelineAggColumn, AggBasedColumn] | null => { + const { aggType } = agg; + const op = SUPPORTED_METRICS[aggType]; + if (!op) { + return null; + } + + const metric = getMetricFromParentPipelineAgg(agg, aggs); + if (!metric) { + return null; + } + + const subAgg = SUPPORTED_METRICS[metric.aggType]; + + if (!subAgg) { + return null; + } + + if (SIBLING_PIPELINE_AGGS.includes(metric.aggType)) { + return null; + } + + if (PIPELINE_AGGS.includes(metric.aggType)) { + const formula = getFormulaForPipelineAgg({ agg, aggs, dataView }); + if (!formula) { + return null; + } + + return createFormulaColumn(formula, agg); + } + + const subMetric = convertMetricToColumns(metric, dataView, aggs); + + if (subMetric === null) { + return null; + } + + return [ + { + operationType: op.name, + references: [subMetric[0].columnId], + ...createColumn(agg), + params: {}, + timeShift: agg.aggParams?.timeShift, + } as ParentPipelineAggColumn, + subMetric[0], + ]; +}; + +export const convertToCumulativeSumAggColumn = ( + { agg, dataView, aggs }: ExtendedColumnConverterArgs, + reducedTimeRange?: string +): + | FormulaColumn + | [ParentPipelineAggColumn, MetricAggregationColumnWithoutSpecialParams] + | null => { + const { aggParams, aggType } = agg; + if (!aggParams) { + return null; + } + const metric = getMetricFromParentPipelineAgg(agg, aggs); + if (!metric) { + return null; + } + + const subAgg = SUPPORTED_METRICS[metric.aggType]; + + if (!subAgg) { + return null; + } + + if (SIBLING_PIPELINE_AGGS.includes(metric.aggType)) { + return null; + } + + if (metric.aggType === METRIC_TYPES.COUNT || subAgg.name === 'sum') { + // create column for sum or count + const subMetric = convertMetricAggregationColumnWithoutSpecialParams( + subAgg, + { agg: metric as SchemaConfig, dataView }, + reducedTimeRange + ); + + if (subMetric === null) { + return null; + } + + const op = SUPPORTED_METRICS[aggType]; + if (!op) { + return null; + } + + return [ + { + operationType: op.name, + ...createColumn(agg), + references: [subMetric?.columnId], + params: {}, + timeShift: agg.aggParams?.timeShift, + } as ParentPipelineAggColumn, + + subMetric, + ]; + } else { + const formula = getFormulaForPipelineAgg({ agg, aggs, dataView }); + if (!formula) { + return null; + } + + return createFormulaColumn(formula, agg); + } +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.test.ts new file mode 100644 index 0000000000000..b4cf7f141e928 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.test.ts @@ -0,0 +1,142 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertToPercentileColumn } from './percentile'; +import { PercentileColumn } from './types'; + +const mockGetFieldNameFromField = jest.fn(); +const mockGetFieldByName = jest.fn(); +const mockGetLabel = jest.fn(); +const mockGetLabelForPercentile = jest.fn(); + +jest.mock('../utils', () => ({ + getFieldNameFromField: jest.fn(() => mockGetFieldNameFromField()), + getLabel: jest.fn(() => mockGetLabel()), + getLabelForPercentile: jest.fn(() => mockGetLabelForPercentile()), +})); + +describe('convertToPercentileColumn', () => { + const dataView = stubLogstashDataView; + const field = dataView.fields[0].displayName; + const aggId = 'pr.10'; + const percentile = 10; + const percents = [percentile]; + + const agg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.PERCENTILES, + aggParams: { field, percents }, + aggId, + }; + const singlePercentileRankAgg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.SINGLE_PERCENTILE, + aggParams: { field, percentile }, + aggId, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockGetFieldNameFromField.mockReturnValue(dataView.fields[0]); + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + mockGetLabel.mockReturnValue('someLabel'); + mockGetLabelForPercentile.mockReturnValue('someOtherLabel'); + dataView.getFieldByName = mockGetFieldByName; + }); + + test.each< + [string, Parameters, Partial | null] + >([ + ['null if no percents', [{ agg: { ...agg, aggId: 'pr' }, dataView }], null], + [ + 'null if no value', + [{ agg: { ...singlePercentileRankAgg, aggParams: undefined }, dataView }], + null, + ], + ['null if no aggId', [{ agg: { ...agg, aggId: undefined }, dataView }], null], + ['null if no aggParams', [{ agg: { ...agg, aggParams: undefined }, dataView }], null], + ['null if aggId is invalid', [{ agg: { ...agg, aggId: 'pr.invalid' }, dataView }], null], + [ + 'null if values are undefined', + [{ agg: { ...agg, aggParams: { percents: undefined, field } }, dataView }], + null, + ], + [ + 'null if values are empty', + [{ agg: { ...agg, aggParams: { percents: [], field } }, dataView }], + null, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToPercentileColumn(...input)).toBeNull(); + } else { + expect(convertToPercentileColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); + + test('should return null if field is not specified', () => { + mockGetFieldNameFromField.mockReturnValue(null); + expect(convertToPercentileColumn({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(0); + }); + + test('should return null if field absent at the index pattern', () => { + mockGetFieldByName.mockReturnValueOnce(null); + dataView.getFieldByName = mockGetFieldByName; + + expect(convertToPercentileColumn({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return percentile rank column for percentiles', () => { + expect(convertToPercentileColumn({ agg, dataView })).toEqual( + expect.objectContaining({ + dataType: 'number', + label: 'someOtherLabel', + meta: { aggId: 'pr.10' }, + operationType: 'percentile', + params: { percentile: 10 }, + sourceField: 'bytes', + }) + ); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return percentile rank column for single percentile', () => { + expect(convertToPercentileColumn({ agg: singlePercentileRankAgg, dataView })).toEqual( + expect.objectContaining({ + dataType: 'number', + label: 'someOtherLabel', + meta: { aggId: 'pr.10' }, + operationType: 'percentile', + params: { percentile: 10 }, + sourceField: 'bytes', + }) + ); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.ts new file mode 100644 index 0000000000000..de9d4e088b636 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile.ts @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig } from '../../..'; +import { isFieldValid, PercentileParams } from '../..'; +import { getFieldNameFromField, getLabelForPercentile } from '../utils'; +import { createColumn, getFormat } from './column'; +import { PercentileColumn, CommonColumnConverterArgs } from './types'; +import { SUPPORTED_METRICS } from './supported_metrics'; + +export const convertToPercentileParams = (percentile: number): PercentileParams => ({ + percentile, +}); + +const isSinglePercentile = ( + agg: SchemaConfig +): agg is SchemaConfig => { + if (agg.aggType === METRIC_TYPES.SINGLE_PERCENTILE) { + return true; + } + return false; +}; + +const getPercent = ( + agg: SchemaConfig +) => { + if (isSinglePercentile(agg)) { + return agg.aggParams?.percentile; + } + const { aggParams, aggId } = agg; + if (!aggParams || !aggId) { + return null; + } + + const { percents } = aggParams; + + const [, percentStr] = aggId.split('.'); + + const percent = Number(percentStr); + if (!percents || !percents.length || percentStr === '' || isNaN(percent)) { + return null; + } + return percent; +}; + +export const convertToPercentileColumn = ( + { + agg, + dataView, + }: CommonColumnConverterArgs, + { index, reducedTimeRange }: { index?: number; reducedTimeRange?: string } = {} +): PercentileColumn | null => { + const { aggParams, aggId } = agg; + if (!aggParams || !aggId) { + return null; + } + const percent = getPercent(agg); + if (percent === null || percent === undefined) { + return null; + } + + const params = convertToPercentileParams(percent); + + const fieldName = getFieldNameFromField(agg?.aggParams?.field); + + if (!fieldName) { + return null; + } + + const field = dataView.getFieldByName(fieldName); + if (!isFieldValid(field, SUPPORTED_METRICS[agg.aggType])) { + return null; + } + + return { + operationType: 'percentile', + sourceField: field.name, + ...createColumn(agg, field, { reducedTimeRange }), + params: { ...params, ...getFormat() }, + label: getLabelForPercentile(agg), + timeShift: agg.aggParams?.timeShift, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.test.ts new file mode 100644 index 0000000000000..8a696d51d871b --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertToPercentileRankColumn } from './percentile_rank'; +import { PercentileRanksColumn } from './types'; + +const mockGetFieldNameFromField = jest.fn(); +const mockGetFieldByName = jest.fn(); +const mockGetLabel = jest.fn(); +const mockGetLabelForPercentile = jest.fn(); + +jest.mock('../utils', () => ({ + getFieldNameFromField: jest.fn(() => mockGetFieldNameFromField()), + getLabel: jest.fn(() => mockGetLabel()), + getLabelForPercentile: jest.fn(() => mockGetLabelForPercentile()), +})); + +describe('convertToPercentileRankColumn', () => { + const dataView = stubLogstashDataView; + const field = dataView.fields[0].displayName; + const aggId = 'pr.10'; + const value = 10; + const values = [value]; + + const agg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.PERCENTILE_RANKS, + aggParams: { field, values }, + aggId, + }; + const singlePercentileRankAgg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.SINGLE_PERCENTILE_RANK, + aggParams: { field, value }, + aggId, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockGetFieldNameFromField.mockReturnValue(dataView.fields[0]); + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + mockGetLabel.mockReturnValue('someLabel'); + mockGetLabelForPercentile.mockReturnValue('someOtherLabel'); + dataView.getFieldByName = mockGetFieldByName; + }); + + test.each< + [ + string, + Parameters, + Partial | null + ] + >([ + ['null if no percents', [{ agg: { ...agg, aggId: 'pr' }, dataView }], null], + [ + 'null if no value', + [{ agg: { ...singlePercentileRankAgg, aggParams: undefined }, dataView }], + null, + ], + ['null if no aggId', [{ agg: { ...agg, aggId: undefined }, dataView }], null], + ['null if no aggParams', [{ agg: { ...agg, aggParams: undefined }, dataView }], null], + ['null if aggId is invalid', [{ agg: { ...agg, aggId: 'pr.invalid' }, dataView }], null], + [ + 'null if values are undefined', + [{ agg: { ...agg, aggParams: { values: undefined, field } }, dataView }], + null, + ], + [ + 'null if values are empty', + [{ agg: { ...agg, aggParams: { values: [], field } }, dataView }], + null, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToPercentileRankColumn(...input)).toBeNull(); + } else { + expect(convertToPercentileRankColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); + + test('should return null if field is not specified', () => { + mockGetFieldNameFromField.mockReturnValue(null); + expect(convertToPercentileRankColumn({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(0); + }); + + test('should return null if field absent at the index pattern', () => { + mockGetFieldByName.mockReturnValueOnce(null); + dataView.getFieldByName = mockGetFieldByName; + + expect(convertToPercentileRankColumn({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return percentile rank column for percentile ranks', () => { + expect(convertToPercentileRankColumn({ agg, dataView })).toEqual( + expect.objectContaining({ + dataType: 'number', + label: 'someOtherLabel', + meta: { aggId: 'pr.10' }, + operationType: 'percentile_rank', + params: { value: 10 }, + sourceField: 'bytes', + }) + ); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return percentile rank column for single percentile rank', () => { + expect(convertToPercentileRankColumn({ agg: singlePercentileRankAgg, dataView })).toEqual( + expect.objectContaining({ + dataType: 'number', + label: 'someOtherLabel', + meta: { aggId: 'pr.10' }, + operationType: 'percentile_rank', + params: { value: 10 }, + sourceField: 'bytes', + }) + ); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.ts new file mode 100644 index 0000000000000..5124a26543552 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/percentile_rank.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig } from '../../..'; +import { isFieldValid, PercentileRanksParams } from '../..'; +import { getFieldNameFromField, getLabelForPercentile } from '../utils'; +import { createColumn, getFormat } from './column'; +import { PercentileRanksColumn, CommonColumnConverterArgs } from './types'; +import { SUPPORTED_METRICS } from './supported_metrics'; + +export const convertToPercentileRankParams = (value: number): PercentileRanksParams => ({ + value: Number(value), +}); + +const isSinglePercentileRank = ( + agg: SchemaConfig +): agg is SchemaConfig => { + if (agg.aggType === METRIC_TYPES.SINGLE_PERCENTILE_RANK) { + return true; + } + return false; +}; + +const getPercent = ( + agg: SchemaConfig +) => { + if (isSinglePercentileRank(agg)) { + return agg.aggParams?.value; + } + const { aggParams, aggId } = agg; + if (!aggParams || !aggId) { + return null; + } + const { values } = aggParams; + const [, percentStr] = aggId.split('.'); + + const percent = Number(percentStr); + + if (!values || !values.length || percentStr === '' || isNaN(percent)) { + return null; + } + return percent; +}; + +export const convertToPercentileRankColumn = ( + { + agg, + dataView, + }: CommonColumnConverterArgs, + { index, reducedTimeRange }: { index?: number; reducedTimeRange?: string } = {} +): PercentileRanksColumn | null => { + const { aggParams } = agg; + const percent = getPercent(agg); + + if (percent === null || percent === undefined) { + return null; + } + + const params = convertToPercentileRankParams(percent); + const fieldName = getFieldNameFromField(aggParams!.field); + if (!fieldName) { + return null; + } + + const field = dataView.getFieldByName(fieldName); + if (!isFieldValid(field, SUPPORTED_METRICS[agg.aggType])) { + return null; + } + + return { + operationType: 'percentile_rank', + sourceField: field.name, + ...createColumn(agg, field, { reducedTimeRange }), + params: { ...params, ...getFormat() }, + label: getLabelForPercentile(agg), + timeShift: aggParams?.timeShift, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.test.ts new file mode 100644 index 0000000000000..8f535c28c8264 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.test.ts @@ -0,0 +1,74 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { AggParamsRange, AggParamsHistogram } from '@kbn/data-plugin/common'; +import { convertToRangeColumn } from './range'; +import { RangeColumn } from './types'; +import { DataType } from '../../types'; +import { RANGE_MODES } from '../../constants'; + +describe('convertToRangeColumn', () => { + const aggId = `some-id`; + const ranges = [ + { + from: 1, + to: 1000, + label: '1', + }, + ]; + const aggParamsRange: AggParamsRange = { + field: stubLogstashDataView.fields[0].name, + ranges, + }; + const aggParamsHistogram: AggParamsHistogram = { + interval: '1d', + field: stubLogstashDataView.fields[0].name, + }; + + test.each<[string, Parameters, Partial | null]>([ + [ + 'range column if provide valid range agg', + [aggId, aggParamsRange, '', stubLogstashDataView], + { + dataType: stubLogstashDataView.fields[0].type as DataType, + isBucketed: true, + isSplit: false, + sourceField: stubLogstashDataView.fields[0].name, + meta: { aggId }, + params: { + type: RANGE_MODES.Range, + maxBars: 'auto', + ranges, + }, + }, + ], + [ + 'range column if provide valid histogram agg', + [aggId, aggParamsHistogram, '', stubLogstashDataView, true], + { + dataType: stubLogstashDataView.fields[0].type as DataType, + isBucketed: true, + isSplit: true, + sourceField: stubLogstashDataView.fields[0].name, + meta: { aggId }, + params: { + type: RANGE_MODES.Histogram, + maxBars: 'auto', + ranges: [], + }, + }, + ], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(convertToRangeColumn(...input)).toBeNull(); + } else { + expect(convertToRangeColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.ts new file mode 100644 index 0000000000000..6a9f96fd5ad1e --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/range.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { AggParamsRange, AggParamsHistogram } from '@kbn/data-plugin/common'; +import type { DataView } from '@kbn/data-views-plugin/common'; +import uuid from 'uuid'; +import { RANGE_MODES } from '../../constants'; +import { DataType, RangeParams } from '../../types'; +import { getFieldNameFromField } from '../utils'; +import { RangeColumn } from './types'; + +const isHistogramAggParams = ( + aggParams: AggParamsRange | AggParamsHistogram +): aggParams is AggParamsHistogram => { + return aggParams && 'interval' in aggParams; +}; + +export const convertToRangeParams = ( + aggParams: AggParamsRange | AggParamsHistogram +): RangeParams => { + if (isHistogramAggParams(aggParams)) { + return { + type: RANGE_MODES.Histogram, + maxBars: aggParams.maxBars ?? 'auto', + ranges: [], + }; + } else { + return { + type: RANGE_MODES.Range, + maxBars: 'auto', + ranges: + aggParams.ranges?.map((range) => ({ + label: range.label, + from: range.from ?? null, + to: range.to ?? null, + })) ?? [], + }; + } +}; + +export const convertToRangeColumn = ( + aggId: string, + aggParams: AggParamsRange | AggParamsHistogram, + label: string, + dataView: DataView, + isSplit: boolean = false +): RangeColumn | null => { + const fieldName = getFieldNameFromField(aggParams.field); + + if (!fieldName) { + return null; + } + + const field = dataView.getFieldByName(fieldName); + if (!field) { + return null; + } + + const params = convertToRangeParams(aggParams); + + return { + columnId: uuid(), + label, + operationType: 'range', + dataType: field.type as DataType, + isBucketed: true, + isSplit, + sourceField: field.name, + params, + timeShift: aggParams.timeShift, + meta: { aggId }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.test.ts new file mode 100644 index 0000000000000..759620650b8a6 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertToSiblingPipelineColumns } from './sibling_pipeline'; + +const mockConvertMetricToColumns = jest.fn(); +const mockConvertToSchemaConfig = jest.fn(); + +jest.mock('../metrics', () => ({ + convertMetricToColumns: jest.fn(() => mockConvertMetricToColumns()), +})); + +jest.mock('../../../vis_schemas', () => ({ + convertToSchemaConfig: jest.fn(() => mockConvertToSchemaConfig()), +})); + +describe('convertToSiblingPipelineColumns', () => { + const dataView = stubLogstashDataView; + const aggId = 'agg-id-1'; + const agg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + aggParams: { customMetric: {} as IAggConfig }, + aggId, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockConvertMetricToColumns.mockReturnValue([{}]); + mockConvertToSchemaConfig.mockReturnValue({}); + }); + + test('should return null if aggParams are not defined', () => { + expect( + convertToSiblingPipelineColumns({ agg: { ...agg, aggParams: undefined }, aggs: [], dataView }) + ).toBeNull(); + expect(mockConvertMetricToColumns).toBeCalledTimes(0); + }); + + test('should return null if customMetric is not defined', () => { + expect( + convertToSiblingPipelineColumns({ + agg: { ...agg, aggParams: { customMetric: undefined } }, + aggs: [], + dataView, + }) + ).toBeNull(); + expect(mockConvertMetricToColumns).toBeCalledTimes(0); + }); + + test('should return null if sibling agg is not supported', () => { + mockConvertMetricToColumns.mockReturnValue(null); + expect(convertToSiblingPipelineColumns({ agg, aggs: [], dataView })).toBeNull(); + expect(mockConvertToSchemaConfig).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + }); + + test('should return column', () => { + const column = { operationType: 'formula' }; + mockConvertMetricToColumns.mockReturnValue([column]); + expect(convertToSiblingPipelineColumns({ agg, aggs: [], dataView })).toEqual(column); + expect(mockConvertToSchemaConfig).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.ts new file mode 100644 index 0000000000000..03e1d955dd045 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/sibling_pipeline.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { convertMetricToColumns } from '../metrics'; +import { AggBasedColumn, ExtendedColumnConverterArgs, SiblingPipelineMetric } from './types'; +import { convertToSchemaConfig } from '../../../vis_schemas'; + +export const convertToSiblingPipelineColumns = ( + columnConverterArgs: ExtendedColumnConverterArgs +): AggBasedColumn | null => { + const { aggParams, label } = columnConverterArgs.agg; + if (!aggParams) { + return null; + } + + if (!aggParams.customMetric) { + return null; + } + + const customMetricColumn = convertMetricToColumns( + { ...convertToSchemaConfig(aggParams.customMetric), label }, + columnConverterArgs.dataView, + columnConverterArgs.aggs + ); + + if (!customMetricColumn) { + return null; + } + + return customMetricColumn[0]; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.test.ts new file mode 100644 index 0000000000000..cbb1f03a6dc2e --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.test.ts @@ -0,0 +1,115 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertToStdDeviationFormulaColumns } from './std_deviation'; +import { FormulaColumn } from './types'; + +const mockGetFieldNameFromField = jest.fn(); +const mockGetFieldByName = jest.fn(); +const mockGetLabel = jest.fn(); + +jest.mock('../utils', () => ({ + getFieldNameFromField: jest.fn(() => mockGetFieldNameFromField()), + getLabel: jest.fn(() => mockGetLabel()), +})); + +describe('convertToStdDeviationFormulaColumns', () => { + const dataView = stubLogstashDataView; + const stdLowerAggId = 'agg-id.std_lower'; + const stdUpperAggId = 'agg-id.std_upper'; + const label = 'std label'; + const agg: SchemaConfig = { + accessor: 0, + label, + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.STD_DEV, + aggId: stdLowerAggId, + aggParams: { + field: dataView.fields[0].displayName, + }, + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockGetFieldNameFromField.mockReturnValue(dataView.fields[0].displayName); + mockGetFieldByName.mockReturnValue(dataView.fields[0]); + mockGetLabel.mockReturnValue('some label'); + dataView.getFieldByName = mockGetFieldByName; + }); + + test.each< + [string, Parameters, Partial | null] + >([['null if no aggId is passed', [{ agg: { ...agg, aggId: undefined }, dataView }], null]])( + 'should return %s', + (_, input, expected) => { + if (expected === null) { + expect(convertToStdDeviationFormulaColumns(...input)).toBeNull(); + } else { + expect(convertToStdDeviationFormulaColumns(...input)).toEqual( + expect.objectContaining(expected) + ); + } + } + ); + + test('should return null if field is not present', () => { + mockGetFieldNameFromField.mockReturnValue(null); + expect(convertToStdDeviationFormulaColumns({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(0); + }); + + test("should return null if field doesn't exist in dataView", () => { + mockGetFieldByName.mockReturnValue(null); + dataView.getFieldByName = mockGetFieldByName; + expect(convertToStdDeviationFormulaColumns({ agg, dataView })).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return null if agg id is invalid', () => { + expect( + convertToStdDeviationFormulaColumns({ agg: { ...agg, aggId: 'some-id' }, dataView }) + ).toBeNull(); + expect(mockGetFieldNameFromField).toBeCalledTimes(1); + expect(dataView.getFieldByName).toBeCalledTimes(1); + }); + + test('should return formula column for lower std deviation', () => { + expect( + convertToStdDeviationFormulaColumns({ agg: { ...agg, aggId: stdLowerAggId }, dataView }) + ).toEqual( + expect.objectContaining({ + label, + meta: { aggId: 'agg-id.std_lower' }, + operationType: 'formula', + params: { formula: 'average(bytes) - 2 * standard_deviation(bytes)' }, + }) + ); + }); + + test('should return formula column for upper std deviation', () => { + expect( + convertToStdDeviationFormulaColumns({ agg: { ...agg, aggId: stdUpperAggId }, dataView }) + ).toEqual( + expect.objectContaining({ + label, + meta: { aggId: 'agg-id.std_upper' }, + operationType: 'formula', + params: { formula: 'average(bytes) + 2 * standard_deviation(bytes)' }, + }) + ); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.ts new file mode 100644 index 0000000000000..f2c218d429bdf --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/std_deviation.ts @@ -0,0 +1,82 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { isFieldValid } from '../../utils'; +import { addTimeRangeToFormula } from '../metrics/formula'; +import { getFieldNameFromField } from '../utils'; +import { createFormulaColumn } from './formula'; +import { getFormulaFromMetric, SUPPORTED_METRICS } from './supported_metrics'; +import { CommonColumnConverterArgs, FormulaColumn } from './types'; + +const STD_LOWER = 'std_lower'; +const STD_UPPER = 'std_upper'; +const STD_MODES = [STD_LOWER, STD_UPPER]; + +const getFormulaForStdDevLowerBound = (field: string, reducedTimeRange?: string) => { + const aggFormula = getFormulaFromMetric(SUPPORTED_METRICS.std_dev); + + return `average(${field}${addTimeRangeToFormula( + reducedTimeRange + )}) - ${2} * ${aggFormula}(${field}${addTimeRangeToFormula(reducedTimeRange)})`; +}; + +const getFormulaForStdDevUpperBound = (field: string, reducedTimeRange?: string) => { + const aggFormula = getFormulaFromMetric(SUPPORTED_METRICS.std_dev); + + return `average(${field}${addTimeRangeToFormula( + reducedTimeRange + )}) + ${2} * ${aggFormula}(${field}${addTimeRangeToFormula(reducedTimeRange)})`; +}; + +export const getStdDeviationFormula = ( + aggId: string, + fieldName: string, + reducedTimeRange?: string +) => { + const [, mode] = aggId.split('.'); + if (!STD_MODES.includes(mode)) { + return null; + } + + return mode === STD_LOWER + ? getFormulaForStdDevLowerBound(fieldName, reducedTimeRange) + : getFormulaForStdDevUpperBound(fieldName, reducedTimeRange); +}; + +export const convertToStdDeviationFormulaColumns = ( + { agg, dataView }: CommonColumnConverterArgs, + reducedTimeRange?: string +) => { + const { aggId } = agg; + if (!aggId) { + return null; + } + + const fieldName = getFieldNameFromField(agg.aggParams?.field); + + if (!fieldName) { + return null; + } + const field = dataView.getFieldByName(fieldName); + if (!isFieldValid(field, SUPPORTED_METRICS[agg.aggType])) { + return null; + } + + const formula = getStdDeviationFormula(aggId, field.displayName, reducedTimeRange); + + if (!formula) { + return null; + } + + const formulaColumn: FormulaColumn | null = createFormulaColumn(formula, agg); + if (!formulaColumn) { + return null; + } + return { ...formulaColumn, label: agg.label }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/supported_metrics.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/supported_metrics.ts new file mode 100644 index 0000000000000..17a8ccf26c369 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/supported_metrics.ts @@ -0,0 +1,231 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { BUCKET_TYPES, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { Operation } from '../../types'; +import { Operations } from '../../constants'; + +interface Agg { + isFormula?: false; +} +interface AggWithFormula { + isFormula: true; + formula: string; +} + +export type AggOptions = { + isFullReference: boolean; + isFieldRequired: boolean; + supportedDataTypes: readonly string[]; +} & (T extends Exclude ? Agg : AggWithFormula); + +// list of supported TSVB aggregation types in Lens +// some of them are supported on the quick functions tab and some of them +// are supported with formulas + +export type Metric = { name: T } & AggOptions; +interface LocalSupportedMetrics { + [METRIC_TYPES.AVG]: Metric; + [METRIC_TYPES.CARDINALITY]: Metric; + [METRIC_TYPES.MEDIAN]: Metric; + [METRIC_TYPES.COUNT]: Metric; + [METRIC_TYPES.DERIVATIVE]: Metric; + [METRIC_TYPES.CUMULATIVE_SUM]: Metric; + [METRIC_TYPES.AVG_BUCKET]: Metric; + [METRIC_TYPES.MAX_BUCKET]: Metric; + [METRIC_TYPES.MIN_BUCKET]: Metric; + [METRIC_TYPES.SUM_BUCKET]: Metric; + [METRIC_TYPES.MAX]: Metric; + [METRIC_TYPES.MIN]: Metric; + [METRIC_TYPES.SUM]: Metric; + [METRIC_TYPES.VALUE_COUNT]: Metric; + [METRIC_TYPES.STD_DEV]: Metric; + [METRIC_TYPES.PERCENTILES]: Metric; + [METRIC_TYPES.SINGLE_PERCENTILE]: Metric; + [METRIC_TYPES.PERCENTILE_RANKS]: Metric; + [METRIC_TYPES.SINGLE_PERCENTILE_RANK]: Metric; + [METRIC_TYPES.TOP_HITS]: Metric; + [METRIC_TYPES.TOP_METRICS]: Metric; + [METRIC_TYPES.MOVING_FN]: Metric; +} + +type UnsupportedSupportedMetrics = Exclude< + METRIC_TYPES | BUCKET_TYPES, + keyof LocalSupportedMetrics +>; +export type SupportedMetrics = LocalSupportedMetrics & { + [Key in UnsupportedSupportedMetrics]?: null; +}; + +const supportedDataTypesWithDate = ['number', 'date', 'histogram'] as const; +const supportedDataTypes = ['number', 'histogram'] as const; +const extendedSupportedDataTypes = [ + 'string', + 'boolean', + 'number', + 'number_range', + 'ip', + 'ip_range', + 'date', + 'date_range', + 'murmur3', +] as const; + +export const SUPPORTED_METRICS: SupportedMetrics = { + avg: { + name: 'average', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: ['number'], + }, + cardinality: { + name: 'unique_count', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: extendedSupportedDataTypes, + }, + count: { + name: 'count', + isFullReference: false, + isFieldRequired: false, + supportedDataTypes: [], + }, + moving_avg: { + name: 'moving_average', + isFullReference: true, + isFieldRequired: true, + supportedDataTypes: ['number'], + }, + derivative: { + name: 'differences', + isFullReference: true, + isFieldRequired: true, + supportedDataTypes: ['number'], + }, + cumulative_sum: { + name: 'cumulative_sum', + isFullReference: true, + isFieldRequired: true, + supportedDataTypes: ['number'], + }, + avg_bucket: { + name: 'formula', + isFullReference: true, + isFieldRequired: true, + isFormula: true, + formula: 'overall_average', + supportedDataTypes: ['number'], + }, + max_bucket: { + name: 'formula', + isFullReference: true, + isFieldRequired: true, + isFormula: true, + formula: 'overall_max', + supportedDataTypes: ['number'], + }, + min_bucket: { + name: 'formula', + isFullReference: true, + isFieldRequired: true, + isFormula: true, + formula: 'overall_min', + supportedDataTypes: ['number'], + }, + sum_bucket: { + name: 'formula', + isFullReference: true, + isFieldRequired: true, + isFormula: true, + formula: 'overall_sum', + supportedDataTypes: ['number'], + }, + max: { + name: 'max', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: supportedDataTypesWithDate, + }, + min: { + name: 'min', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: supportedDataTypesWithDate, + }, + percentiles: { + name: 'percentile', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + single_percentile: { + name: 'percentile', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + percentile_ranks: { + name: 'percentile_rank', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + single_percentile_rank: { + name: 'percentile_rank', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + sum: { + name: 'sum', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + top_hits: { + name: 'last_value', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: extendedSupportedDataTypes, + }, + top_metrics: { + name: 'last_value', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: extendedSupportedDataTypes, + }, + value_count: { + name: 'count', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes: extendedSupportedDataTypes, + }, + std_dev: { + name: 'standard_deviation', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, + median: { + name: 'median', + isFullReference: false, + isFieldRequired: true, + supportedDataTypes, + }, +} as const; + +type SupportedMetricsKeys = keyof LocalSupportedMetrics; + +export type SupportedMetric = typeof SUPPORTED_METRICS[SupportedMetricsKeys]; + +export const getFormulaFromMetric = (metric: SupportedMetric) => { + if (metric.isFormula) { + return metric.formula; + } + return metric.name; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.test.ts new file mode 100644 index 0000000000000..d214ec74b09b1 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.test.ts @@ -0,0 +1,241 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { AggParamsTerms, IAggConfig, METRIC_TYPES, BUCKET_TYPES } from '@kbn/data-plugin/common'; +import { convertToTermsColumn } from './terms'; +import { AggBasedColumn, TermsColumn } from './types'; +import { SchemaConfig } from '../../..'; + +const mockConvertMetricToColumns = jest.fn(); + +jest.mock('../metrics', () => ({ + convertMetricToColumns: jest.fn(() => mockConvertMetricToColumns()), +})); + +jest.mock('../../../vis_schemas', () => ({ + convertToSchemaConfig: jest.fn(() => ({})), +})); + +describe('convertToDateHistogramColumn', () => { + const aggId = `some-id`; + const aggParams: AggParamsTerms = { + field: stubLogstashDataView.fields[0].name, + orderBy: '_key', + order: { + value: 'asc', + text: '', + }, + size: 5, + }; + const aggs: Array> = [ + { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggParams: { + field: stubLogstashDataView.fields[0].name, + }, + }, + ]; + const metricColumns: AggBasedColumn[] = [ + { + columnId: 'column-1', + operationType: 'average', + isBucketed: false, + isSplit: false, + sourceField: stubLogstashDataView.fields[0].name, + dataType: 'number', + params: {}, + meta: { + aggId: '1', + }, + }, + ]; + + afterEach(() => { + jest.clearAllMocks(); + }); + + test.each< + [string, Parameters, Partial | null, () => void] + >([ + [ + 'null if dataview does not include field from terms params', + [ + aggId, + { + agg: { aggParams: { ...aggParams, field: '' } } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + null, + () => {}, + ], + [ + 'terms column with alphabetical orderBy', + [ + aggId, + { + agg: { aggParams } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + { + operationType: 'terms', + sourceField: stubLogstashDataView.fields[0].name, + isBucketed: true, + params: { + size: 5, + include: [], + exclude: [], + parentFormat: { id: 'terms' }, + orderBy: { type: 'alphabetical' }, + orderDirection: 'asc', + }, + }, + () => {}, + ], + [ + 'terms column with column orderBy if provided column for orderBy is exist', + [ + aggId, + { + agg: { aggParams: { ...aggParams, orderBy: '1' } } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + { + operationType: 'terms', + sourceField: stubLogstashDataView.fields[0].name, + isBucketed: true, + params: { + size: 5, + include: [], + exclude: [], + parentFormat: { id: 'terms' }, + orderBy: { type: 'column', columnId: metricColumns[0].columnId }, + orderAgg: metricColumns[0], + orderDirection: 'asc', + }, + }, + () => {}, + ], + [ + 'null if provided column for orderBy is not exist', + [ + aggId, + { + agg: { aggParams: { ...aggParams, orderBy: '2' } } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + null, + () => {}, + ], + [ + 'null if provided custom orderBy without orderAgg', + [ + aggId, + { + agg: { + aggParams: { ...aggParams, orderBy: 'custom', orderAgg: undefined }, + } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + null, + () => {}, + ], + [ + 'null if provided custom orderBy and not valid orderAgg', + [ + aggId, + { + agg: { + aggParams: { ...aggParams, orderBy: 'custom', orderAgg: {} as IAggConfig }, + } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + null, + () => { + mockConvertMetricToColumns.mockReturnValue(null); + }, + ], + [ + 'terms column with custom orderBy and prepared orderAgg', + [ + aggId, + { + agg: { + aggParams: { ...aggParams, orderBy: 'custom', orderAgg: {} as IAggConfig }, + } as SchemaConfig, + dataView: stubLogstashDataView, + aggs, + metricColumns, + }, + '', + false, + ], + { + operationType: 'terms', + sourceField: stubLogstashDataView.fields[0].name, + isBucketed: true, + params: { + size: 5, + include: [], + exclude: [], + parentFormat: { id: 'terms' }, + orderBy: { type: 'custom' }, + orderAgg: metricColumns[0], + orderDirection: 'asc', + }, + }, + () => { + mockConvertMetricToColumns.mockReturnValue(metricColumns); + }, + ], + ])('should return %s', (_, input, expected, actions) => { + actions(); + if (expected === null) { + expect(convertToTermsColumn(...input)).toBeNull(); + } else { + expect(convertToTermsColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.ts new file mode 100644 index 0000000000000..0a50390ec469e --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/terms.ts @@ -0,0 +1,141 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { BUCKET_TYPES } from '@kbn/data-plugin/common'; +import uuid from 'uuid'; +import { DataType, TermsParams } from '../../types'; +import { getFieldNameFromField, isColumnWithMeta } from '../utils'; +import { convertToSchemaConfig } from '../../../vis_schemas'; +import { convertMetricToColumns } from '../metrics'; +import { CommonBucketConverterArgs, TermsColumn } from './types'; + +interface OrderByWithAgg { + orderAgg?: TermsParams['orderAgg']; + orderBy: TermsParams['orderBy']; +} + +const getOrderByWithAgg = ({ + agg, + dataView, + aggs, + metricColumns, +}: CommonBucketConverterArgs): OrderByWithAgg | null => { + if (!agg.aggParams) { + return null; + } + + if (agg.aggParams.orderBy === '_key') { + return { orderBy: { type: 'alphabetical' } }; + } + + if (agg.aggParams.orderBy === 'custom') { + if (!agg.aggParams.orderAgg) { + return null; + } + const orderMetricColumn = convertMetricToColumns( + convertToSchemaConfig(agg.aggParams.orderAgg), + dataView, + aggs + ); + if (!orderMetricColumn) { + return null; + } + return { + orderBy: { type: 'custom' }, + orderAgg: orderMetricColumn[0], + }; + } + + const orderAgg = metricColumns.find((column) => { + if (isColumnWithMeta(column)) { + return column.meta.aggId === agg.aggParams?.orderBy; + } + return false; + }); + + if (!orderAgg) { + return null; + } + + return { + orderBy: { type: 'column', columnId: orderAgg.columnId }, + orderAgg, + }; +}; + +export const convertToTermsParams = ({ + agg, + dataView, + aggs, + metricColumns, +}: CommonBucketConverterArgs): TermsParams | null => { + if (!agg.aggParams) { + return null; + } + + const orderByWithAgg = getOrderByWithAgg({ agg, dataView, aggs, metricColumns }); + if (orderByWithAgg === null) { + return null; + } + + return { + size: agg.aggParams.size ?? 10, + include: agg.aggParams.include + ? Array.isArray(agg.aggParams.include) + ? agg.aggParams.include + : [agg.aggParams.include] + : [], + includeIsRegex: agg.aggParams.includeIsRegex, + exclude: agg.aggParams.exclude + ? Array.isArray(agg.aggParams.exclude) + ? agg.aggParams.exclude + : [agg.aggParams.exclude] + : [], + excludeIsRegex: agg.aggParams.excludeIsRegex, + otherBucket: agg.aggParams.otherBucket, + orderDirection: agg.aggParams.order?.value ?? 'desc', + parentFormat: { id: 'terms' }, + missingBucket: agg.aggParams.missingBucket, + ...orderByWithAgg, + }; +}; + +export const convertToTermsColumn = ( + aggId: string, + { agg, dataView, aggs, metricColumns }: CommonBucketConverterArgs, + label: string, + isSplit: boolean +): TermsColumn | null => { + if (!agg.aggParams?.field) { + return null; + } + const sourceField = getFieldNameFromField(agg.aggParams?.field) ?? 'document'; + const field = dataView.getFieldByName(sourceField); + + if (!field) { + return null; + } + + const params = convertToTermsParams({ agg, dataView, aggs, metricColumns }); + if (!params) { + return null; + } + + return { + columnId: uuid(), + operationType: 'terms', + label, + dataType: (field.type as DataType) ?? undefined, + sourceField: field.name, + isBucketed: true, + isSplit, + params: { ...params }, + timeShift: agg.aggParams?.timeShift, + meta: { aggId }, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/convert/types.ts b/src/plugins/visualizations/common/convert_to_lens/lib/convert/types.ts new file mode 100644 index 0000000000000..3dfaee67a61e0 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/convert/types.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import type { DataView } from '@kbn/data-views-plugin/common'; +import { SchemaConfig, SupportedAggregation } from '../../../types'; +import { + Operation, + BaseColumn as GenericBaseColumn, + Column as BaseColumn, + GenericColumnWithMeta, + PercentileColumn as BasePercentileColumn, + PercentileRanksColumn as BasePercentileRanksColumn, + FormulaColumn as BaseFormulaColumn, + LastValueColumn as BaseLastValueColumn, + AvgColumn as BaseAvgColumn, + CountColumn as BaseCountColumn, + CardinalityColumn as BaseCardinalityColumn, + MaxColumn as BaseMaxColumn, + MedianColumn as BaseMedianColumn, + MinColumn as BaseMinColumn, + SumColumn as BaseSumColumn, + CumulativeSumColumn as BaseCumulativeSumColumn, + MovingAverageColumn as BaseMovingAverageColumn, + DerivativeColumn as BaseDerivativeColumn, + DateHistogramColumn as BaseDateHistogramColumn, + TermsColumn as BaseTermsColumn, + FiltersColumn as BaseFiltersColumn, + RangeColumn as BaseRangeColumn, +} from '../../types'; + +export type MetricsWithField = Exclude< + METRIC_TYPES, + | METRIC_TYPES.FILTERED_METRIC + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.SUM_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.SERIAL_DIFF + | METRIC_TYPES.COUNT +>; + +export type OtherParentPipelineAggs = METRIC_TYPES.DERIVATIVE | METRIC_TYPES.MOVING_FN; + +export type ParentPipelineMetric = METRIC_TYPES.CUMULATIVE_SUM | OtherParentPipelineAggs; + +export type SiblingPipelineMetric = + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.SUM_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.MAX_BUCKET; + +export type BucketColumn = DateHistogramColumn | TermsColumn | FiltersColumn; +export interface CommonColumnConverterArgs< + Agg extends SupportedAggregation = SupportedAggregation +> { + agg: SchemaConfig; + dataView: DataView; +} + +export interface ExtendedColumnConverterArgs< + Agg extends SupportedAggregation = SupportedAggregation +> extends CommonColumnConverterArgs { + aggs: Array>; +} + +export interface CommonBucketConverterArgs< + Agg extends SupportedAggregation = SupportedAggregation +> { + agg: SchemaConfig; + dataView: DataView; + metricColumns: AggBasedColumn[]; + aggs: Array>; +} + +export type AggId = `${string}`; + +export interface Meta { + aggId: AggId; +} + +export type GeneralColumn = Omit, 'operationType' | 'params'>; +export type GeneralColumnWithMeta = GenericColumnWithMeta; +export interface ExtraColumnFields { + isBucketed?: boolean; + isSplit?: boolean; + reducedTimeRange?: string; +} + +export type PercentileColumn = GenericColumnWithMeta; +export type PercentileRanksColumn = GenericColumnWithMeta; + +export type AggBasedColumn = GenericColumnWithMeta | BucketColumn; + +export type FormulaColumn = GenericColumnWithMeta; +export type LastValueColumn = GenericColumnWithMeta; +export type AvgColumn = GenericColumnWithMeta; +export type CountColumn = GenericColumnWithMeta; +export type CardinalityColumn = GenericColumnWithMeta; +export type MaxColumn = GenericColumnWithMeta; +export type MedianColumn = GenericColumnWithMeta; +export type MinColumn = GenericColumnWithMeta; +export type SumColumn = GenericColumnWithMeta; +export type CumulativeSumColumn = GenericColumnWithMeta; +export type MovingAverageColumn = GenericColumnWithMeta; +export type DerivativeColumn = GenericColumnWithMeta; +export type DateHistogramColumn = GenericColumnWithMeta; +export type TermsColumn = GenericColumnWithMeta; +export type FiltersColumn = GenericColumnWithMeta; +export type RangeColumn = GenericColumnWithMeta; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/index.ts b/src/plugins/visualizations/common/convert_to_lens/lib/index.ts new file mode 100644 index 0000000000000..083450c8ff5d1 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export * from './buckets'; +export * from './metrics'; +export * from './convert'; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.test.ts new file mode 100644 index 0000000000000..95e128e22b092 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.test.ts @@ -0,0 +1,474 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { DataViewField, IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig } from '../../..'; +import { getFormulaForPipelineAgg, getFormulaForAgg } from './formula'; + +const mockGetMetricFromParentPipelineAgg = jest.fn(); +const mockIsPercentileAgg = jest.fn(); +const mockIsPercentileRankAgg = jest.fn(); +const mockIsPipeline = jest.fn(); +const mockIsStdDevAgg = jest.fn(); +const mockGetFieldByName = jest.fn(); +const originalGetFieldByName = stubLogstashDataView.getFieldByName; + +jest.mock('../utils', () => ({ + getFieldNameFromField: jest.fn((field) => field), + getMetricFromParentPipelineAgg: jest.fn(() => mockGetMetricFromParentPipelineAgg()), + isPercentileAgg: jest.fn(() => mockIsPercentileAgg()), + isPercentileRankAgg: jest.fn(() => mockIsPercentileRankAgg()), + isPipeline: jest.fn(() => mockIsPipeline()), + isStdDevAgg: jest.fn(() => mockIsStdDevAgg()), +})); + +const dataView = stubLogstashDataView; + +const field = stubLogstashDataView.fields[0].name; +const aggs: Array> = [ + { + aggId: '1', + aggType: METRIC_TYPES.CUMULATIVE_SUM, + aggParams: { customMetric: {} as IAggConfig }, + accessor: 0, + params: {}, + label: 'cumulative sum', + format: {}, + }, + { + aggId: '2', + aggType: METRIC_TYPES.AVG_BUCKET, + aggParams: { customMetric: {} as IAggConfig }, + accessor: 0, + params: {}, + label: 'overall average', + format: {}, + }, + { + aggId: '3.10', + aggType: METRIC_TYPES.PERCENTILES, + aggParams: { percents: [0, 10], field }, + accessor: 0, + params: {}, + label: 'percentile', + format: {}, + }, + { + aggId: '4.5', + aggType: METRIC_TYPES.PERCENTILE_RANKS, + aggParams: { values: [0, 5], field }, + accessor: 0, + params: {}, + label: 'percintile rank', + format: {}, + }, + { + aggId: '5.std_upper', + aggType: METRIC_TYPES.STD_DEV, + aggParams: { field }, + accessor: 0, + params: {}, + label: 'std dev', + format: {}, + }, + { + aggId: '6', + aggType: METRIC_TYPES.AVG, + aggParams: { field }, + accessor: 0, + params: {}, + label: 'average', + format: {}, + }, +]; + +describe('getFormulaForPipelineAgg', () => { + afterEach(() => { + jest.clearAllMocks(); + dataView.getFieldByName = originalGetFieldByName; + }); + + test.each<[string, Parameters, () => void, string | null]>([ + [ + 'null if custom metric is invalid', + [{ agg: aggs[0] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue(null); + }, + null, + ], + [ + 'null if custom metric type is not supported', + [{ agg: aggs[0] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValue({ + aggType: METRIC_TYPES.GEO_BOUNDS, + }); + }, + null, + ], + [ + 'correct formula if agg is parent pipeline agg and custom metric is valid and supported pipeline agg', + [{ agg: aggs[0] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg + .mockReturnValueOnce({ + aggType: METRIC_TYPES.MOVING_FN, + aggParams: {}, + aggId: '2', + }) + .mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '3', + }); + }, + 'cumulative_sum(moving_average(average(bytes)))', + ], + [ + 'correct formula if agg is parent pipeline agg and custom metric is valid and supported not pipeline agg', + [{ agg: aggs[0] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '2', + }); + }, + 'cumulative_sum(average(bytes))', + ], + [ + 'correct formula if agg is parent pipeline agg and custom metric is valid and supported percentile rank agg', + [{ agg: aggs[0] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.PERCENTILE_RANKS, + aggParams: { + field, + }, + aggId: '3.10', + }); + }, + 'cumulative_sum(percentile_rank(bytes, value=10))', + ], + [ + 'correct formula if agg is sibling pipeline agg and custom metric is valid and supported agg', + [{ agg: aggs[1] as SchemaConfig, aggs, dataView }], + () => { + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '3', + }); + }, + 'average(bytes)', + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(getFormulaForPipelineAgg(...input)).toBeNull(); + } else { + expect(getFormulaForPipelineAgg(...input)).toEqual(expected); + } + }); + + test('null if agg is sibling pipeline agg, custom metric is valid, agg is supported and field type is not supported', () => { + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '3', + }); + + const field1: DataViewField = { + name: 'bytes', + type: 'geo', + esTypes: ['long'], + aggregatable: true, + searchable: true, + count: 10, + readFromDocValues: true, + scripted: false, + isMapped: true, + } as DataViewField; + + mockGetFieldByName.mockReturnValueOnce(field1); + + dataView.getFieldByName = mockGetFieldByName; + const agg = getFormulaForPipelineAgg({ + agg: aggs[1] as SchemaConfig, + aggs, + dataView, + }); + expect(agg).toBeNull(); + }); + + test('null if agg is sibling pipeline agg, custom metric is valid, agg is supported, field type is supported and field is not aggregatable', () => { + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '3', + }); + + const field1: DataViewField = { + name: 'str', + type: 'string', + esTypes: ['text'], + aggregatable: false, + searchable: true, + count: 10, + readFromDocValues: true, + scripted: false, + isMapped: true, + } as DataViewField; + + mockGetFieldByName.mockReturnValueOnce(field1); + + dataView.getFieldByName = mockGetFieldByName; + const agg = getFormulaForPipelineAgg({ + agg: aggs[1] as SchemaConfig, + aggs, + dataView, + }); + expect(agg).toBeNull(); + }); +}); + +describe('getFormulaForAgg', () => { + beforeEach(() => { + mockIsPercentileAgg.mockReturnValue(false); + mockIsPipeline.mockReturnValue(false); + mockIsStdDevAgg.mockReturnValue(false); + mockIsPercentileRankAgg.mockReturnValue(false); + }); + + afterEach(() => { + jest.clearAllMocks(); + dataView.getFieldByName = originalGetFieldByName; + }); + + test.each<[string, Parameters, () => void, string | null]>([ + [ + 'null if agg type is not supported', + [ + { + agg: { ...aggs[0], aggType: METRIC_TYPES.GEO_BOUNDS, aggParams: { field } }, + aggs, + dataView, + }, + ], + () => {}, + null, + ], + [ + 'correct pipeline formula if agg is valid pipeline agg', + [{ agg: aggs[0], aggs, dataView }], + () => { + mockIsPipeline.mockReturnValue(true); + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '2', + }); + }, + 'cumulative_sum(average(bytes))', + ], + [ + 'correct percentile formula if agg is valid percentile agg', + [{ agg: aggs[2], aggs, dataView }], + () => { + mockIsPercentileAgg.mockReturnValue(true); + }, + 'percentile(bytes, percentile=10)', + ], + [ + 'correct percentile rank formula if agg is valid percentile rank agg', + [{ agg: aggs[3], aggs, dataView }], + () => { + mockIsPercentileRankAgg.mockReturnValue(true); + }, + 'percentile_rank(bytes, value=5)', + ], + [ + 'correct standart deviation formula if agg is valid standart deviation agg', + [{ agg: aggs[4], aggs, dataView }], + () => { + mockIsStdDevAgg.mockReturnValue(true); + }, + 'average(bytes) + 2 * standard_deviation(bytes)', + ], + [ + 'correct metric formula if agg is valid other metric agg', + [{ agg: aggs[5], aggs, dataView }], + () => {}, + 'average(bytes)', + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(getFormulaForAgg(...input)).toBeNull(); + } else { + expect(getFormulaForAgg(...input)).toEqual(expected); + } + }); + + test.each([ + [ + 'null if agg is valid pipeline agg', + aggs[0], + () => { + mockIsPipeline.mockReturnValue(true); + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '2', + }); + }, + ], + [ + 'null if percentile rank agg is valid percentile agg', + aggs[2], + () => { + mockIsPercentileAgg.mockReturnValue(true); + }, + ], + [ + 'null if agg is valid percentile rank agg', + aggs[3], + () => { + mockIsPercentileRankAgg.mockReturnValue(true); + }, + ], + [ + 'null if agg is valid standart deviation agg', + aggs[4], + () => { + mockIsStdDevAgg.mockReturnValue(true); + }, + ], + ['null if agg is valid other metric agg', aggs[5], () => {}], + ])('should return %s and field type is not supported', (_, agg, actions) => { + actions(); + const field1: DataViewField = { + name: 'bytes', + type: 'geo', + esTypes: ['long'], + aggregatable: true, + searchable: true, + count: 10, + readFromDocValues: true, + scripted: false, + isMapped: true, + } as DataViewField; + + mockGetFieldByName.mockReturnValueOnce(field1); + + dataView.getFieldByName = mockGetFieldByName; + const result = getFormulaForPipelineAgg({ + agg: agg as SchemaConfig< + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.SUM_BUCKET + >, + aggs, + dataView, + }); + expect(result).toBeNull(); + }); + + test.each([ + [ + 'null if agg is valid pipeline agg', + aggs[0], + () => { + mockIsPipeline.mockReturnValue(true); + mockGetMetricFromParentPipelineAgg.mockReturnValueOnce({ + aggType: METRIC_TYPES.AVG, + aggParams: { + field, + }, + aggId: '2', + }); + }, + ], + [ + 'null if percentile rank agg is valid percentile agg', + aggs[2], + () => { + mockIsPercentileAgg.mockReturnValue(true); + }, + ], + [ + 'null if agg is valid percentile rank agg', + aggs[3], + () => { + mockIsPercentileRankAgg.mockReturnValue(true); + }, + ], + [ + 'null if agg is valid standart deviation agg', + aggs[4], + () => { + mockIsStdDevAgg.mockReturnValue(true); + }, + ], + ['null if agg is valid other metric agg', aggs[5], () => {}], + ])( + 'should return %s, field type is supported and field is not aggregatable', + (_, agg, actions) => { + actions(); + const field1: DataViewField = { + name: 'str', + type: 'string', + esTypes: ['text'], + aggregatable: false, + searchable: true, + count: 10, + readFromDocValues: true, + scripted: false, + isMapped: true, + } as DataViewField; + + mockGetFieldByName.mockReturnValueOnce(field1); + + dataView.getFieldByName = mockGetFieldByName; + const result = getFormulaForPipelineAgg({ + agg: agg as SchemaConfig< + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.SUM_BUCKET + >, + aggs, + dataView, + }); + expect(result).toBeNull(); + } + ); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.ts new file mode 100644 index 0000000000000..276ac54e2fc3d --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/formula.ts @@ -0,0 +1,258 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { DataView, DataViewField, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { isFieldValid, SchemaConfig } from '../../..'; +import { Operations } from '../../constants'; +import { isMetricWithField, getStdDeviationFormula, ExtendedColumnConverterArgs } from '../convert'; +import { getFormulaFromMetric, SUPPORTED_METRICS } from '../convert/supported_metrics'; +import { + getFieldNameFromField, + getMetricFromParentPipelineAgg, + isPercentileAgg, + isPercentileRankAgg, + isPipeline, + isStdDevAgg, +} from '../utils'; +import { SIBLING_PIPELINE_AGGS } from '../convert/constants'; + +type PipelineAggs = SchemaConfig< + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.SUM_BUCKET +>; + +type MetricAggsWithoutParams = SchemaConfig< + | METRIC_TYPES.AVG + | METRIC_TYPES.MAX + | METRIC_TYPES.MIN + | METRIC_TYPES.SUM + | METRIC_TYPES.CARDINALITY + | METRIC_TYPES.COUNT +>; + +export const addTimeRangeToFormula = (reducedTimeRange?: string) => { + return reducedTimeRange ? `, reducedTimeRange='${reducedTimeRange}'` : ''; +}; + +const PARENT_PIPELINE_OPS: string[] = [ + Operations.CUMULATIVE_SUM, + Operations.DIFFERENCES, + Operations.MOVING_AVERAGE, +]; + +const METRIC_OPS_WITHOUT_PARAMS: string[] = [ + Operations.AVERAGE, + Operations.MAX, + Operations.MIN, + Operations.SUM, + Operations.UNIQUE_COUNT, + Operations.COUNT, +]; + +const isDataViewField = (field: string | DataViewField): field is DataViewField => { + if (field && typeof field === 'object') { + return true; + } + return false; +}; + +const isValidAgg = (agg: SchemaConfig, dataView: DataView) => { + const aggregation = SUPPORTED_METRICS[agg.aggType]; + if (!aggregation) { + return false; + } + if (isMetricWithField(agg)) { + if (!agg.aggParams?.field) { + return false; + } + const sourceField = getFieldNameFromField(agg.aggParams?.field); + const field = dataView.getFieldByName(sourceField!); + if (!isFieldValid(field, aggregation)) { + return false; + } + } + + return true; +}; + +const getFormulaForAggsWithoutParams = ( + agg: SchemaConfig, + dataView: DataView, + selector: string | undefined, + reducedTimeRange?: string +) => { + const op = SUPPORTED_METRICS[agg.aggType]; + if (!isValidAgg(agg, dataView) || !op) { + return null; + } + + const formula = getFormulaFromMetric(op); + return `${formula}(${selector ?? ''}${addTimeRangeToFormula(reducedTimeRange)})`; +}; + +const getFormulaForPercentileRanks = ( + agg: SchemaConfig, + dataView: DataView, + selector: string | undefined, + reducedTimeRange?: string +) => { + const value = Number(agg.aggId?.split('.')[1]); + const op = SUPPORTED_METRICS[agg.aggType]; + if (!isValidAgg(agg, dataView) || !op) { + return null; + } + + const formula = getFormulaFromMetric(op); + return `${formula}(${selector}, value=${value}${addTimeRangeToFormula(reducedTimeRange)})`; +}; + +const getFormulaForPercentile = ( + agg: SchemaConfig, + dataView: DataView, + selector: string, + reducedTimeRange?: string +) => { + const percentile = Number(agg.aggId?.split('.')[1]); + const op = SUPPORTED_METRICS[agg.aggType]; + if (!isValidAgg(agg, dataView) || !op) { + return null; + } + + const formula = getFormulaFromMetric(op); + return `${formula}(${selector}, percentile=${percentile}${addTimeRangeToFormula( + reducedTimeRange + )})`; +}; + +const getFormulaForSubMetric = ({ + agg, + dataView, + aggs, +}: ExtendedColumnConverterArgs): string | null => { + const op = SUPPORTED_METRICS[agg.aggType]; + if (!op) { + return null; + } + + if ( + PARENT_PIPELINE_OPS.includes(op.name) || + SIBLING_PIPELINE_AGGS.includes(agg.aggType as METRIC_TYPES) + ) { + return getFormulaForPipelineAgg({ agg: agg as PipelineAggs, aggs, dataView }); + } + + if (METRIC_OPS_WITHOUT_PARAMS.includes(op.name)) { + const metricAgg = agg as MetricAggsWithoutParams; + return getFormulaForAggsWithoutParams( + metricAgg, + dataView, + metricAgg.aggParams && 'field' in metricAgg.aggParams + ? isDataViewField(metricAgg.aggParams.field) + ? metricAgg.aggParams?.field.displayName + : metricAgg.aggParams?.field + : undefined + ); + } + + if (op.name === Operations.PERCENTILE_RANK) { + const percentileRanksAgg = agg as SchemaConfig; + + return getFormulaForPercentileRanks( + percentileRanksAgg, + dataView, + percentileRanksAgg.aggParams?.field + ); + } + + return null; +}; + +export const getFormulaForPipelineAgg = ({ + agg, + dataView, + aggs, +}: ExtendedColumnConverterArgs< + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.SUM_BUCKET +>) => { + const { aggType } = agg; + const supportedAgg = SUPPORTED_METRICS[aggType]; + if (!supportedAgg) { + return null; + } + + const metricAgg = getMetricFromParentPipelineAgg(agg, aggs); + if (!metricAgg) { + return null; + } + + const subFormula = getFormulaForSubMetric({ + agg: metricAgg, + aggs, + dataView, + }); + if (subFormula === null) { + return null; + } + + if (PARENT_PIPELINE_OPS.includes(supportedAgg.name)) { + const formula = getFormulaFromMetric(supportedAgg); + return `${formula}(${subFormula})`; + } + + return subFormula; +}; + +export const getFormulaForAgg = ({ + agg, + aggs, + dataView, +}: ExtendedColumnConverterArgs) => { + if (isPipeline(agg)) { + return getFormulaForPipelineAgg({ agg, aggs, dataView }); + } + + if (isPercentileAgg(agg)) { + return getFormulaForPercentile( + agg, + dataView, + getFieldNameFromField(agg.aggParams?.field) ?? '' + ); + } + + if (isPercentileRankAgg(agg)) { + return getFormulaForPercentileRanks( + agg, + dataView, + getFieldNameFromField(agg.aggParams?.field) ?? '' + ); + } + + if (isStdDevAgg(agg) && agg.aggId) { + if (!isValidAgg(agg, dataView)) { + return null; + } + return getStdDeviationFormula(agg.aggId, getFieldNameFromField(agg.aggParams?.field) ?? ''); + } + + return getFormulaForAggsWithoutParams( + agg, + dataView, + isMetricWithField(agg) ? getFieldNameFromField(agg.aggParams?.field) ?? '' : '' + ); +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/index.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/index.ts new file mode 100644 index 0000000000000..c34e328332339 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { getFormulaForPipelineAgg } from './formula'; +export { convertMetricToColumns } from './metrics'; +export { getPercentageColumnFormulaColumn } from './percentage_formula'; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.test.ts new file mode 100644 index 0000000000000..659ab80ea03d5 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.test.ts @@ -0,0 +1,368 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { SchemaConfig } from '../../..'; +import { convertMetricToColumns } from './metrics'; + +const mockConvertMetricAggregationColumnWithoutSpecialParams = jest.fn(); +const mockConvertToOtherParentPipelineAggColumns = jest.fn(); +const mockConvertToPercentileColumn = jest.fn(); +const mockConvertToPercentileRankColumn = jest.fn(); +const mockConvertToSiblingPipelineColumns = jest.fn(); +const mockConvertToStdDeviationFormulaColumns = jest.fn(); +const mockConvertToLastValueColumn = jest.fn(); +const mockConvertToCumulativeSumAggColumn = jest.fn(); + +jest.mock('../convert', () => ({ + convertMetricAggregationColumnWithoutSpecialParams: jest.fn(() => + mockConvertMetricAggregationColumnWithoutSpecialParams() + ), + convertToOtherParentPipelineAggColumns: jest.fn(() => + mockConvertToOtherParentPipelineAggColumns() + ), + convertToPercentileColumn: jest.fn(() => mockConvertToPercentileColumn()), + convertToPercentileRankColumn: jest.fn(() => mockConvertToPercentileRankColumn()), + convertToSiblingPipelineColumns: jest.fn(() => mockConvertToSiblingPipelineColumns()), + convertToStdDeviationFormulaColumns: jest.fn(() => mockConvertToStdDeviationFormulaColumns()), + convertToLastValueColumn: jest.fn(() => mockConvertToLastValueColumn()), + convertToCumulativeSumAggColumn: jest.fn(() => mockConvertToCumulativeSumAggColumn()), +})); + +describe('convertMetricToColumns invalid cases', () => { + const dataView = stubLogstashDataView; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + beforeAll(() => { + mockConvertMetricAggregationColumnWithoutSpecialParams.mockReturnValue(null); + mockConvertToOtherParentPipelineAggColumns.mockReturnValue(null); + mockConvertToPercentileColumn.mockReturnValue(null); + mockConvertToPercentileRankColumn.mockReturnValue(null); + mockConvertToSiblingPipelineColumns.mockReturnValue(null); + mockConvertToStdDeviationFormulaColumns.mockReturnValue(null); + mockConvertToLastValueColumn.mockReturnValue(null); + mockConvertToCumulativeSumAggColumn.mockReturnValue(null); + }); + + test.each<[string, Parameters, null, jest.Mock | undefined]>([ + [ + 'null if agg is not supported', + [{ aggType: METRIC_TYPES.GEO_BOUNDS } as unknown as SchemaConfig, dataView, []], + null, + undefined, + ], + [ + 'null if supported agg AVG is not valid', + [{ aggType: METRIC_TYPES.AVG } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg MIN is not valid', + [{ aggType: METRIC_TYPES.MIN } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg MAX is not valid', + [{ aggType: METRIC_TYPES.MAX } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg SUM is not valid', + [{ aggType: METRIC_TYPES.SUM } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg COUNT is not valid', + [{ aggType: METRIC_TYPES.COUNT } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg CARDINALITY is not valid', + [{ aggType: METRIC_TYPES.CARDINALITY } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg VALUE_COUNT is not valid', + [{ aggType: METRIC_TYPES.VALUE_COUNT } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg MEDIAN is not valid', + [{ aggType: METRIC_TYPES.MEDIAN } as SchemaConfig, dataView, []], + null, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'null if supported agg STD_DEV is not valid', + [{ aggType: METRIC_TYPES.STD_DEV } as SchemaConfig, dataView, []], + null, + mockConvertToStdDeviationFormulaColumns, + ], + [ + 'null if supported agg PERCENTILES is not valid', + [{ aggType: METRIC_TYPES.PERCENTILES } as SchemaConfig, dataView, []], + null, + mockConvertToPercentileColumn, + ], + [ + 'null if supported agg SINGLE_PERCENTILE is not valid', + [{ aggType: METRIC_TYPES.SINGLE_PERCENTILE } as SchemaConfig, dataView, []], + null, + mockConvertToPercentileColumn, + ], + [ + 'null if supported agg PERCENTILE_RANKS is not valid', + [{ aggType: METRIC_TYPES.PERCENTILE_RANKS } as SchemaConfig, dataView, []], + null, + mockConvertToPercentileRankColumn, + ], + [ + 'null if supported agg SINGLE_PERCENTILE_RANK is not valid', + [{ aggType: METRIC_TYPES.SINGLE_PERCENTILE_RANK } as SchemaConfig, dataView, []], + null, + mockConvertToPercentileRankColumn, + ], + [ + 'null if supported agg TOP_HITS is not valid', + [{ aggType: METRIC_TYPES.TOP_HITS } as SchemaConfig, dataView, []], + null, + mockConvertToLastValueColumn, + ], + [ + 'null if supported agg TOP_METRICS is not valid', + [{ aggType: METRIC_TYPES.TOP_METRICS } as SchemaConfig, dataView, []], + null, + mockConvertToLastValueColumn, + ], + [ + 'null if supported agg CUMULATIVE_SUM is not valid', + [{ aggType: METRIC_TYPES.CUMULATIVE_SUM } as SchemaConfig, dataView, []], + null, + mockConvertToCumulativeSumAggColumn, + ], + [ + 'null if supported agg DERIVATIVE is not valid', + [{ aggType: METRIC_TYPES.DERIVATIVE } as SchemaConfig, dataView, []], + null, + mockConvertToOtherParentPipelineAggColumns, + ], + [ + 'null if supported agg MOVING_FN is not valid', + [{ aggType: METRIC_TYPES.MOVING_FN } as SchemaConfig, dataView, []], + null, + mockConvertToOtherParentPipelineAggColumns, + ], + [ + 'null if supported agg SUM_BUCKET is not valid', + [{ aggType: METRIC_TYPES.SUM_BUCKET } as SchemaConfig, dataView, []], + null, + mockConvertToSiblingPipelineColumns, + ], + [ + 'null if supported agg MIN_BUCKET is not valid', + [{ aggType: METRIC_TYPES.MIN_BUCKET } as SchemaConfig, dataView, []], + null, + mockConvertToSiblingPipelineColumns, + ], + [ + 'null if supported agg MAX_BUCKET is not valid', + [{ aggType: METRIC_TYPES.MAX_BUCKET } as SchemaConfig, dataView, []], + null, + mockConvertToSiblingPipelineColumns, + ], + [ + 'null if supported agg AVG_BUCKET is not valid', + [{ aggType: METRIC_TYPES.AVG_BUCKET } as SchemaConfig, dataView, []], + null, + mockConvertToSiblingPipelineColumns, + ], + [ + 'null if supported agg SERIAL_DIFF is not valid', + [{ aggType: METRIC_TYPES.SERIAL_DIFF } as SchemaConfig, dataView, []], + null, + undefined, + ], + ])('should return %s', (_, input, expected, mock) => { + expect(convertMetricToColumns(...input)).toBeNull(); + + if (mock) { + expect(mock).toBeCalledTimes(1); + } + }); +}); +describe('convertMetricToColumns valid cases', () => { + const dataView = stubLogstashDataView; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + const result = [{}]; + + beforeAll(() => { + mockConvertMetricAggregationColumnWithoutSpecialParams.mockReturnValue(result); + mockConvertToOtherParentPipelineAggColumns.mockReturnValue(result); + mockConvertToPercentileColumn.mockReturnValue(result); + mockConvertToPercentileRankColumn.mockReturnValue(result); + mockConvertToSiblingPipelineColumns.mockReturnValue(result); + mockConvertToStdDeviationFormulaColumns.mockReturnValue(result); + mockConvertToLastValueColumn.mockReturnValue(result); + mockConvertToCumulativeSumAggColumn.mockReturnValue(result); + }); + + test.each<[string, Parameters, Array<{}>, jest.Mock]>([ + [ + 'array of columns if supported agg AVG is valid', + [{ aggType: METRIC_TYPES.AVG } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg MIN is valid', + [{ aggType: METRIC_TYPES.MIN } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg MAX is valid', + [{ aggType: METRIC_TYPES.MAX } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg SUM is valid', + [{ aggType: METRIC_TYPES.SUM } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg COUNT is valid', + [{ aggType: METRIC_TYPES.COUNT } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg CARDINALITY is valid', + [{ aggType: METRIC_TYPES.CARDINALITY } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg VALUE_COUNT is valid', + [{ aggType: METRIC_TYPES.VALUE_COUNT } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg MEDIAN is valid', + [{ aggType: METRIC_TYPES.MEDIAN } as SchemaConfig, dataView, []], + result, + mockConvertMetricAggregationColumnWithoutSpecialParams, + ], + [ + 'array of columns if supported agg STD_DEV is valid', + [{ aggType: METRIC_TYPES.STD_DEV } as SchemaConfig, dataView, []], + result, + mockConvertToStdDeviationFormulaColumns, + ], + [ + 'array of columns if supported agg PERCENTILES is valid', + [{ aggType: METRIC_TYPES.PERCENTILES } as SchemaConfig, dataView, []], + result, + mockConvertToPercentileColumn, + ], + [ + 'array of columns if supported agg SINGLE_PERCENTILE is valid', + [{ aggType: METRIC_TYPES.SINGLE_PERCENTILE } as SchemaConfig, dataView, []], + result, + mockConvertToPercentileColumn, + ], + [ + 'array of columns if supported agg PERCENTILE_RANKS is valid', + [{ aggType: METRIC_TYPES.PERCENTILE_RANKS } as SchemaConfig, dataView, []], + result, + mockConvertToPercentileRankColumn, + ], + [ + 'array of columns if supported agg SINGLE_PERCENTILE_RANK is valid', + [{ aggType: METRIC_TYPES.SINGLE_PERCENTILE_RANK } as SchemaConfig, dataView, []], + result, + mockConvertToPercentileRankColumn, + ], + [ + 'array of columns if supported agg TOP_HITS is valid', + [{ aggType: METRIC_TYPES.TOP_HITS } as SchemaConfig, dataView, []], + result, + mockConvertToLastValueColumn, + ], + [ + 'array of columns if supported agg TOP_METRICS is valid', + [{ aggType: METRIC_TYPES.TOP_METRICS } as SchemaConfig, dataView, []], + result, + mockConvertToLastValueColumn, + ], + [ + 'array of columns if supported agg CUMULATIVE_SUM is valid', + [{ aggType: METRIC_TYPES.CUMULATIVE_SUM } as SchemaConfig, dataView, []], + result, + mockConvertToCumulativeSumAggColumn, + ], + [ + 'array of columns if supported agg DERIVATIVE is valid', + [{ aggType: METRIC_TYPES.DERIVATIVE } as SchemaConfig, dataView, []], + result, + mockConvertToOtherParentPipelineAggColumns, + ], + [ + 'array of columns if supported agg MOVING_FN is valid', + [{ aggType: METRIC_TYPES.MOVING_FN } as SchemaConfig, dataView, []], + result, + mockConvertToOtherParentPipelineAggColumns, + ], + [ + 'array of columns if supported agg SUM_BUCKET is valid', + [{ aggType: METRIC_TYPES.SUM_BUCKET } as SchemaConfig, dataView, []], + result, + mockConvertToSiblingPipelineColumns, + ], + [ + 'array of columns if supported agg MIN_BUCKET is valid', + [{ aggType: METRIC_TYPES.MIN_BUCKET } as SchemaConfig, dataView, []], + result, + mockConvertToSiblingPipelineColumns, + ], + [ + 'array of columns if supported agg MAX_BUCKET is valid', + [{ aggType: METRIC_TYPES.MAX_BUCKET } as SchemaConfig, dataView, []], + result, + mockConvertToSiblingPipelineColumns, + ], + [ + 'array of columns if supported agg AVG_BUCKET is valid', + [{ aggType: METRIC_TYPES.AVG_BUCKET } as SchemaConfig, dataView, []], + result, + mockConvertToSiblingPipelineColumns, + ], + ])('should return %s', (_, input, expected, mock) => { + expect(convertMetricToColumns(...input)).toEqual(expected.map(expect.objectContaining)); + if (mock) { + expect(mock).toBeCalledTimes(1); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.ts new file mode 100644 index 0000000000000..d97f81c4c8240 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/metrics.ts @@ -0,0 +1,127 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import type { DataView } from '@kbn/data-views-plugin/common'; +import { SchemaConfig } from '../../..'; +import { + convertMetricAggregationColumnWithoutSpecialParams, + convertToOtherParentPipelineAggColumns, + convertToPercentileColumn, + convertToPercentileRankColumn, + convertToSiblingPipelineColumns, + convertToStdDeviationFormulaColumns, + convertToLastValueColumn, + convertToCumulativeSumAggColumn, + AggBasedColumn, +} from '../convert'; +import { SUPPORTED_METRICS } from '../convert/supported_metrics'; +import { getValidColumns } from '../utils'; + +export const convertMetricToColumns = ( + agg: SchemaConfig, + dataView: DataView, + aggs: Array> +): AggBasedColumn[] | null => { + const supportedAgg = SUPPORTED_METRICS[agg.aggType]; + if (!supportedAgg) { + return null; + } + + switch (agg.aggType) { + case METRIC_TYPES.AVG: + case METRIC_TYPES.MIN: + case METRIC_TYPES.MAX: + case METRIC_TYPES.SUM: + case METRIC_TYPES.COUNT: + case METRIC_TYPES.CARDINALITY: + case METRIC_TYPES.VALUE_COUNT: + case METRIC_TYPES.MEDIAN: { + const columns = convertMetricAggregationColumnWithoutSpecialParams(supportedAgg, { + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.STD_DEV: { + const columns = convertToStdDeviationFormulaColumns({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.PERCENTILES: { + const columns = convertToPercentileColumn({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.SINGLE_PERCENTILE: { + const columns = convertToPercentileColumn({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.PERCENTILE_RANKS: { + const columns = convertToPercentileRankColumn({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.SINGLE_PERCENTILE_RANK: { + const columns = convertToPercentileRankColumn({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.TOP_HITS: + case METRIC_TYPES.TOP_METRICS: { + const columns = convertToLastValueColumn({ + agg, + dataView, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.CUMULATIVE_SUM: { + const columns = convertToCumulativeSumAggColumn({ + agg, + dataView, + aggs, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.DERIVATIVE: + case METRIC_TYPES.MOVING_FN: { + const columns = convertToOtherParentPipelineAggColumns({ + agg, + dataView, + aggs, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.SUM_BUCKET: + case METRIC_TYPES.MIN_BUCKET: + case METRIC_TYPES.MAX_BUCKET: + case METRIC_TYPES.AVG_BUCKET: { + const columns = convertToSiblingPipelineColumns({ + agg, + dataView, + aggs, + }); + return getValidColumns(columns); + } + case METRIC_TYPES.SERIAL_DIFF: + return null; + default: + return null; + } +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.test.ts new file mode 100644 index 0000000000000..9855ce44b6602 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.test.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { getPercentageColumnFormulaColumn } from './percentage_formula'; +import { FormulaColumn } from '../../types'; +import { SchemaConfig } from '../../..'; + +const mockGetFormulaForAgg = jest.fn(); +const mockCreateFormulaColumn = jest.fn(); + +jest.mock('./formula', () => ({ + getFormulaForAgg: jest.fn(() => mockGetFormulaForAgg()), +})); + +jest.mock('../convert', () => ({ + createFormulaColumn: jest.fn((formula) => mockCreateFormulaColumn(formula)), +})); + +describe('getPercentageColumnFormulaColumn', () => { + const dataView = stubLogstashDataView; + const field = stubLogstashDataView.fields[0].name; + const aggs: Array> = [ + { + aggId: '1', + aggType: METRIC_TYPES.AVG, + aggParams: { field }, + accessor: 0, + params: {}, + label: 'average', + format: {}, + }, + ]; + + afterEach(() => { + jest.clearAllMocks(); + }); + + test.each< + [ + string, + Parameters, + () => void, + Partial | null + ] + >([ + [ + 'null if cannot build formula for provided agg', + [{ agg: aggs[0], aggs, dataView }], + () => { + mockGetFormulaForAgg.mockReturnValue(null); + }, + null, + ], + [ + 'null if cannot create formula column for provided arguments', + [{ agg: aggs[0], aggs, dataView }], + () => { + mockGetFormulaForAgg.mockReturnValue('test-formula'); + mockCreateFormulaColumn.mockReturnValue(null); + }, + null, + ], + [ + 'formula column if provided arguments are valid', + [{ agg: aggs[0], aggs, dataView }], + () => { + mockGetFormulaForAgg.mockReturnValue('test-formula'); + mockCreateFormulaColumn.mockImplementation((formula) => ({ + operationType: 'formula', + params: { formula }, + label: 'Average', + })); + }, + { + operationType: 'formula', + params: { + formula: `(test-formula) / overall_sum(test-formula)`, + format: { id: 'percent' }, + }, + label: `Average percentages`, + }, + ], + ])('should return %s', (_, input, actions, expected) => { + actions(); + if (expected === null) { + expect(getPercentageColumnFormulaColumn(...input)).toBeNull(); + } else { + expect(getPercentageColumnFormulaColumn(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.ts b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.ts new file mode 100644 index 0000000000000..773851a770db4 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/metrics/percentage_formula.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { METRIC_TYPES } from '@kbn/data-plugin/common'; +import { createFormulaColumn, ExtendedColumnConverterArgs, FormulaColumn } from '../convert'; +import { getFormulaForAgg } from './formula'; + +export const getPercentageColumnFormulaColumn = ({ + agg, + aggs, + dataView, +}: ExtendedColumnConverterArgs): FormulaColumn | null => { + const metricFormula = getFormulaForAgg({ agg, aggs, dataView }); + if (!metricFormula) { + return null; + } + const formula = `(${metricFormula}) / overall_sum(${metricFormula})`; + + const formulaColumn = createFormulaColumn(formula, agg); + + if (!formulaColumn) { + return null; + } + + return { + ...formulaColumn, + params: { + ...formulaColumn.params, + format: { id: 'percent' }, + }, + label: `${formulaColumn?.label} percentages`, + }; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/utils.test.ts b/src/plugins/visualizations/common/convert_to_lens/lib/utils.test.ts new file mode 100644 index 0000000000000..73118b6ad4f03 --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/utils.test.ts @@ -0,0 +1,521 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { AggBasedColumn, ColumnWithMeta, Operations } from '../..'; +import { SchemaConfig } from '../../types'; +import { + getCustomBucketsFromSiblingAggs, + getFieldNameFromField, + getLabel, + getLabelForPercentile, + getMetricFromParentPipelineAgg, + getValidColumns, + isColumnWithMeta, + isMetricAggWithoutParams, + isPercentileAgg, + isPercentileRankAgg, + isPipeline, + isSchemaConfig, + isSiblingPipeline, + isStdDevAgg, +} from './utils'; + +describe('getLabel', () => { + const label = 'some label'; + const customLabel = 'some custom label'; + + const agg: SchemaConfig = { + accessor: 0, + label, + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggId: 'id', + aggParams: { field: 'some-field' }, + }; + + test('should return label', () => { + const { aggParams, ...aggWithoutAggParams } = agg; + expect(getLabel(aggWithoutAggParams)).toEqual(label); + expect(getLabel(agg)).toEqual(label); + expect(getLabel({ ...agg, aggParams: { ...aggParams!, customLabel: undefined } })).toEqual( + label + ); + }); + + test('should return customLabel', () => { + const aggParams = { ...agg.aggParams!, customLabel }; + const aggWithCustomLabel = { ...agg, aggParams }; + expect(getLabel(aggWithCustomLabel)).toEqual(customLabel); + }); +}); + +describe('getLabelForPercentile', () => { + const label = 'some label'; + const customLabel = 'some custom label'; + + const agg: SchemaConfig = { + accessor: 0, + label, + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.PERCENTILES, + aggId: 'id', + aggParams: { field: 'some-field' }, + }; + + test('should return empty string if no custom label is specified', () => { + const { aggParams, ...aggWithoutAggParams } = agg; + expect(getLabelForPercentile(aggWithoutAggParams)).toEqual(''); + expect(getLabel({ ...agg, aggParams: { ...aggParams!, customLabel: '' } })).toEqual(''); + }); + + test('should return label if custom label is specified', () => { + const aggParams = { ...agg.aggParams!, customLabel }; + const aggWithCustomLabel = { ...agg, aggParams }; + expect(getLabelForPercentile(aggWithCustomLabel)).toEqual(label); + }); +}); + +describe('getValidColumns', () => { + const dataView = stubLogstashDataView; + const columns: AggBasedColumn[] = [ + { + operationType: Operations.AVERAGE, + sourceField: dataView.fields[0].name, + columnId: 'some-id-0', + dataType: 'number', + params: {}, + meta: { aggId: 'aggId-0' }, + isSplit: false, + isBucketed: true, + }, + { + operationType: Operations.SUM, + sourceField: dataView.fields[0].name, + columnId: 'some-id-1', + dataType: 'number', + params: {}, + meta: { aggId: 'aggId-1' }, + isSplit: false, + isBucketed: true, + }, + ]; + test.each<[string, Parameters, AggBasedColumn[] | null]>([ + ['null if array contains null', [[null, ...columns]], null], + ['null if columns is null', [null], null], + ['null if columns is undefined', [undefined], null], + ['columns', [columns], columns], + ['columns if one column is passed', [columns[0]], [columns[0]]], + ])('should return %s', (_, input, expected) => { + if (expected === null) { + expect(getValidColumns(...input)).toBeNull(); + } else { + expect(getValidColumns(...input)).toEqual(expect.objectContaining(expected)); + } + }); +}); + +describe('getFieldNameFromField', () => { + test('should return null if no field is passed', () => { + expect(getFieldNameFromField(undefined)).toBeNull(); + }); + + test('should return field name if field is string', () => { + const fieldName = 'some-field-name'; + expect(getFieldNameFromField(fieldName)).toEqual(fieldName); + }); + + test('should return field name if field is DataViewField', () => { + const field = stubLogstashDataView.fields[0]; + expect(getFieldNameFromField(field)).toEqual(field.name); + }); +}); + +describe('isSchemaConfig', () => { + const iAggConfig = { + id: '', + enabled: false, + params: {}, + } as IAggConfig; + + const schemaConfig: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + test('should be false if is IAggConfig', () => { + expect(isSchemaConfig(iAggConfig)).toBeFalsy(); + }); + + test('should be false if is SchemaConfig', () => { + expect(isSchemaConfig(schemaConfig)).toBeTruthy(); + }); +}); + +describe('isColumnWithMeta', () => { + const column: AggBasedColumn = { + sourceField: '', + columnId: '', + operationType: 'terms', + isBucketed: false, + isSplit: false, + dataType: 'string', + } as AggBasedColumn; + + const columnWithMeta: ColumnWithMeta = { + sourceField: '', + columnId: '', + operationType: 'average', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'some-agg-id' }, + }; + + test('should return false if column without meta', () => { + expect(isColumnWithMeta(column)).toBeFalsy(); + }); + + test('should return true if column with meta', () => { + expect(isColumnWithMeta(columnWithMeta)).toBeTruthy(); + }); +}); + +describe('isSiblingPipeline', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.AVG_BUCKET, true], + [METRIC_TYPES.SUM_BUCKET, true], + [METRIC_TYPES.MAX_BUCKET, true], + [METRIC_TYPES.MIN_BUCKET, true], + [METRIC_TYPES.CUMULATIVE_SUM, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isSiblingPipeline({ ...metric, aggType } as SchemaConfig)).toBe( + expected + ); + }); +}); + +describe('isPipeline', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.AVG_BUCKET, true], + [METRIC_TYPES.SUM_BUCKET, true], + [METRIC_TYPES.MAX_BUCKET, true], + [METRIC_TYPES.MIN_BUCKET, true], + [METRIC_TYPES.CUMULATIVE_SUM, true], + [METRIC_TYPES.DERIVATIVE, true], + [METRIC_TYPES.MOVING_FN, true], + [METRIC_TYPES.AVG, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isPipeline({ ...metric, aggType } as SchemaConfig)).toBe(expected); + }); +}); + +describe('isMetricAggWithoutParams', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.AVG, true], + [METRIC_TYPES.COUNT, true], + [METRIC_TYPES.MAX, true], + [METRIC_TYPES.MIN, true], + [METRIC_TYPES.SUM, true], + [METRIC_TYPES.MEDIAN, true], + [METRIC_TYPES.CARDINALITY, true], + [METRIC_TYPES.VALUE_COUNT, true], + [METRIC_TYPES.DERIVATIVE, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isMetricAggWithoutParams({ ...metric, aggType } as SchemaConfig)).toBe( + expected + ); + }); +}); + +describe('isPercentileAgg', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.PERCENTILES, true], + [METRIC_TYPES.DERIVATIVE, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isPercentileAgg({ ...metric, aggType } as SchemaConfig)).toBe(expected); + }); +}); + +describe('isPercentileRankAgg', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.PERCENTILE_RANKS, true], + [METRIC_TYPES.PERCENTILES, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isPercentileRankAgg({ ...metric, aggType } as SchemaConfig)).toBe( + expected + ); + }); +}); + +describe('isStdDevAgg', () => { + const metric: Omit = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + test.each<[METRIC_TYPES, boolean]>([ + [METRIC_TYPES.STD_DEV, true], + [METRIC_TYPES.PERCENTILES, false], + ])('for %s should return %s', (aggType, expected) => { + expect(isStdDevAgg({ ...metric, aggType } as SchemaConfig)).toBe(expected); + }); +}); + +describe('getCustomBucketsFromSiblingAggs', () => { + const bucket1 = { + id: 'some-id', + params: { type: 'some-type' }, + type: 'type1', + enabled: true, + } as unknown as IAggConfig; + const serialize1 = () => bucket1; + + const bucket2 = { + id: 'some-id-1', + params: { type: 'some-type-1' }, + type: 'type2', + enabled: false, + } as unknown as IAggConfig; + const serialize2 = () => bucket2; + + const bucketWithSerialize1 = { ...bucket1, serialize: serialize1 } as unknown as IAggConfig; + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + aggId: 'some-agg-id', + aggParams: { + customBucket: bucketWithSerialize1, + }, + }; + + const bucketWithSerialize2 = { ...bucket2, serialize: serialize2 } as unknown as IAggConfig; + const metric2: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + aggId: 'some-agg-id', + aggParams: { + customBucket: bucketWithSerialize2, + }, + }; + const bucket3 = { ...bucket1, id: 'other id' } as unknown as IAggConfig; + const serialize3 = () => bucket3; + + const bucketWithSerialize3 = { ...bucket3, serialize: serialize3 } as unknown as IAggConfig; + const metric3: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + aggId: 'some-agg-id', + aggParams: { + customBucket: bucketWithSerialize3, + }, + }; + + test("should filter out duplicated custom buckets, ignoring id's", () => { + expect(getCustomBucketsFromSiblingAggs([metric1, metric2, metric3])).toEqual([ + bucketWithSerialize1, + bucketWithSerialize2, + ]); + }); +}); + +const mockConvertToSchemaConfig = jest.fn(); + +jest.mock('../../vis_schemas', () => ({ + convertToSchemaConfig: jest.fn(() => mockConvertToSchemaConfig()), +})); + +describe('getMetricFromParentPipelineAgg', () => { + const metricAggId = 'agg-id-0'; + const aggId = 'agg-id-1'; + const plainAgg: SchemaConfig = { + accessor: 0, + label: 'some-label', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + aggId: metricAggId, + }; + const agg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + aggParams: { customMetric: {} as IAggConfig }, + aggId, + }; + + const parentPipelineAgg: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.CUMULATIVE_SUM, + aggParams: { metricAgg: 'custom' }, + aggId, + }; + + const metric = { aggType: METRIC_TYPES.CUMULATIVE_SUM }; + beforeEach(() => { + jest.clearAllMocks(); + }); + + beforeAll(() => { + mockConvertToSchemaConfig.mockReturnValue(metric); + }); + + test('should return null if aggParams are undefined', () => { + expect(getMetricFromParentPipelineAgg({ ...agg, aggParams: undefined }, [])).toBeNull(); + expect(mockConvertToSchemaConfig).toBeCalledTimes(0); + }); + + test('should return null if is sibling pipeline agg and custom metric is not defined', () => { + expect( + getMetricFromParentPipelineAgg({ ...agg, aggParams: { customMetric: undefined } }, []) + ).toBeNull(); + expect(mockConvertToSchemaConfig).toBeCalledTimes(0); + }); + + test('should return null if is parent pipeline agg, metricAgg is custom and custom metric is not defined', () => { + expect(getMetricFromParentPipelineAgg(parentPipelineAgg, [])).toBeNull(); + expect(mockConvertToSchemaConfig).toBeCalledTimes(0); + }); + + test('should return metric if is parent pipeline agg, metricAgg is equal to aggId and custom metric is not defined', () => { + const parentPipelineAggWithLink = { + ...parentPipelineAgg, + aggParams: { + metricAgg: metricAggId, + }, + }; + expect( + getMetricFromParentPipelineAgg(parentPipelineAggWithLink, [ + parentPipelineAggWithLink, + plainAgg, + ]) + ).toEqual(plainAgg); + expect(mockConvertToSchemaConfig).toBeCalledTimes(0); + }); + + test('should return metric if sibling pipeline agg with custom metric', () => { + expect(getMetricFromParentPipelineAgg(agg, [agg])).toEqual(metric); + expect(mockConvertToSchemaConfig).toBeCalledTimes(1); + }); + + test('should return metric if parent pipeline agg with custom metric', () => { + expect( + getMetricFromParentPipelineAgg( + { + ...parentPipelineAgg, + aggParams: { ...parentPipelineAgg.aggParams, customMetric: {} as IAggConfig }, + }, + [agg] + ) + ).toEqual(metric); + expect(mockConvertToSchemaConfig).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/common/convert_to_lens/lib/utils.ts b/src/plugins/visualizations/common/convert_to_lens/lib/utils.ts new file mode 100644 index 0000000000000..c4e5c5474bf0c --- /dev/null +++ b/src/plugins/visualizations/common/convert_to_lens/lib/utils.ts @@ -0,0 +1,201 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { isEqual, omit } from 'lodash'; +import { IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { DataViewField } from '@kbn/data-views-plugin/common'; +import { DataViewFieldBase } from '@kbn/es-query'; +import { SchemaConfig } from '../../types'; +import { + AggBasedColumn, + MetricsWithoutSpecialParams, + ParentPipelineMetric, + SiblingPipelineMetric, +} from './convert'; +import { ColumnWithMeta } from '../types'; +import { convertToSchemaConfig } from '../../vis_schemas'; + +type UnwrapArray = T extends Array ? P : T; + +export const getLabel = (agg: SchemaConfig) => { + return agg.aggParams && 'customLabel' in agg.aggParams + ? agg.aggParams.customLabel ?? agg.label + : agg.label; +}; + +export const getLabelForPercentile = (agg: SchemaConfig) => { + return agg.aggParams && 'customLabel' in agg.aggParams && agg.aggParams.customLabel !== '' + ? agg.label + : ''; +}; + +export const getValidColumns = ( + columns: Array | AggBasedColumn | null | undefined +) => { + if (columns && Array.isArray(columns)) { + const nonNullColumns = columns.filter( + (c): c is Exclude, null> => c !== null + ); + + if (nonNullColumns.length !== columns.length) { + return null; + } + + return nonNullColumns; + } + + return columns ? [columns] : null; +}; + +export const getFieldNameFromField = ( + field: DataViewField | DataViewFieldBase | string | undefined +) => { + if (!field) { + return null; + } + + if (typeof field === 'string') { + return field; + } + + return field.name; +}; + +export const isSchemaConfig = (agg: SchemaConfig | IAggConfig): agg is SchemaConfig => { + if ((agg as SchemaConfig).aggType) { + return true; + } + return false; +}; + +export const isColumnWithMeta = ( + column: AggBasedColumn | ColumnWithMeta +): column is ColumnWithMeta => { + if ((column as ColumnWithMeta).meta) { + return true; + } + return false; +}; + +const SIBBLING_PIPELINE_AGGS: string[] = [ + METRIC_TYPES.AVG_BUCKET, + METRIC_TYPES.SUM_BUCKET, + METRIC_TYPES.MAX_BUCKET, + METRIC_TYPES.MIN_BUCKET, +]; + +const PARENT_PIPELINE_AGGS: string[] = [ + METRIC_TYPES.CUMULATIVE_SUM, + METRIC_TYPES.DERIVATIVE, + METRIC_TYPES.MOVING_FN, +]; + +const AGGS_WITHOUT_SPECIAL_RARAMS: string[] = [ + METRIC_TYPES.AVG, + METRIC_TYPES.COUNT, + METRIC_TYPES.MAX, + METRIC_TYPES.MIN, + METRIC_TYPES.SUM, + METRIC_TYPES.MEDIAN, + METRIC_TYPES.CARDINALITY, + METRIC_TYPES.VALUE_COUNT, +]; + +const PIPELINE_AGGS: string[] = [...SIBBLING_PIPELINE_AGGS, ...PARENT_PIPELINE_AGGS]; + +export const isSiblingPipeline = ( + metric: SchemaConfig +): metric is SchemaConfig => { + return SIBBLING_PIPELINE_AGGS.includes(metric.aggType); +}; + +export const isPipeline = ( + metric: SchemaConfig +): metric is SchemaConfig< + | METRIC_TYPES.CUMULATIVE_SUM + | METRIC_TYPES.DERIVATIVE + | METRIC_TYPES.MOVING_FN + | METRIC_TYPES.AVG_BUCKET + | METRIC_TYPES.MAX_BUCKET + | METRIC_TYPES.MIN_BUCKET + | METRIC_TYPES.SUM_BUCKET +> => { + return PIPELINE_AGGS.includes(metric.aggType); +}; + +export const isMetricAggWithoutParams = ( + metric: SchemaConfig +): metric is SchemaConfig => { + return AGGS_WITHOUT_SPECIAL_RARAMS.includes(metric.aggType); +}; + +export const isPercentileAgg = ( + metric: SchemaConfig +): metric is SchemaConfig => { + return metric.aggType === METRIC_TYPES.PERCENTILES; +}; + +export const isPercentileRankAgg = ( + metric: SchemaConfig +): metric is SchemaConfig => { + return metric.aggType === METRIC_TYPES.PERCENTILE_RANKS; +}; + +export const isStdDevAgg = (metric: SchemaConfig): metric is SchemaConfig => { + return metric.aggType === METRIC_TYPES.STD_DEV; +}; + +export const getCustomBucketsFromSiblingAggs = (metrics: SchemaConfig[]) => { + return metrics.reduce((acc, metric) => { + if ( + isSiblingPipeline(metric) && + metric.aggParams?.customBucket && + acc.every( + (bucket) => + !isEqual( + omit(metric.aggParams?.customBucket?.serialize(), ['id']), + omit(bucket.serialize(), ['id']) + ) + ) + ) { + acc.push(metric.aggParams.customBucket); + } + + return acc; + }, []); +}; + +export const getMetricFromParentPipelineAgg = ( + agg: SchemaConfig, + aggs: Array> +): SchemaConfig | null => { + if (!agg.aggParams) { + return null; + } + + if (isSiblingPipeline(agg)) { + if (agg.aggParams.customMetric) { + return convertToSchemaConfig(agg.aggParams.customMetric); + } + return null; + } + + const { customMetric, metricAgg } = agg.aggParams; + if (!customMetric && metricAgg === 'custom') { + return null; + } + + let metric; + if (!customMetric) { + metric = aggs.find(({ aggId }) => aggId === metricAgg); + } else { + metric = convertToSchemaConfig(customMetric); + } + + return metric as SchemaConfig; +}; diff --git a/src/plugins/visualizations/common/convert_to_lens/types/columns.ts b/src/plugins/visualizations/common/convert_to_lens/types/columns.ts index 6817e216e762d..735fe3f33b527 100644 --- a/src/plugins/visualizations/common/convert_to_lens/types/columns.ts +++ b/src/plugins/visualizations/common/convert_to_lens/types/columns.ts @@ -109,5 +109,9 @@ export type AnyColumnWithReferences = export type Column = AnyColumnWithReferences | AnyColumnWithSourceField | FiltersColumn; -export type ColumnWithMeta = Col & - (Meta extends undefined ? undefined : { meta: Meta }); +export type GenericColumnWithMeta< + Col extends Column | {}, + Meta extends {} | unknown = undefined +> = Col & (Meta extends undefined ? undefined : { meta: Meta }); + +export type ColumnWithMeta = GenericColumnWithMeta; diff --git a/src/plugins/visualizations/common/convert_to_lens/types/common.ts b/src/plugins/visualizations/common/convert_to_lens/types/common.ts index 974326834ce2a..d792467e298d0 100644 --- a/src/plugins/visualizations/common/convert_to_lens/types/common.ts +++ b/src/plugins/visualizations/common/convert_to_lens/types/common.ts @@ -29,7 +29,7 @@ export interface FilterQuery { export interface Filter { input: FilterQuery; - label: string; + label?: string; } export interface Range { diff --git a/src/plugins/visualizations/common/convert_to_lens/types/configurations.ts b/src/plugins/visualizations/common/convert_to_lens/types/configurations.ts index 4702ebae80826..a6a771d07e7a6 100644 --- a/src/plugins/visualizations/common/convert_to_lens/types/configurations.ts +++ b/src/plugins/visualizations/common/convert_to_lens/types/configurations.ts @@ -6,48 +6,32 @@ * Side Public License, v 1. */ -import { HorizontalAlignment, Position, VerticalAlignment } from '@elastic/charts'; +import { HorizontalAlignment, LayoutDirection, Position, VerticalAlignment } from '@elastic/charts'; import { $Values } from '@kbn/utility-types'; -import type { PaletteOutput } from '@kbn/coloring'; +import type { CustomPaletteParams, PaletteOutput } from '@kbn/coloring'; import { KibanaQueryOutput } from '@kbn/data-plugin/common'; import { LegendSize } from '../../constants'; - -export const XYCurveTypes = { - LINEAR: 'LINEAR', - CURVE_MONOTONE_X: 'CURVE_MONOTONE_X', - CURVE_STEP_AFTER: 'CURVE_STEP_AFTER', -} as const; - -export const YAxisModes = { - AUTO: 'auto', - LEFT: 'left', - RIGHT: 'right', - BOTTOM: 'bottom', -} as const; - -export const SeriesTypes = { - BAR: 'bar', - LINE: 'line', - AREA: 'area', - BAR_STACKED: 'bar_stacked', - AREA_STACKED: 'area_stacked', - BAR_HORIZONTAL: 'bar_horizontal', - BAR_PERCENTAGE_STACKED: 'bar_percentage_stacked', - BAR_HORIZONTAL_STACKED: 'bar_horizontal_stacked', - AREA_PERCENTAGE_STACKED: 'area_percentage_stacked', - BAR_HORIZONTAL_PERCENTAGE_STACKED: 'bar_horizontal_percentage_stacked', -} as const; - -export const FillTypes = { - NONE: 'none', - ABOVE: 'above', - BELOW: 'below', -} as const; +import { + CategoryDisplayTypes, + PartitionChartTypes, + NumberDisplayTypes, + LegendDisplayTypes, + FillTypes, + SeriesTypes, + YAxisModes, + XYCurveTypes, + LayerTypes, +} from '../constants'; export type FillType = $Values; export type SeriesType = $Values; export type YAxisMode = $Values; export type XYCurveType = $Values; +export type PartitionChartType = $Values; +export type CategoryDisplayType = $Values; +export type NumberDisplayType = $Values; +export type LegendDisplayType = $Values; +export type LayerType = $Values; export interface AxisExtentConfig { mode: 'full' | 'custom' | 'dataBounds'; @@ -170,4 +154,81 @@ export interface XYConfiguration { valuesInLegend?: boolean; } -export type Configuration = XYConfiguration; +export interface SortingState { + columnId: string | undefined; + direction: 'asc' | 'desc' | 'none'; +} + +export interface PagingState { + size: number; + enabled: boolean; +} + +export interface ColumnState { + columnId: string; + summaryRow?: 'none' | 'sum' | 'avg' | 'count' | 'min' | 'max'; + alignment?: 'left' | 'right' | 'center'; + collapseFn?: string; +} + +export interface TableVisConfiguration { + columns: ColumnState[]; + layerId: string; + layerType: 'data'; + sorting?: SortingState; + rowHeight?: 'auto' | 'single' | 'custom'; + headerRowHeight?: 'auto' | 'single' | 'custom'; + rowHeightLines?: number; + headerRowHeightLines?: number; + paging?: PagingState; +} + +export interface MetricVisConfiguration { + layerId: string; + layerType: 'data'; + metricAccessor?: string; + secondaryMetricAccessor?: string; + maxAccessor?: string; + breakdownByAccessor?: string; + // the dimensions can optionally be single numbers + // computed by collapsing all rows + collapseFn?: string; + subtitle?: string; + secondaryPrefix?: string; + progressDirection?: LayoutDirection; + color?: string; + palette?: PaletteOutput; + maxCols?: number; +} + +export interface PartitionLayerState { + layerId: string; + layerType: LayerType; + primaryGroups: string[]; + secondaryGroups?: string[]; + metric?: string; + collapseFns?: Record; + numberDisplay: NumberDisplayType; + categoryDisplay: CategoryDisplayType; + legendDisplay: LegendDisplayType; + legendPosition?: Position; + showValuesInLegend?: boolean; + nestedLegend?: boolean; + percentDecimals?: number; + emptySizeRatio?: number; + legendMaxLines?: number; + legendSize?: LegendSize; + truncateLegend?: boolean; +} + +export interface PartitionVisConfiguration { + shape: PartitionChartType; + layers: PartitionLayerState[]; + palette?: PaletteOutput; +} + +export type Configuration = + | XYConfiguration + | TableVisConfiguration + | PartitionVisConfiguration + | MetricVisConfiguration; diff --git a/src/plugins/visualizations/common/convert_to_lens/types/context.ts b/src/plugins/visualizations/common/convert_to_lens/types/context.ts index 037d1c8c96a1c..c894f95596983 100644 --- a/src/plugins/visualizations/common/convert_to_lens/types/context.ts +++ b/src/plugins/visualizations/common/convert_to_lens/types/context.ts @@ -20,4 +20,5 @@ export interface NavigateToLensContext layers: Layer[]; type: string; configuration: T; + indexPatternIds: string[]; } diff --git a/src/plugins/visualizations/common/convert_to_lens/types/params.ts b/src/plugins/visualizations/common/convert_to_lens/types/params.ts index 6fc49d30fe02e..d66822921fb19 100644 --- a/src/plugins/visualizations/common/convert_to_lens/types/params.ts +++ b/src/plugins/visualizations/common/convert_to_lens/types/params.ts @@ -6,9 +6,13 @@ * Side Public License, v 1. */ +import { $Values } from '@kbn/utility-types'; +import { RANGE_MODES } from '../constants'; import { Column } from './columns'; import { Filter, NumberValueFormat } from './common'; +export type RangeMode = $Values; + export interface FormatParams { format?: NumberValueFormat; } @@ -17,21 +21,6 @@ export interface FiltersParams { filters: Filter[]; } -export interface RangeParams extends FormatParams { - type: 'histogram' | 'range'; - maxBars: 'auto' | number; - ranges: Range[]; - includeEmptyRows?: boolean; - parentFormat?: { - id: string; - params?: { - id?: string; - template?: string; - replaceInfinity?: boolean; - }; - }; -} - export interface TermsParams extends FormatParams { size: number; include?: string[] | number[]; @@ -58,6 +47,22 @@ export interface DateHistogramParams { dropPartials?: boolean; } +interface Range { + from: number | null; + to: number | null; + label?: string; +} +export interface RangeParams extends FormatParams { + type: RangeMode; + maxBars: 'auto' | number; + ranges: Range[]; + includeEmptyRows?: boolean; + parentFormat?: { + id: string; + params?: { id?: string; template?: string; replaceInfinity?: boolean }; + }; +} + export type MinParams = FormatParams; export type MaxParams = FormatParams; export type AvgParams = FormatParams; diff --git a/src/plugins/visualizations/common/convert_to_lens/utils.ts b/src/plugins/visualizations/common/convert_to_lens/utils.ts index 1beba70bc2a1b..3536282d830d3 100644 --- a/src/plugins/visualizations/common/convert_to_lens/utils.ts +++ b/src/plugins/visualizations/common/convert_to_lens/utils.ts @@ -6,8 +6,28 @@ * Side Public License, v 1. */ -import { XYAnnotationsLayerConfig, XYLayerConfig } from './types'; +import { DataViewField } from '@kbn/data-views-plugin/common'; +import { SupportedMetric } from './lib/convert/supported_metrics'; +import { Layer, XYAnnotationsLayerConfig, XYLayerConfig } from './types'; export const isAnnotationsLayer = ( layer: Pick ): layer is XYAnnotationsLayerConfig => layer.layerType === 'annotations'; + +export const getIndexPatternIds = (layers: Layer[]) => + layers.map(({ indexPatternId }) => indexPatternId); + +export const isFieldValid = ( + field: DataViewField | undefined, + aggregation: SupportedMetric +): field is DataViewField => { + if (!field && aggregation.isFieldRequired) { + return false; + } + + if (field && (!field.aggregatable || !aggregation.supportedDataTypes.includes(field.type))) { + return false; + } + + return true; +}; diff --git a/src/plugins/visualizations/common/index.ts b/src/plugins/visualizations/common/index.ts index dde60809ea593..90ea3f6dca0a1 100644 --- a/src/plugins/visualizations/common/index.ts +++ b/src/plugins/visualizations/common/index.ts @@ -14,5 +14,6 @@ export * from './types'; export * from './utils'; export * from './expression_functions'; export * from './convert_to_lens'; +export { convertToSchemaConfig } from './vis_schemas'; export { LegendSize, LegendSizeToPixels, DEFAULT_LEGEND_SIZE } from './constants'; diff --git a/src/plugins/visualizations/common/types.ts b/src/plugins/visualizations/common/types.ts index 8aa03470b2094..12407f0966cd7 100644 --- a/src/plugins/visualizations/common/types.ts +++ b/src/plugins/visualizations/common/types.ts @@ -7,7 +7,14 @@ */ import type { SerializableRecord } from '@kbn/utility-types'; -import type { AggConfigSerialized, SerializedSearchSourceFields } from '@kbn/data-plugin/common'; +import { + AggParamsMapping, + AggConfigSerialized, + SerializedSearchSourceFields, + METRIC_TYPES, + BUCKET_TYPES, +} from '@kbn/data-plugin/common'; +import type { SerializedFieldFormat } from '@kbn/field-formats-plugin/common'; import type { SavedObjectAttributes } from '@kbn/core/types'; export interface VisParams { @@ -49,3 +56,26 @@ export interface SerializedVis { uiState?: any; data: SerializedVisData; } +interface SchemaConfigParams { + precision?: number; + useGeocentroid?: boolean; +} + +export type SupportedAggregation = METRIC_TYPES | BUCKET_TYPES; + +type SchemasByAggs = { + [Agg in Aggs]: GenericSchemaConfig; +}[Aggs]; + +export interface GenericSchemaConfig { + accessor: number; + label: string; + format: SerializedFieldFormat; + params: SchemaConfigParams; + aggType: Agg; + aggId?: string; + aggParams?: AggParamsMapping[Agg]; +} + +export type SchemaConfig = + SchemasByAggs; diff --git a/src/plugins/visualizations/common/vis_schemas.ts b/src/plugins/visualizations/common/vis_schemas.ts new file mode 100644 index 0000000000000..cdccc7902e08d --- /dev/null +++ b/src/plugins/visualizations/common/vis_schemas.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { IAggConfig, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { SchemaConfig, SupportedAggregation } from './types'; + +interface SchemaConfigParams { + precision?: number; + useGeocentroid?: boolean; +} + +export function convertToSchemaConfig(agg: IAggConfig): SchemaConfig { + const aggType = agg.type.name as SupportedAggregation; + const hasSubAgg = [ + 'derivative', + 'moving_avg', + 'serial_diff', + 'cumulative_sum', + 'sum_bucket', + 'avg_bucket', + 'min_bucket', + 'max_bucket', + ].includes(aggType); + + const formatAgg = hasSubAgg + ? agg.params.customMetric || agg.aggConfigs.getRequestAggById(agg.params.metricAgg) + : agg; + + const params: SchemaConfigParams = {}; + + if (aggType === 'geohash_grid') { + params.precision = agg.params.precision; + params.useGeocentroid = agg.params.useGeocentroid; + } + + const label = agg.makeLabel && agg.makeLabel(); + return { + accessor: 0, + format: formatAgg.toSerializedFieldFormat(), + params, + label, + aggType, + aggId: agg.id, + aggParams: agg.params, + } as SchemaConfig; +} diff --git a/src/plugins/visualizations/public/convert_to_lens/datasource.ts b/src/plugins/visualizations/public/convert_to_lens/datasource.ts new file mode 100644 index 0000000000000..502632651170d --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/datasource.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; + +export const getDataViewByIndexPatternId = async ( + indexPatternId: string | undefined, + dataViews: DataViewsPublicPluginStart +) => { + try { + return indexPatternId ? await dataViews.get(indexPatternId) : await dataViews.getDefault(); + } catch (err) { + return null; + } +}; diff --git a/src/plugins/visualizations/public/convert_to_lens/index.ts b/src/plugins/visualizations/public/convert_to_lens/index.ts new file mode 100644 index 0000000000000..9cd2ba2768ad7 --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { getColumnsFromVis } from './schemas'; +export { getPercentageColumnFormulaColumn } from '../../common/convert_to_lens/lib'; diff --git a/src/plugins/visualizations/public/convert_to_lens/schemas.test.ts b/src/plugins/visualizations/public/convert_to_lens/schemas.test.ts new file mode 100644 index 0000000000000..5b8b7832730b9 --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/schemas.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { + AggConfig, + AggConfigOptions, + AggConfigs, + AggConfigsOptions, + GetConfigFn, +} from '@kbn/data-plugin/common'; +import { dataPluginMock } from '@kbn/data-plugin/public/mocks'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import type { Vis } from '../vis'; +import { getColumnsFromVis } from './schemas'; + +const mockConvertMetricToColumns = jest.fn(); +const mockConvertBucketToColumns = jest.fn(); +const mockGetCutomBucketsFromSiblingAggs = jest.fn(); +const mockGetVisSchemas = jest.fn(); + +const mockGetBucketCollapseFn = jest.fn(); +const mockGetBucketColumns = jest.fn(); +const mockGetColumnIds = jest.fn(); +const mockGetColumnsWithoutReferenced = jest.fn(); +const mockGetMetricsWithoutDuplicates = jest.fn(); +const mockIsValidVis = jest.fn(); +const mockSortColumns = jest.fn(); + +jest.mock('../../common/convert_to_lens/lib/metrics', () => ({ + convertMetricToColumns: jest.fn(() => mockConvertMetricToColumns()), +})); + +jest.mock('../../common/convert_to_lens/lib/buckets', () => ({ + convertBucketToColumns: jest.fn(() => mockConvertBucketToColumns()), +})); + +jest.mock('../../common/convert_to_lens/lib/utils', () => ({ + getCustomBucketsFromSiblingAggs: jest.fn(() => mockGetCutomBucketsFromSiblingAggs()), +})); + +jest.mock('../vis_schemas', () => ({ + getVisSchemas: jest.fn(() => mockGetVisSchemas()), +})); + +jest.mock('./utils', () => ({ + getBucketCollapseFn: jest.fn(() => mockGetBucketCollapseFn()), + getBucketColumns: jest.fn(() => mockGetBucketColumns()), + getColumnIds: jest.fn(() => mockGetColumnIds()), + getColumnsWithoutReferenced: jest.fn(() => mockGetColumnsWithoutReferenced()), + getMetricsWithoutDuplicates: jest.fn(() => mockGetMetricsWithoutDuplicates()), + isValidVis: jest.fn(() => mockIsValidVis()), + sortColumns: jest.fn(() => mockSortColumns()), +})); + +describe('getColumnsFromVis', () => { + const dataServiceMock = dataPluginMock.createStartContract(); + const dataView = stubLogstashDataView; + const aggConfigs = new AggConfigs( + dataView, + [], + {} as AggConfigsOptions, + (() => ({})) as GetConfigFn + ); + const aggConfig = new AggConfig(aggConfigs, {} as AggConfigOptions); + + const vis = {} as Vis; + beforeEach(() => { + jest.clearAllMocks(); + mockGetVisSchemas.mockReturnValue({}); + mockIsValidVis.mockReturnValue(true); + }); + + test('should return null if vis is not valid', () => { + mockIsValidVis.mockReturnValue(false); + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(0); + }); + + test('should return null if multiple different sibling aggs was provided', () => { + const buckets: AggConfig[] = [aggConfig, aggConfig]; + mockGetCutomBucketsFromSiblingAggs.mockReturnValue(buckets); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(0); + }); + + test('should return null if one sibling agg was provided and it is not supported', () => { + const buckets: AggConfig[] = [aggConfig]; + mockGetCutomBucketsFromSiblingAggs.mockReturnValue(buckets); + mockConvertBucketToColumns.mockReturnValue(null); + mockGetMetricsWithoutDuplicates.mockReturnValue([{}]); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(1); + expect(mockConvertBucketToColumns).toBeCalledTimes(1); + expect(mockGetBucketColumns).toBeCalledTimes(0); + }); + + test('should return null if metrics are not supported', () => { + const buckets: AggConfig[] = [aggConfig]; + mockGetCutomBucketsFromSiblingAggs.mockReturnValue(buckets); + mockGetMetricsWithoutDuplicates.mockReturnValue([{}]); + mockConvertMetricToColumns.mockReturnValue([null, {}]); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + expect(mockGetBucketColumns).toBeCalledTimes(0); + }); + + test('should return null if buckets are not supported', () => { + const buckets: AggConfig[] = [aggConfig]; + mockGetCutomBucketsFromSiblingAggs.mockReturnValue(buckets); + mockConvertBucketToColumns.mockReturnValue({}); + mockGetMetricsWithoutDuplicates.mockReturnValue([{}]); + mockConvertMetricToColumns.mockReturnValue([{}]); + mockGetBucketColumns.mockReturnValue(null); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + expect(mockGetBucketColumns).toBeCalledTimes(1); + }); + + test('should return null if splits are not supported', () => { + const buckets: AggConfig[] = [aggConfig]; + mockGetCutomBucketsFromSiblingAggs.mockReturnValue(buckets); + mockConvertBucketToColumns.mockReturnValue({}); + mockGetMetricsWithoutDuplicates.mockReturnValue([{}]); + mockConvertMetricToColumns.mockReturnValue([{}]); + mockGetBucketColumns.mockReturnValueOnce([{}]); + mockGetBucketColumns.mockReturnValueOnce(null); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toBeNull(); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + expect(mockGetBucketColumns).toBeCalledTimes(2); + expect(mockSortColumns).toBeCalledTimes(0); + }); + + test('should return columns', () => { + const buckets: AggConfig[] = [aggConfig]; + const bucketColumns = [ + { + sourceField: 'some-field', + columnId: 'col3', + operationType: 'date_histogram', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: { interval: '1h' }, + meta: { aggId: 'agg-id-1' }, + }, + ]; + const metrics = [ + { + sourceField: 'some-field', + columnId: 'col2', + operationType: 'max', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'col-id-3' }, + }, + ]; + + const columnsWithoutReferenced = ['col2']; + const metricId = 'metric1'; + const bucketId = 'bucket1'; + const bucketCollapseFn = 'max'; + + mockGetCutomBucketsFromSiblingAggs.mockReturnValue([]); + mockGetMetricsWithoutDuplicates.mockReturnValue(metrics); + mockConvertMetricToColumns.mockReturnValue(metrics); + mockConvertBucketToColumns.mockReturnValue(bucketColumns); + mockGetBucketColumns.mockReturnValue(bucketColumns); + mockGetColumnsWithoutReferenced.mockReturnValue(columnsWithoutReferenced); + mockSortColumns.mockReturnValue([...metrics, ...buckets]); + mockGetColumnIds.mockReturnValueOnce([metricId]); + mockGetColumnIds.mockReturnValueOnce([bucketId]); + mockGetBucketCollapseFn.mockReturnValueOnce(bucketCollapseFn); + + const result = getColumnsFromVis(vis, dataServiceMock.query.timefilter.timefilter, dataView, { + splits: [], + buckets: [], + }); + + expect(result).toEqual({ + bucketCollapseFn, + buckets: [bucketId], + columns: [...metrics, ...buckets], + columnsWithoutReferenced, + metrics: [metricId], + }); + expect(mockGetVisSchemas).toBeCalledTimes(1); + expect(mockIsValidVis).toBeCalledTimes(1); + expect(mockGetCutomBucketsFromSiblingAggs).toBeCalledTimes(1); + expect(mockGetMetricsWithoutDuplicates).toBeCalledTimes(1); + expect(mockConvertMetricToColumns).toBeCalledTimes(1); + expect(mockGetBucketColumns).toBeCalledTimes(2); + expect(mockSortColumns).toBeCalledTimes(1); + expect(mockGetColumnsWithoutReferenced).toBeCalledTimes(1); + }); +}); diff --git a/src/plugins/visualizations/public/convert_to_lens/schemas.ts b/src/plugins/visualizations/public/convert_to_lens/schemas.ts new file mode 100644 index 0000000000000..56108b1a1d63f --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/schemas.ts @@ -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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { DataView } from '@kbn/data-views-plugin/common'; +import { METRIC_TYPES, TimefilterContract } from '@kbn/data-plugin/public'; +import { AggBasedColumn, SchemaConfig } from '../../common'; +import { convertMetricToColumns } from '../../common/convert_to_lens/lib/metrics'; +import { convertBucketToColumns } from '../../common/convert_to_lens/lib/buckets'; +import { getCustomBucketsFromSiblingAggs } from '../../common/convert_to_lens/lib/utils'; +import type { Vis } from '../types'; +import { getVisSchemas, Schemas } from '../vis_schemas'; +import { + getBucketCollapseFn, + getBucketColumns, + getColumnIds, + getColumnsWithoutReferenced, + getMetricsWithoutDuplicates, + isValidVis, + sortColumns, +} from './utils'; + +const areVisSchemasValid = (visSchemas: Schemas, unsupported: Array) => { + const usedUnsupportedSchemas = unsupported.filter( + (schema) => visSchemas[schema] && visSchemas[schema]?.length + ); + return !usedUnsupportedSchemas.length; +}; + +export const getColumnsFromVis = ( + vis: Vis, + timefilter: TimefilterContract, + dataView: DataView, + { + splits = [], + buckets = [], + unsupported = [], + }: { + splits?: Array; + buckets?: Array; + unsupported?: Array; + } = {}, + config?: { + dropEmptyRowsInDateHistogram?: boolean; + } +) => { + const visSchemas = getVisSchemas(vis, { + timefilter, + timeRange: timefilter.getAbsoluteTime(), + }); + + if (!isValidVis(visSchemas) || !areVisSchemasValid(visSchemas, unsupported)) { + return null; + } + + const customBuckets = getCustomBucketsFromSiblingAggs(visSchemas.metric); + + // doesn't support sibbling pipeline aggs with different bucket aggs + if (customBuckets.length > 1) { + return null; + } + + const metricsWithoutDuplicates = getMetricsWithoutDuplicates(visSchemas.metric); + const aggs = metricsWithoutDuplicates as Array>; + + const metricColumns = metricsWithoutDuplicates.flatMap((m) => + convertMetricToColumns(m, dataView, aggs) + ); + + if (metricColumns.includes(null)) { + return null; + } + const metrics = metricColumns as AggBasedColumn[]; + const customBucketColumns = []; + + if (customBuckets.length) { + const customBucketColumn = convertBucketToColumns( + { agg: customBuckets[0], dataView, metricColumns: metrics, aggs }, + false, + config?.dropEmptyRowsInDateHistogram + ); + if (!customBucketColumn) { + return null; + } + customBucketColumns.push(customBucketColumn); + } + + const bucketColumns = getBucketColumns( + visSchemas, + buckets, + dataView, + false, + metricColumns as AggBasedColumn[], + config?.dropEmptyRowsInDateHistogram + ); + if (!bucketColumns) { + return null; + } + + const splitBucketColumns = getBucketColumns( + visSchemas, + splits, + dataView, + true, + metricColumns as AggBasedColumn[], + config?.dropEmptyRowsInDateHistogram + ); + if (!splitBucketColumns) { + return null; + } + + const columns = sortColumns( + [...metrics, ...bucketColumns, ...splitBucketColumns, ...customBucketColumns], + visSchemas, + [...buckets, ...splits], + metricsWithoutDuplicates + ); + + const columnsWithoutReferenced = getColumnsWithoutReferenced(columns); + + return { + metrics: getColumnIds(columnsWithoutReferenced.filter((с) => !с.isBucketed)), + buckets: getColumnIds(columnsWithoutReferenced.filter((c) => c.isBucketed)), + bucketCollapseFn: getBucketCollapseFn(visSchemas.metric, customBucketColumns), + columnsWithoutReferenced, + columns, + }; +}; diff --git a/src/plugins/visualizations/public/convert_to_lens/utils.test.ts b/src/plugins/visualizations/public/convert_to_lens/utils.test.ts new file mode 100644 index 0000000000000..734a250a2972c --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/utils.test.ts @@ -0,0 +1,610 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { BUCKET_TYPES, METRIC_TYPES } from '@kbn/data-plugin/common'; +import { stubLogstashDataView } from '@kbn/data-views-plugin/common/data_view.stub'; +import { + AggBasedColumn, + CounterRateColumn, + GenericColumnWithMeta, + SchemaConfig, + SupportedAggregation, +} from '../../common'; +import { + AvgColumn, + CountColumn, + MaxColumn, + DateHistogramColumn, + Meta, +} from '../../common/convert_to_lens/lib'; +import { + getBucketCollapseFn, + getBucketColumns, + getColumnIds, + getColumnsWithoutReferenced, + getMetricsWithoutDuplicates, + isReferenced, + isValidVis, + sortColumns, +} from './utils'; +import { Schemas } from '../vis_schemas'; + +const mockConvertBucketToColumns = jest.fn(); + +jest.mock('../../common/convert_to_lens/lib/buckets', () => ({ + convertBucketToColumns: jest.fn(() => mockConvertBucketToColumns()), +})); + +describe('isReferenced', () => { + const columnId = 'col1'; + const references = ['col0', columnId, '----']; + + test.each<[string, [string, string[]], boolean]>([ + ['false if referneces are empty', [columnId, []], false], + ['false if columnId is not in referneces', ['some new column', references], false], + ['true if columnId is in referneces', [columnId, references], true], + ])('should return %s', (_, input, expected) => { + expect(isReferenced(...input)).toBe(expected); + }); +}); + +describe('getColumnsWithoutReferenced', () => { + const column: AvgColumn = { + sourceField: 'some-field', + columnId: 'col3', + operationType: 'average', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'some id' }, + }; + + const referencedColumn: CountColumn = { + sourceField: 'document', + columnId: 'col1', + operationType: 'count', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'some id' }, + }; + + const columnWithReference: GenericColumnWithMeta = { + references: [referencedColumn.columnId], + columnId: 'col2', + operationType: 'counter_rate', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'some id' }, + }; + + const columns: AggBasedColumn[] = [column, columnWithReference, referencedColumn]; + const columnsWithoutReferenced = [column, columnWithReference]; + test.each<[string, AggBasedColumn[], AggBasedColumn[]]>([ + ['filter out referenced column if contains', columns, columnsWithoutReferenced], + [ + 'return the same array, if no referenced columns', + columnsWithoutReferenced, + columnsWithoutReferenced, + ], + ])('should %s', (_, input, expected) => { + expect(getColumnsWithoutReferenced(input)).toEqual(expected); + }); +}); + +describe('getBucketCollapseFn', () => { + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + const metric2: SchemaConfig = { + ...metric1, + aggType: METRIC_TYPES.AVG_BUCKET, + }; + + const metric3: SchemaConfig = { + ...metric1, + aggType: METRIC_TYPES.MAX_BUCKET, + }; + + const metric4: SchemaConfig = { + ...metric1, + aggType: METRIC_TYPES.MIN_BUCKET, + }; + + const metric5: SchemaConfig = { + ...metric1, + aggType: METRIC_TYPES.SUM_BUCKET, + }; + + const customBucketColum: AggBasedColumn = { + columnId: 'bucket-1', + operationType: 'date_histogram', + sourceField: 'test', + isBucketed: true, + isSplit: false, + params: { + interval: '1h', + }, + dataType: 'date', + meta: { + aggId: '1', + }, + }; + + test.each< + [ + string, + [Array>, AggBasedColumn[]], + Record + ] + >([ + ['avg', [[metric1, metric2], [customBucketColum]], { [customBucketColum.columnId]: 'avg' }], + ['max', [[metric1, metric3], [customBucketColum]], { [customBucketColum.columnId]: 'max' }], + ['min', [[metric1, metric4], [customBucketColum]], { [customBucketColum.columnId]: 'min' }], + ['sum', [[metric1, metric5], [customBucketColum]], { [customBucketColum.columnId]: 'sum' }], + [ + 'undefined if no sibling pipeline agg is provided', + [[metric1], [customBucketColum]], + { [customBucketColum.columnId]: undefined }, + ], + ])('should return%s', (_, input, expected) => { + expect(getBucketCollapseFn(...input)).toEqual(expected); + }); +}); + +describe('getBucketColumns', () => { + const dataView = stubLogstashDataView; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('should skip empty schemas and return empty array', () => { + const metricKey = 'metric'; + const bucketKey = 'group'; + const keys = [metricKey, bucketKey]; + + const visSchemas: Schemas = { + [metricKey]: [], + [bucketKey]: [], + }; + + expect(getBucketColumns(visSchemas, keys, dataView, false, [])).toEqual([]); + expect(mockConvertBucketToColumns).toBeCalledTimes(0); + }); + + test('should return null if metric is invalid', () => { + const metricKey = 'metric'; + const bucketKey = 'group'; + const keys = [metricKey, bucketKey]; + + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1], + [bucketKey]: [], + }; + mockConvertBucketToColumns.mockReturnValueOnce(null); + + expect(getBucketColumns(visSchemas, keys, dataView, false, [])).toBeNull(); + expect(mockConvertBucketToColumns).toBeCalledTimes(1); + }); + + test('should return null if no buckets are returned', () => { + const metricKey = 'metric'; + const bucketKey = 'group'; + const keys = [metricKey, bucketKey]; + + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1], + [bucketKey]: [], + }; + mockConvertBucketToColumns.mockReturnValueOnce([null]); + + expect(getBucketColumns(visSchemas, keys, dataView, false, [])).toBeNull(); + expect(mockConvertBucketToColumns).toBeCalledTimes(1); + }); + test('should return columns', () => { + const metricKey = 'metric'; + const bucketKey = 'group'; + const keys = [metricKey, bucketKey]; + + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + const column: AvgColumn = { + sourceField: 'some-field', + columnId: 'col3', + operationType: 'average', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: 'some id' }, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1], + [bucketKey]: [metric1], + }; + + const returnValue = [column]; + + mockConvertBucketToColumns.mockReturnValue(returnValue); + + expect(getBucketColumns(visSchemas, keys, dataView, false, [])).toEqual([ + ...returnValue, + ...returnValue, + ]); + expect(mockConvertBucketToColumns).toBeCalledTimes(2); + }); +}); + +describe('isValidVis', () => { + const metricKey = 'metric'; + const bucketKey = 'group'; + + test("should return true, if metrics doesn't contain sibling aggs", () => { + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1], + [bucketKey]: [], + }; + + expect(isValidVis(visSchemas)).toBeTruthy(); + }); + + test('should return true, if metrics contain only one sibling agg', () => { + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1], + [bucketKey]: [], + }; + + expect(isValidVis(visSchemas)).toBeTruthy(); + }); + + test('should return true, if metrics contain multiple sibling aggs of the same type', () => { + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1, metric1], + [bucketKey]: [], + }; + + expect(isValidVis(visSchemas)).toBeTruthy(); + }); + + test('should return false, if metrics contain multiple sibling aggs with different types', () => { + const metric1: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.AVG_BUCKET, + }; + const metric2: SchemaConfig = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + aggType: METRIC_TYPES.SUM_BUCKET, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1, metric2], + [bucketKey]: [], + }; + + expect(isValidVis(visSchemas)).toBeFalsy(); + }); +}); + +describe('getMetricsWithoutDuplicates', () => { + const duplicatedAggId = 'some-agg-id'; + const baseMetric = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + + const metric1: SchemaConfig = { + ...baseMetric, + aggType: METRIC_TYPES.AVG, + aggId: duplicatedAggId, + }; + + const metric2: SchemaConfig = { + ...baseMetric, + aggType: METRIC_TYPES.SUM, + aggId: 'some-other-id', + }; + + const metric3: SchemaConfig = { + ...baseMetric, + aggType: METRIC_TYPES.MAX, + aggId: duplicatedAggId, + }; + + test('should remove aggs with same aggIds', () => { + expect(getMetricsWithoutDuplicates([metric1, metric2, metric3])).toEqual([metric1, metric2]); + }); + + test('should return array if no duplicates', () => { + expect(getMetricsWithoutDuplicates([metric2, metric3])).toEqual([metric2, metric3]); + }); +}); + +describe('sortColumns', () => { + const aggId1 = '0_agg_id'; + const aggId2 = '1_agg_id'; + const aggId3 = '2_agg_id'; + const aggId4 = '3_agg_id'; + const aggId5 = '4_agg_id'; + + const column1: AvgColumn = { + sourceField: 'some-field', + columnId: 'col0', + operationType: 'average', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: aggId1 }, + }; + + const column2: CountColumn = { + sourceField: 'document', + columnId: 'col1', + operationType: 'count', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: aggId2 }, + }; + + const column3: MaxColumn = { + sourceField: 'some-field', + columnId: 'col2', + operationType: 'max', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: aggId3 }, + }; + + const column4: DateHistogramColumn = { + sourceField: 'some-field', + columnId: 'col3', + operationType: 'date_histogram', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: { interval: '1h' }, + meta: { aggId: aggId4 }, + }; + + const column5: DateHistogramColumn = { + sourceField: 'some-field', + columnId: 'col4', + operationType: 'date_histogram', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: { interval: '1h' }, + meta: { aggId: aggId5 }, + }; + + const metricKey = 'metric'; + const bucketKey = 'group'; + + const baseMetric = { + accessor: 0, + label: '', + format: { + id: undefined, + params: undefined, + }, + params: {}, + }; + const metric1: SchemaConfig = { + ...baseMetric, + accessor: 1, + aggType: METRIC_TYPES.AVG, + aggId: aggId1, + }; + const metric2: SchemaConfig = { + ...baseMetric, + accessor: 2, + aggType: METRIC_TYPES.COUNT, + aggId: aggId2, + }; + const metric3: SchemaConfig = { + ...baseMetric, + accessor: 3, + aggType: METRIC_TYPES.MAX, + aggId: aggId3, + }; + + const bucket1: SchemaConfig = { + ...baseMetric, + accessor: 4, + aggType: BUCKET_TYPES.DATE_HISTOGRAM, + aggId: aggId4, + }; + + const bucket2: SchemaConfig = { + ...baseMetric, + accessor: 5, + aggType: BUCKET_TYPES.DATE_HISTOGRAM, + aggId: aggId5, + }; + + const visSchemas: Schemas = { + [metricKey]: [metric1, metric2, metric3], + [bucketKey]: [bucket1, bucket2], + }; + const columns: AggBasedColumn[] = [column4, column3, column2, column5, column1]; + const metricsWithoutDuplicates: Array> = [ + metric1, + metric2, + metric3, + ]; + const keys = [bucketKey]; + + test('should remove aggs with same aggIds', () => { + expect(sortColumns(columns, visSchemas, keys, metricsWithoutDuplicates)).toEqual([ + column1, + column2, + column3, + column4, + column5, + ]); + }); +}); + +describe('getColumnIds', () => { + const colId1 = '0_agg_id'; + const colId2 = '1_agg_id'; + const colId3 = '2_agg_id'; + const colId4 = '3_agg_id'; + + const column1: AvgColumn = { + sourceField: 'some-field', + columnId: colId1, + operationType: 'average', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: colId1 }, + }; + + const column2: CountColumn = { + sourceField: 'document', + columnId: colId2, + operationType: 'count', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: colId2 }, + }; + + const column3: MaxColumn = { + sourceField: 'some-field', + columnId: colId3, + operationType: 'max', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: {}, + meta: { aggId: colId3 }, + }; + + const column4: DateHistogramColumn = { + sourceField: 'some-field', + columnId: colId4, + operationType: 'date_histogram', + isBucketed: false, + isSplit: false, + dataType: 'string', + params: { interval: '1h' }, + meta: { aggId: colId4 }, + }; + + test('return columnIds', () => { + expect(getColumnIds([column1, column2, column3, column4])).toEqual([ + colId1, + colId2, + colId3, + colId4, + ]); + }); +}); diff --git a/src/plugins/visualizations/public/convert_to_lens/utils.ts b/src/plugins/visualizations/public/convert_to_lens/utils.ts new file mode 100644 index 0000000000000..a5337568b5568 --- /dev/null +++ b/src/plugins/visualizations/public/convert_to_lens/utils.ts @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { DataView } from '@kbn/data-views-plugin/common'; +import { METRIC_TYPES } from '@kbn/data-plugin/public'; +import { AggBasedColumn, SchemaConfig, SupportedAggregation } from '../../common'; +import { convertBucketToColumns } from '../../common/convert_to_lens/lib/buckets'; +import { isSiblingPipeline } from '../../common/convert_to_lens/lib/utils'; +import { Schemas } from '../vis_schemas'; + +export const isReferenced = (columnId: string, references: string[]) => + references.includes(columnId); + +export const getColumnsWithoutReferenced = (columns: AggBasedColumn[]) => { + const references = Object.values(columns).flatMap((col) => + 'references' in col ? col.references : [] + ); + return columns.filter(({ columnId }) => !isReferenced(columnId, references)); +}; + +export const getBucketCollapseFn = ( + metrics: Array>, + customBucketColumns: AggBasedColumn[] +) => { + const collapseFn = metrics.find((m) => isSiblingPipeline(m))?.aggType.split('_')[0]; + return customBucketColumns.length + ? { + [customBucketColumns[0].columnId]: collapseFn, + } + : {}; +}; + +export const getBucketColumns = ( + visSchemas: Schemas, + keys: Array, + dataView: DataView, + isSplit: boolean, + metricColumns: AggBasedColumn[], + dropEmptyRowsInDateHistogram: boolean = false +) => { + const columns: AggBasedColumn[] = []; + for (const key of keys) { + if (visSchemas[key] && visSchemas[key]?.length) { + const bucketColumns = visSchemas[key]?.flatMap((m) => + convertBucketToColumns( + { + agg: m, + dataView, + metricColumns, + aggs: visSchemas.metric as Array>, + }, + isSplit, + dropEmptyRowsInDateHistogram + ) + ); + if (!bucketColumns || bucketColumns.includes(null)) { + return null; + } + columns.push(...(bucketColumns as AggBasedColumn[])); + } + } + return columns; +}; + +export const isValidVis = (visSchemas: Schemas) => { + const { metric } = visSchemas; + const siblingPipelineAggs = metric.filter((m) => isSiblingPipeline(m)); + + if (!siblingPipelineAggs.length) { + return true; + } + + // doesn't support mixed sibling pipeline aggregations + if (siblingPipelineAggs.some((agg) => agg.aggType !== siblingPipelineAggs[0].aggType)) { + return false; + } + + return true; +}; + +export const getMetricsWithoutDuplicates = (metrics: Array>) => + metrics.reduce>>((acc, metric) => { + if (metric.aggId && !acc.some((m) => m.aggId === metric.aggId)) { + acc.push(metric); + } + return acc; + }, []); + +export const sortColumns = ( + columns: AggBasedColumn[], + visSchemas: Schemas, + bucketsAndSplitsKeys: Array, + metricsWithoutDuplicates: Array> +) => { + const aggOrderMap: Record = ['metric', ...bucketsAndSplitsKeys].reduce( + (acc, key) => { + return { + ...acc, + ...(key === 'metric' ? metricsWithoutDuplicates : visSchemas[key])?.reduce( + (newAcc, schema) => { + newAcc[schema.aggId] = schema.accessor; + return newAcc; + }, + {} + ), + }; + }, + {} + ); + + return columns.sort( + (a, b) => + Number(aggOrderMap[a.meta.aggId.split('-')[0]]) - + Number(aggOrderMap[b.meta.aggId.split('-')[0]]) + ); +}; + +export const getColumnIds = (columns: AggBasedColumn[]) => columns.map(({ columnId }) => columnId); diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx b/src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx index fcdcede24409e..26746f8d23200 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable.tsx @@ -569,6 +569,7 @@ export class VisualizeEmbeddable }, variables: { embeddableTitle: this.getTitle(), + ...(await this.vis.type.getExpressionVariables?.(this.vis, this.timefilter)), }, searchSessionId: this.input.searchSessionId, syncColors: this.input.syncColors, diff --git a/src/plugins/visualizations/public/index.ts b/src/plugins/visualizations/public/index.ts index 39fc5e570a9cf..693bbd26a2e2f 100644 --- a/src/plugins/visualizations/public/index.ts +++ b/src/plugins/visualizations/public/index.ts @@ -30,7 +30,7 @@ export type VisualizeEmbeddableFactoryContract = PublicContract; export type { VisualizeInput } from './embeddable'; export type { VisualizeEmbeddable } from './embeddable'; -export type { SchemaConfig } from './vis_schemas'; +export type { SchemaConfig } from '../common/types'; export { updateOldState } from './legacy/vis_update_state'; export type { PersistedState } from './persisted_state'; export type { @@ -66,4 +66,12 @@ export { urlFor, getFullPath } from './utils/saved_visualize_utils'; export type { IEditorController, EditorRenderProps } from './visualize_app/types'; -export { VISUALIZE_EDITOR_TRIGGER, ACTION_CONVERT_TO_LENS } from './triggers'; +export { + VISUALIZE_EDITOR_TRIGGER, + AGG_BASED_VISUALIZATION_TRIGGER, + ACTION_CONVERT_TO_LENS, + ACTION_CONVERT_AGG_BASED_TO_LENS, +} from './triggers'; + +export const convertToLensModule = import('./convert_to_lens'); +export { getDataViewByIndexPatternId } from './convert_to_lens/datasource'; diff --git a/src/plugins/visualizations/public/plugin.ts b/src/plugins/visualizations/public/plugin.ts index 50245642e7fed..b7094f30b8b04 100644 --- a/src/plugins/visualizations/public/plugin.ts +++ b/src/plugins/visualizations/public/plugin.ts @@ -57,7 +57,7 @@ import type { SpacesPluginStart } from '@kbn/spaces-plugin/public'; import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; import type { TypesSetup, TypesStart } from './vis_types'; import type { VisualizeServices } from './visualize_app/types'; -import { visualizeEditorTrigger } from './triggers'; +import { aggBasedVisualizationTrigger, visualizeEditorTrigger } from './triggers'; import { createVisEditorsRegistry, VisEditorsRegistry } from './vis_editors_registry'; import { showNewVisModal } from './wizard'; import { VisualizeLocatorDefinition } from '../common/locator'; @@ -338,6 +338,7 @@ export class VisualizationsPlugin expressions.registerFunction(rangeExpressionFunction); expressions.registerFunction(visDimensionExpressionFunction); expressions.registerFunction(xyDimensionExpressionFunction); + uiActions.registerTrigger(aggBasedVisualizationTrigger); uiActions.registerTrigger(visualizeEditorTrigger); const embeddableFactory = new VisualizeEmbeddableFactory({ start }); embeddable.registerEmbeddableFactory(VISUALIZE_EMBEDDABLE_TYPE, embeddableFactory); diff --git a/src/plugins/visualizations/public/triggers/index.ts b/src/plugins/visualizations/public/triggers/index.ts index 2050185db15e4..c6eb548d7fab5 100644 --- a/src/plugins/visualizations/public/triggers/index.ts +++ b/src/plugins/visualizations/public/triggers/index.ts @@ -11,8 +11,16 @@ import { Trigger } from '@kbn/ui-actions-plugin/public'; export const VISUALIZE_EDITOR_TRIGGER = 'VISUALIZE_EDITOR_TRIGGER'; export const visualizeEditorTrigger: Trigger = { id: VISUALIZE_EDITOR_TRIGGER, - title: 'Convert legacy visualizations to Lens', - description: 'Triggered when user navigates from a legacy visualization to Lens.', + title: 'Convert TSVB to Lens', + description: 'Triggered when user navigates from a TSVB to Lens.', +}; + +export const AGG_BASED_VISUALIZATION_TRIGGER = 'AGG_BASED_VISUALIZATION_TRIGGER'; +export const aggBasedVisualizationTrigger: Trigger = { + id: AGG_BASED_VISUALIZATION_TRIGGER, + title: 'Convert legacy agg based visualizations to Lens', + description: 'Triggered when user navigates from a agg based visualization to Lens.', }; export const ACTION_CONVERT_TO_LENS = 'ACTION_CONVERT_TO_LENS'; +export const ACTION_CONVERT_AGG_BASED_TO_LENS = 'ACTION_CONVERT_AGG_BASED_TO_LENS'; diff --git a/src/plugins/visualizations/public/vis_schemas.ts b/src/plugins/visualizations/public/vis_schemas.ts index 795631b9b4f07..cd8bd9bc386a8 100644 --- a/src/plugins/visualizations/public/vis_schemas.ts +++ b/src/plugins/visualizations/public/vis_schemas.ts @@ -6,24 +6,29 @@ * Side Public License, v 1. */ -import type { SerializedFieldFormat } from '@kbn/field-formats-plugin/common'; -import { IAggConfig, search } from '@kbn/data-plugin/public'; - +import { + BUCKET_TYPES, + IAggConfig, + METRIC_TYPES, + SHARD_DELAY_AGG_NAME, +} from '@kbn/data-plugin/common'; +import { search } from '@kbn/data-plugin/public'; import { Vis, VisToExpressionAstParams } from './types'; +import { SchemaConfig } from '../common/types'; +import { convertToSchemaConfig } from '../common'; const { isDateHistogramBucketAggConfig } = search.aggs; -interface SchemaConfigParams { - precision?: number; - useGeocentroid?: boolean; -} +const SUPPORTED_AGGREGATIONS = [ + ...Object.values(METRIC_TYPES), + ...Object.values(BUCKET_TYPES), + SHARD_DELAY_AGG_NAME, +]; + +type SupportedAggregation = typeof SUPPORTED_AGGREGATIONS[number]; -export interface SchemaConfig { - accessor: number; - label: string; - format: SerializedFieldFormat; - params: SchemaConfigParams; - aggType: string; +function isSupportedAggType(name: string): name is SupportedAggregation { + return SUPPORTED_AGGREGATIONS.includes(name as SupportedAggregation); } export interface Schemas { @@ -41,54 +46,40 @@ export interface Schemas { [key: string]: any[] | undefined; } -export const getVisSchemas = ( - vis: Vis, +const updateDateHistogramParams = ( + agg: IAggConfig, { timeRange, timefilter }: VisToExpressionAstParams -): Schemas => { - const createSchemaConfig = (accessor: number, agg: IAggConfig): SchemaConfig => { - if (isDateHistogramBucketAggConfig(agg)) { - agg.params.timeRange = timeRange; - const bounds = - agg.params.timeRange && agg.fieldIsTimeField() - ? timefilter.calculateBounds(agg.params.timeRange) - : undefined; - agg.buckets.setBounds(bounds); - agg.buckets.setInterval(agg.params.interval); - } - - const hasSubAgg = [ - 'derivative', - 'moving_avg', - 'serial_diff', - 'cumulative_sum', - 'sum_bucket', - 'avg_bucket', - 'min_bucket', - 'max_bucket', - ].includes(agg.type.name); - - const formatAgg = hasSubAgg - ? agg.params.customMetric || agg.aggConfigs.getRequestAggById(agg.params.metricAgg) - : agg; - - const params: SchemaConfigParams = {}; - - if (agg.type.name === 'geohash_grid') { - params.precision = agg.params.precision; - params.useGeocentroid = agg.params.useGeocentroid; - } +) => { + if (isDateHistogramBucketAggConfig(agg)) { + agg.params.timeRange = timeRange; + const bounds = + agg.params.timeRange && agg.fieldIsTimeField() + ? timefilter.calculateBounds(agg.params.timeRange) + : undefined; + agg.buckets.setBounds(bounds); + agg.buckets.setInterval(agg.params.interval); + } + return agg; +}; - const label = agg.makeLabel && agg.makeLabel(); +const createSchemaConfig = ( + agg: IAggConfig, + accessor: number, + params: VisToExpressionAstParams +): SchemaConfig => { + const aggType = agg.type.name; + if (!isSupportedAggType(aggType)) { + throw new Error(`Unsupported agg type: ${aggType}`); + } - return { - accessor, - format: formatAgg.toSerializedFieldFormat(), - params, - label, - aggType: agg.type.name, - }; - }; + const updatedAgg = updateDateHistogramParams(agg, params); + return { ...convertToSchemaConfig(updatedAgg), accessor }; +}; +export const getVisSchemas = ( + vis: Vis, + params: VisToExpressionAstParams +): Schemas => { let cnt = 0; const schemas: Schemas = { metric: [], @@ -121,11 +112,11 @@ export const getVisSchemas = ( schemas[schemaName] = []; } if (!isHierarchical || agg.type.type !== 'metrics') { - schemas[schemaName]!.push(createSchemaConfig(cnt++, agg)); + schemas[schemaName]!.push(createSchemaConfig(agg, cnt++, params)); } if (isHierarchical && (agg.type.type !== 'metrics' || metrics.length === responseAggs.length)) { metrics.forEach((metric: any) => { - const schemaConfig = createSchemaConfig(cnt++, metric); + const schemaConfig = createSchemaConfig(metric, cnt++, params); if (!skipMetrics) { schemas.metric.push(schemaConfig); } diff --git a/src/plugins/visualizations/public/vis_types/base_vis_type.ts b/src/plugins/visualizations/public/vis_types/base_vis_type.ts index 1b0875f636af4..2d351f18a3b47 100644 --- a/src/plugins/visualizations/public/vis_types/base_vis_type.ts +++ b/src/plugins/visualizations/public/vis_types/base_vis_type.ts @@ -29,6 +29,7 @@ export class BaseVisType { public readonly note; public readonly getSupportedTriggers; public readonly navigateToLens; + public readonly getExpressionVariables; public readonly icon; public readonly image; public readonly stage; @@ -62,6 +63,7 @@ export class BaseVisType { this.note = opts.note ?? ''; this.getSupportedTriggers = opts.getSupportedTriggers; this.navigateToLens = opts.navigateToLens; + this.getExpressionVariables = opts.getExpressionVariables; this.title = opts.title; this.icon = opts.icon; this.image = opts.image; diff --git a/src/plugins/visualizations/public/vis_types/types.ts b/src/plugins/visualizations/public/vis_types/types.ts index 2eb011e91d66a..9689729f187fd 100644 --- a/src/plugins/visualizations/public/vis_types/types.ts +++ b/src/plugins/visualizations/public/vis_types/types.ts @@ -9,8 +9,12 @@ import type { IconType } from '@elastic/eui'; import type { ReactNode } from 'react'; import type { Adapters } from '@kbn/inspector-plugin/common'; -import { TimeRange } from '@kbn/data-plugin/common'; -import type { AggGroupNames, AggParam, AggGroupName } from '@kbn/data-plugin/public'; +import type { + AggGroupNames, + AggParam, + AggGroupName, + TimefilterContract, +} from '@kbn/data-plugin/public'; import type { DataView } from '@kbn/data-views-plugin/public'; import type { Vis, VisEditorOptionsProps, VisParams, VisToExpressionAst } from '../types'; import { VisGroups } from './vis_groups_enum'; @@ -104,10 +108,19 @@ export interface VisTypeDefinition { * in order to be displayed in the Lens editor. */ readonly navigateToLens?: ( - params?: VisParams, - timeRange?: TimeRange + vis?: Vis, + timeFilter?: TimefilterContract ) => Promise | undefined; + /** + * If given, it will provide variables for expression params. + * Every visualization that wants to add variables for expression params should have this method. + */ + readonly getExpressionVariables?: ( + vis?: Vis, + timeFilter?: TimefilterContract + ) => Promise>; + /** * Some visualizations are created without SearchSource and may change the used indexes during the visualization configuration. * Using this method we can rewrite the standard mechanism for getting used indexes diff --git a/src/plugins/visualizations/public/visualize_app/components/visualize_top_nav.tsx b/src/plugins/visualizations/public/visualize_app/components/visualize_top_nav.tsx index 3ba6d035f31fb..055b326b8f19f 100644 --- a/src/plugins/visualizations/public/visualize_app/components/visualize_top_nav.tsx +++ b/src/plugins/visualizations/public/visualize_app/components/visualize_top_nav.tsx @@ -96,18 +96,26 @@ const TopNav = ({ [doReload] ); + const uiStateJSON = useMemo(() => vis.uiState.toJSON(), [vis.uiState]); useEffect(() => { const asyncGetTriggerContext = async () => { if (vis.type.navigateToLens) { const triggerConfig = await vis.type.navigateToLens( - vis.params, - services.data.query.timefilter.timefilter.getAbsoluteTime() + vis, + services.data.query.timefilter.timefilter ); setEditInLensConfig(triggerConfig); } }; asyncGetTriggerContext(); - }, [services.data.query.timefilter.timefilter, vis.params, vis.type]); + }, [ + services.data.query.timefilter.timefilter, + vis, + vis.type, + vis.params, + uiStateJSON?.vis, + vis.data.indexPattern, + ]); const displayEditInLensItem = Boolean(vis.type.navigateToLens && editInLensConfig); const config = useMemo(() => { diff --git a/src/plugins/visualizations/public/visualize_app/utils/get_top_nav_config.tsx b/src/plugins/visualizations/public/visualize_app/utils/get_top_nav_config.tsx index 68cb01d10c94d..36b92585f1096 100644 --- a/src/plugins/visualizations/public/visualize_app/utils/get_top_nav_config.tsx +++ b/src/plugins/visualizations/public/visualize_app/utils/get_top_nav_config.tsx @@ -40,7 +40,7 @@ import { VisualizeConstants } from '../../../common/constants'; import { getEditBreadcrumbs } from './breadcrumbs'; import { VISUALIZE_APP_LOCATOR, VisualizeLocatorParams } from '../../../common/locator'; import { getUiActions } from '../../services'; -import { VISUALIZE_EDITOR_TRIGGER } from '../../triggers'; +import { VISUALIZE_EDITOR_TRIGGER, AGG_BASED_VISUALIZATION_TRIGGER } from '../../triggers'; import { getVizEditorOriginatingAppUrl } from './utils'; import './visualize_navigation.scss'; @@ -311,7 +311,13 @@ export const getTopNavConfig = ( if (editInLensConfig) { hideLensBadge(); setNavigateToLens(true); - getUiActions().getTrigger(VISUALIZE_EDITOR_TRIGGER).exec(updatedWithMeta); + getUiActions() + .getTrigger( + visInstance.vis.type.group === 'aggbased' + ? AGG_BASED_VISUALIZATION_TRIGGER + : VISUALIZE_EDITOR_TRIGGER + ) + .exec(updatedWithMeta); } }, }, diff --git a/test/api_integration/apis/index_patterns/constants.ts b/test/api_integration/apis/data_views/constants.ts similarity index 100% rename from test/api_integration/apis/index_patterns/constants.ts rename to test/api_integration/apis/data_views/constants.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/index.ts b/test/api_integration/apis/data_views/data_views_crud/create_data_view/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/index.ts rename to test/api_integration/apis/data_views/data_views_crud/create_data_view/index.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/main.ts b/test/api_integration/apis/data_views/data_views_crud/create_data_view/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/main.ts rename to test/api_integration/apis/data_views/data_views_crud/create_data_view/main.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/validation.ts b/test/api_integration/apis/data_views/data_views_crud/create_data_view/validation.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/create_index_pattern/validation.ts rename to test/api_integration/apis/data_views/data_views_crud/create_data_view/validation.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/errors.ts b/test/api_integration/apis/data_views/data_views_crud/delete_data_view/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/errors.ts rename to test/api_integration/apis/data_views/data_views_crud/delete_data_view/errors.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/index.ts b/test/api_integration/apis/data_views/data_views_crud/delete_data_view/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/index.ts rename to test/api_integration/apis/data_views/data_views_crud/delete_data_view/index.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/main.ts b/test/api_integration/apis/data_views/data_views_crud/delete_data_view/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/delete_index_pattern/main.ts rename to test/api_integration/apis/data_views/data_views_crud/delete_data_view/main.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/errors.ts b/test/api_integration/apis/data_views/data_views_crud/get_data_view/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/errors.ts rename to test/api_integration/apis/data_views/data_views_crud/get_data_view/errors.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/index.ts b/test/api_integration/apis/data_views/data_views_crud/get_data_view/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/index.ts rename to test/api_integration/apis/data_views/data_views_crud/get_data_view/index.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/main.ts b/test/api_integration/apis/data_views/data_views_crud/get_data_view/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/get_index_pattern/main.ts rename to test/api_integration/apis/data_views/data_views_crud/get_data_view/main.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/get_data_views/index.ts b/test/api_integration/apis/data_views/data_views_crud/get_data_views/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/get_data_views/index.ts rename to test/api_integration/apis/data_views/data_views_crud/get_data_views/index.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/get_data_views/main.ts b/test/api_integration/apis/data_views/data_views_crud/get_data_views/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/get_data_views/main.ts rename to test/api_integration/apis/data_views/data_views_crud/get_data_views/main.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/index.ts b/test/api_integration/apis/data_views/data_views_crud/index.ts similarity index 71% rename from test/api_integration/apis/index_patterns/index_pattern_crud/index.ts rename to test/api_integration/apis/data_views/data_views_crud/index.ts index 158fe3087bcbe..241cc0230e869 100644 --- a/test/api_integration/apis/index_patterns/index_pattern_crud/index.ts +++ b/test/api_integration/apis/data_views/data_views_crud/index.ts @@ -10,10 +10,10 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ loadTestFile }: FtrProviderContext) { describe('index_pattern_crud', () => { - loadTestFile(require.resolve('./create_index_pattern')); - loadTestFile(require.resolve('./get_index_pattern')); - loadTestFile(require.resolve('./delete_index_pattern')); - loadTestFile(require.resolve('./update_index_pattern')); + loadTestFile(require.resolve('./create_data_view')); + loadTestFile(require.resolve('./get_data_view')); + loadTestFile(require.resolve('./delete_data_view')); + loadTestFile(require.resolve('./update_data_view')); loadTestFile(require.resolve('./get_data_views')); }); } diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/errors.ts b/test/api_integration/apis/data_views/data_views_crud/update_data_view/errors.ts similarity index 91% rename from test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/errors.ts rename to test/api_integration/apis/data_views/data_views_crud/update_data_view/errors.ts index 54f61cba1cfbe..670b003a3d24f 100644 --- a/test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/errors.ts +++ b/test/api_integration/apis/data_views/data_views_crud/update_data_view/errors.ts @@ -53,7 +53,7 @@ export default function ({ getService }: FtrProviderContext) { ); }); - it('returns error when update patch is empty', async () => { + it('returns success when update patch is empty', async () => { const title1 = `foo-${Date.now()}-${Math.random()}*`; const response = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -65,9 +65,7 @@ export default function ({ getService }: FtrProviderContext) { [config.serviceKey]: {}, }); - expect(response2.status).to.be(400); - expect(response2.body.statusCode).to.be(400); - expect(response2.body.message).to.be('Index pattern change set is empty.'); + expect(response2.status).to.be(200); }); }); }); diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/index.ts b/test/api_integration/apis/data_views/data_views_crud/update_data_view/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/index.ts rename to test/api_integration/apis/data_views/data_views_crud/update_data_view/index.ts diff --git a/test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/main.ts b/test/api_integration/apis/data_views/data_views_crud/update_data_view/main.ts similarity index 88% rename from test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/main.ts rename to test/api_integration/apis/data_views/data_views_crud/update_data_view/main.ts index 7548d09580f45..aaeef54750864 100644 --- a/test/api_integration/apis/index_patterns/index_pattern_crud/update_index_pattern/main.ts +++ b/test/api_integration/apis/data_views/data_views_crud/update_data_view/main.ts @@ -16,7 +16,7 @@ export default function ({ getService }: FtrProviderContext) { describe('main', () => { configArray.forEach((config) => { describe(config.name, () => { - it('can update index_pattern title', async () => { + it('can update data view title', async () => { const title1 = `foo-${Date.now()}-${Math.random()}*`; const title2 = `bar-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ @@ -41,7 +41,34 @@ export default function ({ getService }: FtrProviderContext) { expect(response3.body[config.serviceKey].title).to.be(title2); }); - it('can update index_pattern timeFieldName', async () => { + it('can update data view name', async () => { + const title = `foo-${Date.now()}-${Math.random()}*`; + const name1 = 'good data view name'; + const name2 = 'better data view name'; + const response1 = await supertest.post(config.path).send({ + [config.serviceKey]: { + title, + name: name1, + }, + }); + + expect(response1.body[config.serviceKey].name).to.be(name1); + + const id = response1.body[config.serviceKey].id; + const response2 = await supertest.post(`${config.path}/${id}`).send({ + [config.serviceKey]: { + name: name2, + }, + }); + + expect(response2.body[config.serviceKey].name).to.be(name2); + + const response3 = await supertest.get(`${config.path}/${id}`); + + expect(response3.body[config.serviceKey].name).to.be(name2); + }); + + it('can update data view timeFieldName', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -66,7 +93,7 @@ export default function ({ getService }: FtrProviderContext) { expect(response3.body[config.serviceKey].timeFieldName).to.be('timeFieldName2'); }); - it('can update index_pattern sourceFilters', async () => { + it('can update data view sourceFilters', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -120,7 +147,7 @@ export default function ({ getService }: FtrProviderContext) { ]); }); - it('can update index_pattern fieldFormats', async () => { + it('can update data view fieldFormats', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -180,7 +207,7 @@ export default function ({ getService }: FtrProviderContext) { }); }); - it('can update index_pattern type', async () => { + it('can update data view type', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -205,7 +232,7 @@ export default function ({ getService }: FtrProviderContext) { expect(response3.body[config.serviceKey].type).to.be('bar'); }); - it('can update index_pattern typeMeta', async () => { + it('can update data view typeMeta', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { @@ -230,7 +257,7 @@ export default function ({ getService }: FtrProviderContext) { expect(response3.body[config.serviceKey].typeMeta).to.eql({ foo: 'baz' }); }); - it('can update multiple index pattern fields at once', async () => { + it('can update multiple data view fields at once', async () => { const title = `foo-${Date.now()}-${Math.random()}*`; const response1 = await supertest.post(config.path).send({ [config.serviceKey]: { diff --git a/test/api_integration/apis/index_patterns/default_index_pattern/default_index_pattern.ts b/test/api_integration/apis/data_views/default_index_pattern/default_index_pattern.ts similarity index 100% rename from test/api_integration/apis/index_patterns/default_index_pattern/default_index_pattern.ts rename to test/api_integration/apis/data_views/default_index_pattern/default_index_pattern.ts diff --git a/test/api_integration/apis/index_patterns/default_index_pattern/index.ts b/test/api_integration/apis/data_views/default_index_pattern/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/default_index_pattern/index.ts rename to test/api_integration/apis/data_views/default_index_pattern/index.ts diff --git a/test/api_integration/apis/index_patterns/deprecations/index.ts b/test/api_integration/apis/data_views/deprecations/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/deprecations/index.ts rename to test/api_integration/apis/data_views/deprecations/index.ts diff --git a/test/api_integration/apis/index_patterns/deprecations/scripted_fields.ts b/test/api_integration/apis/data_views/deprecations/scripted_fields.ts similarity index 100% rename from test/api_integration/apis/index_patterns/deprecations/scripted_fields.ts rename to test/api_integration/apis/data_views/deprecations/scripted_fields.ts diff --git a/test/api_integration/apis/index_patterns/es_errors/errors.js b/test/api_integration/apis/data_views/es_errors/errors.js similarity index 100% rename from test/api_integration/apis/index_patterns/es_errors/errors.js rename to test/api_integration/apis/data_views/es_errors/errors.js diff --git a/test/api_integration/apis/index_patterns/es_errors/index.js b/test/api_integration/apis/data_views/es_errors/index.js similarity index 100% rename from test/api_integration/apis/index_patterns/es_errors/index.js rename to test/api_integration/apis/data_views/es_errors/index.js diff --git a/test/api_integration/apis/index_patterns/es_errors/lib/get_es_errors.js b/test/api_integration/apis/data_views/es_errors/lib/get_es_errors.js similarity index 100% rename from test/api_integration/apis/index_patterns/es_errors/lib/get_es_errors.js rename to test/api_integration/apis/data_views/es_errors/lib/get_es_errors.js diff --git a/test/api_integration/apis/index_patterns/es_errors/lib/index.js b/test/api_integration/apis/data_views/es_errors/lib/index.js similarity index 100% rename from test/api_integration/apis/index_patterns/es_errors/lib/index.js rename to test/api_integration/apis/data_views/es_errors/lib/index.js diff --git a/test/api_integration/apis/index_patterns/fields_api/index.ts b/test/api_integration/apis/data_views/fields_api/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/fields_api/index.ts rename to test/api_integration/apis/data_views/fields_api/index.ts diff --git a/test/api_integration/apis/index_patterns/fields_api/update_fields/errors.ts b/test/api_integration/apis/data_views/fields_api/update_fields/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/fields_api/update_fields/errors.ts rename to test/api_integration/apis/data_views/fields_api/update_fields/errors.ts diff --git a/test/api_integration/apis/index_patterns/fields_api/update_fields/index.ts b/test/api_integration/apis/data_views/fields_api/update_fields/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/fields_api/update_fields/index.ts rename to test/api_integration/apis/data_views/fields_api/update_fields/index.ts diff --git a/test/api_integration/apis/index_patterns/fields_api/update_fields/main.ts b/test/api_integration/apis/data_views/fields_api/update_fields/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/fields_api/update_fields/main.ts rename to test/api_integration/apis/data_views/fields_api/update_fields/main.ts diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js b/test/api_integration/apis/data_views/fields_for_wildcard_route/conflicts.js similarity index 100% rename from test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js rename to test/api_integration/apis/data_views/fields_for_wildcard_route/conflicts.js diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/filter.ts b/test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts similarity index 100% rename from test/api_integration/apis/index_patterns/fields_for_wildcard_route/filter.ts rename to test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js b/test/api_integration/apis/data_views/fields_for_wildcard_route/index.js similarity index 100% rename from test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js rename to test/api_integration/apis/data_views/fields_for_wildcard_route/index.js diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js b/test/api_integration/apis/data_views/fields_for_wildcard_route/params.js similarity index 100% rename from test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js rename to test/api_integration/apis/data_views/fields_for_wildcard_route/params.js diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js b/test/api_integration/apis/data_views/fields_for_wildcard_route/response.js similarity index 100% rename from test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js rename to test/api_integration/apis/data_views/fields_for_wildcard_route/response.js diff --git a/test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts b/test/api_integration/apis/data_views/has_user_index_pattern/has_user_index_pattern.ts similarity index 100% rename from test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts rename to test/api_integration/apis/data_views/has_user_index_pattern/has_user_index_pattern.ts diff --git a/test/api_integration/apis/index_patterns/has_user_index_pattern/index.ts b/test/api_integration/apis/data_views/has_user_index_pattern/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/has_user_index_pattern/index.ts rename to test/api_integration/apis/data_views/has_user_index_pattern/index.ts diff --git a/test/api_integration/apis/index_patterns/index.js b/test/api_integration/apis/data_views/index.js similarity index 94% rename from test/api_integration/apis/index_patterns/index.js rename to test/api_integration/apis/data_views/index.js index 9472f12a85159..c874bbc7d5b28 100644 --- a/test/api_integration/apis/index_patterns/index.js +++ b/test/api_integration/apis/data_views/index.js @@ -10,7 +10,7 @@ export default function ({ loadTestFile }) { describe('index_patterns', () => { loadTestFile(require.resolve('./es_errors')); loadTestFile(require.resolve('./fields_for_wildcard_route')); - loadTestFile(require.resolve('./index_pattern_crud')); + loadTestFile(require.resolve('./data_views_crud')); loadTestFile(require.resolve('./scripted_fields_crud')); loadTestFile(require.resolve('./fields_api')); loadTestFile(require.resolve('./default_index_pattern')); diff --git a/test/api_integration/apis/index_patterns/integration/index.ts b/test/api_integration/apis/data_views/integration/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/integration/index.ts rename to test/api_integration/apis/data_views/integration/index.ts diff --git a/test/api_integration/apis/index_patterns/integration/integration.ts b/test/api_integration/apis/data_views/integration/integration.ts similarity index 100% rename from test/api_integration/apis/index_patterns/integration/integration.ts rename to test/api_integration/apis/data_views/integration/integration.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/errors.ts b/test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/errors.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/main.ts b/test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/create_runtime_field/main.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/create_runtime_field/main.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/errors.ts b/test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/errors.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/main.ts b/test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/delete_runtime_field/main.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/delete_runtime_field/main.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/errors.ts b/test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/errors.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/main.ts b/test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/get_runtime_field/main.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/get_runtime_field/main.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/errors.ts b/test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/errors.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/main.ts b/test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/put_runtime_field/main.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/put_runtime_field/main.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/errors.ts b/test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/errors.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/index.ts b/test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/index.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/index.ts diff --git a/test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/main.ts b/test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/runtime_fields_crud/update_runtime_field/main.ts rename to test/api_integration/apis/data_views/runtime_fields_crud/update_runtime_field/main.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/errors.ts b/test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/errors.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/main.ts b/test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/create_scripted_field/main.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/create_scripted_field/main.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/errors.ts b/test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/errors.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/main.ts b/test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/delete_scripted_field/main.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/delete_scripted_field/main.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/errors.ts b/test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/errors.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/main.ts b/test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/get_scripted_field/main.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/get_scripted_field/main.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/errors.ts b/test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/errors.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/main.ts b/test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/put_scripted_field/main.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/put_scripted_field/main.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/errors.ts b/test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/errors.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/errors.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/errors.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/index.ts b/test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/index.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/index.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/index.ts diff --git a/test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/main.ts b/test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/main.ts similarity index 100% rename from test/api_integration/apis/index_patterns/scripted_fields_crud/update_scripted_field/main.ts rename to test/api_integration/apis/data_views/scripted_fields_crud/update_scripted_field/main.ts diff --git a/test/api_integration/apis/index.ts b/test/api_integration/apis/index.ts index 3b8a182308e77..b3a2f6e8d6eaf 100644 --- a/test/api_integration/apis/index.ts +++ b/test/api_integration/apis/index.ts @@ -16,7 +16,7 @@ export default function ({ loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./general')); loadTestFile(require.resolve('./home')); loadTestFile(require.resolve('./data_view_field_editor')); - loadTestFile(require.resolve('./index_patterns')); + loadTestFile(require.resolve('./data_views')); loadTestFile(require.resolve('./kql_telemetry')); loadTestFile(require.resolve('./saved_objects_management')); loadTestFile(require.resolve('./saved_objects')); diff --git a/test/functional/apps/console/_context_menu.ts b/test/functional/apps/console/_context_menu.ts new file mode 100644 index 0000000000000..8114d4d05097e --- /dev/null +++ b/test/functional/apps/console/_context_menu.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const log = getService('log'); + const retry = getService('retry'); + const PageObjects = getPageObjects(['common', 'console']); + const browser = getService('browser'); + const toasts = getService('toasts'); + + describe('console context menu', function testContextMenu() { + before(async () => { + await PageObjects.common.navigateToApp('console'); + // Ensure that the text area can be interacted with + await PageObjects.console.closeHelpIfExists(); + await PageObjects.console.clearTextArea(); + }); + + it('should open context menu', async () => { + expect(await PageObjects.console.isContextMenuOpen()).to.be(false); + await PageObjects.console.enterRequest(); + await PageObjects.console.clickContextMenu(); + expect(PageObjects.console.isContextMenuOpen()).to.be.eql(true); + }); + + it('should have options to copy as curl, open documentation, and auto indent', async () => { + await PageObjects.console.clickContextMenu(); + expect(PageObjects.console.isContextMenuOpen()).to.be.eql(true); + expect(PageObjects.console.isCopyAsCurlButtonVisible()).to.be.eql(true); + expect(PageObjects.console.isOpenDocumentationButtonVisible()).to.be.eql(true); + expect(PageObjects.console.isAutoIndentButtonVisible()).to.be.eql(true); + }); + + it('should copy as curl and show toast when copy as curl button is clicked', async () => { + await PageObjects.console.clickContextMenu(); + await PageObjects.console.clickCopyAsCurlButton(); + + const resultToast = await toasts.getToastElement(1); + const toastText = await resultToast.getVisibleText(); + + if (toastText.includes('Write permission denied')) { + log.debug('Write permission denied, skipping test'); + return; + } + + expect(toastText).to.be('Request copied as cURL'); + + const canReadClipboard = await browser.checkBrowserPermission('clipboard-read'); + if (canReadClipboard) { + const clipboardText = await browser.getClipboardValue(); + expect(clipboardText).to.contain('curl -XGET'); + } + }); + + it('should open documentation when open documentation button is clicked', async () => { + await PageObjects.console.clickContextMenu(); + await PageObjects.console.clickOpenDocumentationButton(); + + await retry.tryForTime(10000, async () => { + await browser.switchTab(1); + }); + + // Retry until the documentation is loaded + await retry.try(async () => { + const url = await browser.getCurrentUrl(); + expect(url).to.contain('search-search.html'); + }); + + // Close the documentation tab + await browser.closeCurrentWindow(); + await browser.switchTab(0); + }); + + it('should auto indent when auto indent button is clicked', async () => { + await PageObjects.console.clearTextArea(); + await PageObjects.console.enterRequest('GET _search\n{"query": {"match_all": {}}}'); + await PageObjects.console.clickContextMenu(); + await PageObjects.console.clickAutoIndentButton(); + // Retry until the request is auto indented + await retry.try(async () => { + const request = await PageObjects.console.getRequest(); + expect(request).to.be.eql('GET _search\n{\n "query": {\n "match_all": {}\n }\n}'); + }); + }); + + it('should condense when auto indent button is clicked again', async () => { + await PageObjects.console.clickContextMenu(); + await PageObjects.console.clickAutoIndentButton(); + // Retry until the request is condensed + await retry.try(async () => { + const request = await PageObjects.console.getRequest(); + expect(request).to.be.eql('GET _search\n{"query":{"match_all":{}}}'); + }); + }); + }); +} diff --git a/test/functional/apps/console/index.js b/test/functional/apps/console/index.js index 9dee3cda26e83..06c29f0e031ec 100644 --- a/test/functional/apps/console/index.js +++ b/test/functional/apps/console/index.js @@ -24,6 +24,7 @@ export default function ({ getService, loadTestFile }) { loadTestFile(require.resolve('./_variables')); loadTestFile(require.resolve('./_xjson')); loadTestFile(require.resolve('./_misc_console_behavior')); + loadTestFile(require.resolve('./_context_menu')); } }); } diff --git a/test/functional/apps/dashboard/group3/bwc_shared_urls.ts b/test/functional/apps/dashboard/group3/bwc_shared_urls.ts index 35d13b715c14c..0b06e28af0f11 100644 --- a/test/functional/apps/dashboard/group3/bwc_shared_urls.ts +++ b/test/functional/apps/dashboard/group3/bwc_shared_urls.ts @@ -12,9 +12,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['dashboard', 'header']); - const dashboardExpect = getService('dashboardExpect'); - const pieChart = getService('pieChart'); - const elasticChart = getService('elasticChart'); + const toasts = getService('toasts'); const browser = getService('browser'); const log = getService('log'); const queryBar = getService('queryBar'); @@ -42,11 +40,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { `legendOpen:!t))),` + `viewMode:edit)`; - const enableNewChartLibraryDebug = async () => { - await elasticChart.setNewChartUiDebugFlag(); - await queryBar.submitQuery(); - }; - describe('bwc shared urls', function describeIndexTests() { before(async function () { await PageObjects.dashboard.initTests(); @@ -81,13 +74,13 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { log.debug(`Navigating to ${url}`); await browser.get(url, true); await PageObjects.header.waitUntilLoadingHasFinished(); - await elasticChart.setNewChartUiDebugFlag(true); const query = await queryBar.getQueryString(); expect(query).to.equal('memory:>220000'); - await pieChart.expectEmptyPieChart(); - await dashboardExpect.panelCount(2); + const warningToast = await toasts.getToastElement(1); + expect(await warningToast.getVisibleText()).to.contain('Cannot load panels'); + await PageObjects.dashboard.waitForRenderComplete(); }); }); @@ -99,15 +92,13 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const url = `${kibanaLegacyBaseUrl}#/dashboard?${urlQuery}`; log.debug(`Navigating to ${url}`); await browser.get(url, true); - enableNewChartLibraryDebug(); await PageObjects.header.waitUntilLoadingHasFinished(); const query = await queryBar.getQueryString(); expect(query).to.equal('memory:>220000'); - await pieChart.expectPieSliceCount(5); - await dashboardExpect.panelCount(2); + const warningToast = await toasts.getToastElement(1); + expect(await warningToast.getVisibleText()).to.contain('Cannot load panels'); await PageObjects.dashboard.waitForRenderComplete(); - await dashboardExpect.selectedLegendColorCount('#F9D9F9', 5); }); it('loads a saved dashboard', async function () { @@ -120,15 +111,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { log.debug(`Navigating to ${url}`); await browser.get(url, true); await PageObjects.header.waitUntilLoadingHasFinished(); - enableNewChartLibraryDebug(); const query = await queryBar.getQueryString(); expect(query).to.equal('memory:>220000'); - await pieChart.expectPieSliceCount(5); - await dashboardExpect.panelCount(2); await PageObjects.dashboard.waitForRenderComplete(); - await dashboardExpect.selectedLegendColorCount('#F9D9F9', 5); }); it('loads a saved dashboard with query via dashboard_no_match', async function () { @@ -143,7 +130,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const query = await queryBar.getQueryString(); expect(query).to.equal('boop'); - await dashboardExpect.panelCount(2); await PageObjects.dashboard.waitForRenderComplete(); }); @@ -154,33 +140,26 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { log.debug(`Navigating to ${url}`); await browser.get(url, true); - await elasticChart.setNewChartUiDebugFlag(true); await PageObjects.header.waitUntilLoadingHasFinished(); - await dashboardExpect.selectedLegendColorCount('#000000', 5); }); it('back button works for old dashboards after state migrations', async () => { await PageObjects.dashboard.preserveCrossAppState(); const oldId = await PageObjects.dashboard.getDashboardIdFromCurrentUrl(); await PageObjects.dashboard.waitForRenderComplete(); - await dashboardExpect.selectedLegendColorCount('#000000', 5); const url = `${kibanaLegacyBaseUrl}#/dashboard?${urlQuery}`; log.debug(`Navigating to ${url}`); await browser.get(url); - await elasticChart.setNewChartUiDebugFlag(true); await PageObjects.header.waitUntilLoadingHasFinished(); await PageObjects.dashboard.waitForRenderComplete(); - await dashboardExpect.selectedLegendColorCount('#F9D9F9', 5); await browser.goBack(); await PageObjects.header.waitUntilLoadingHasFinished(); const newId = await PageObjects.dashboard.getDashboardIdFromCurrentUrl(); expect(newId).to.be.equal(oldId); await PageObjects.dashboard.waitForRenderComplete(); - await elasticChart.setNewChartUiDebugFlag(true); await queryBar.submitQuery(); - await dashboardExpect.selectedLegendColorCount('#000000', 5); }); }); }); diff --git a/test/functional/apps/dashboard/group3/dashboard_state.ts b/test/functional/apps/dashboard/group3/dashboard_state.ts index bc3f2ed2774a0..2c79f1fd61d23 100644 --- a/test/functional/apps/dashboard/group3/dashboard_state.ts +++ b/test/functional/apps/dashboard/group3/dashboard_state.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import chroma from 'chroma-js'; -import { DEFAULT_PANEL_WIDTH } from '@kbn/dashboard-plugin/public/application/embeddable/dashboard_constants'; +import { DEFAULT_PANEL_WIDTH } from '@kbn/dashboard-plugin/public/dashboard_constants'; import { PIE_CHART_VIS_NAME, AREA_CHART_VIS_NAME } from '../../../page_objects/dashboard_page'; import { FtrProviderContext } from '../../../ftr_provider_context'; diff --git a/test/functional/apps/dashboard/group4/dashboard_empty.ts b/test/functional/apps/dashboard/group4/dashboard_empty.ts index fe5a74bebbc25..02437b0685694 100644 --- a/test/functional/apps/dashboard/group4/dashboard_empty.ts +++ b/test/functional/apps/dashboard/group4/dashboard_empty.ts @@ -54,7 +54,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await kibanaServer.savedObjects.clean({ types: ['search', 'index-pattern'] }); // create the new data view from the dashboards/create route in order to test that the dashboard is loaded properly as soon as the data view is created... - await PageObjects.common.navigateToUrl('dashboard', '/create'); + await PageObjects.common.navigateToApp('dashboard', { hash: '/create' }); const button = await testSubjects.find('createDataViewButton'); button.click(); diff --git a/test/functional/apps/discover/group1/_discover.ts b/test/functional/apps/discover/group1/_discover.ts index 39793c9c047f0..9ac159fa39168 100644 --- a/test/functional/apps/discover/group1/_discover.ts +++ b/test/functional/apps/discover/group1/_discover.ts @@ -362,5 +362,39 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { expect(newMainPanelSize).to.be(mainPanelSize - resizeDistance); }); }); + + describe('URL state', () => { + const getCurrentDataViewId = (currentUrl: string) => { + const [indexSubstring] = currentUrl.match(/index:[^,]*/)!; + const dataViewId = indexSubstring.replace('index:', ''); + return dataViewId; + }; + + it('should show a warning and fall back to the default data view when navigating to a URL with an invalid data view ID', async () => { + await PageObjects.common.navigateToApp('discover'); + await PageObjects.timePicker.setDefaultAbsoluteRange(); + await PageObjects.header.waitUntilLoadingHasFinished(); + const originalUrl = await browser.getCurrentUrl(); + const dataViewId = getCurrentDataViewId(originalUrl); + const newUrl = originalUrl.replace(dataViewId, 'invalid-data-view-id'); + await browser.get(newUrl); + await PageObjects.header.waitUntilLoadingHasFinished(); + expect(await browser.getCurrentUrl()).to.be(originalUrl); + expect(await testSubjects.exists('dscDataViewNotFoundShowDefaultWarning')).to.be(true); + }); + + it('should show a warning and fall back to the current data view if the URL is updated to an invalid data view ID', async () => { + await PageObjects.common.navigateToApp('discover'); + await PageObjects.timePicker.setDefaultAbsoluteRange(); + const originalHash = await browser.execute<[], string>('return window.location.hash'); + const dataViewId = getCurrentDataViewId(originalHash); + const newHash = originalHash.replace(dataViewId, 'invalid-data-view-id'); + await browser.execute(`window.location.hash = "${newHash}"`); + await PageObjects.header.waitUntilLoadingHasFinished(); + const currentHash = await browser.execute<[], string>('return window.location.hash'); + expect(currentHash).to.be(originalHash); + expect(await testSubjects.exists('dscDataViewNotFoundShowSavedWarning')).to.be(true); + }); + }); }); } diff --git a/test/functional/apps/management/_scripted_fields.ts b/test/functional/apps/management/_scripted_fields.ts index 03a298182eec0..d12585088893d 100644 --- a/test/functional/apps/management/_scripted_fields.ts +++ b/test/functional/apps/management/_scripted_fields.ts @@ -211,10 +211,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName); await PageObjects.header.waitUntilLoadingHasFinished(); // verify Lens opens a visualization - expect(await testSubjects.getVisibleTextAll('lns-dimensionTrigger')).to.contain( - '@timestamp', - 'Median of ram_Pain1' - ); + await retry.waitFor('lens visualization', async () => { + const elements = await testSubjects.getVisibleTextAll('lns-dimensionTrigger'); + return elements[0] === '@timestamp' && elements[1] === 'Median of ram_Pain1'; + }); }); }); @@ -314,9 +314,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); // verify Lens opens a visualization - expect(await testSubjects.getVisibleTextAll('lns-dimensionTrigger')).to.contain( - 'Top 5 values of painString' - ); + await retry.waitFor('lens visualization', async () => { + const elements = await testSubjects.getVisibleTextAll('lns-dimensionTrigger'); + return elements[0] === 'Top 5 values of painString'; + }); }); after(async () => { @@ -408,9 +409,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); // verify Lens opens a visualization - expect(await testSubjects.getVisibleTextAll('lns-dimensionTrigger')).to.contain( - 'Top 5 values of painBool' - ); + await retry.waitFor('lens visualization', async () => { + const elements = await testSubjects.getVisibleTextAll('lns-dimensionTrigger'); + return elements[0] === 'Top 5 values of painBool'; + }); }); after(async () => { @@ -503,7 +505,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); // verify Lens opens a visualization - expect(await testSubjects.getVisibleTextAll('lns-dimensionTrigger')).to.contain('painDate'); + await retry.waitFor('lens visualization', async () => { + const elements = await testSubjects.getVisibleTextAll('lns-dimensionTrigger'); + return elements[0] === 'painDate'; + }); }); }); diff --git a/test/functional/page_objects/console_page.ts b/test/functional/page_objects/console_page.ts index 50cc2e7029d48..9f662a09146e9 100644 --- a/test/functional/page_objects/console_page.ts +++ b/test/functional/page_objects/console_page.ts @@ -368,4 +368,40 @@ export class ConsolePageObject extends FtrService { const textArea = await this.testSubjects.find('console-textarea'); await textArea.pressKeys([Key[process.platform === 'darwin' ? 'COMMAND' : 'CONTROL'], '/']); } + + public async clickContextMenu() { + const contextMenu = await this.testSubjects.find('toggleConsoleMenu'); + await contextMenu.click(); + } + + public async isContextMenuOpen() { + return await this.testSubjects.exists('consoleMenu'); + } + + public async isCopyAsCurlButtonVisible() { + return await this.testSubjects.exists('consoleMenuCopyAsCurl'); + } + + public async isOpenDocumentationButtonVisible() { + return await this.testSubjects.exists('consoleMenuOpenDocs'); + } + + public async isAutoIndentButtonVisible() { + return await this.testSubjects.exists('consoleMenuAutoIndent'); + } + + public async clickCopyAsCurlButton() { + const button = await this.testSubjects.find('consoleMenuCopyAsCurl'); + await button.click(); + } + + public async clickOpenDocumentationButton() { + const button = await this.testSubjects.find('consoleMenuOpenDocs'); + await button.click(); + } + + public async clickAutoIndentButton() { + const button = await this.testSubjects.find('consoleMenuAutoIndent'); + await button.click(); + } } diff --git a/test/functional/page_objects/dashboard_page.ts b/test/functional/page_objects/dashboard_page.ts index 7a579f4e4f84b..bad1f6bdebf2b 100644 --- a/test/functional/page_objects/dashboard_page.ts +++ b/test/functional/page_objects/dashboard_page.ts @@ -12,6 +12,7 @@ export const LINE_CHART_VIS_NAME = 'Visualization漢字 LineChart'; import expect from '@kbn/expect'; import { FtrService } from '../ftr_provider_context'; +import { CommonPageObject } from './common_page'; interface SaveDashboardOptions { /** @@ -430,6 +431,31 @@ export class DashboardPageObject extends FtrService { await this.switchToEditMode(); } + public async gotoDashboardURL({ + id, + args, + editMode, + }: { + id?: string; + editMode?: boolean; + args?: Parameters['navigateToActualUrl']>[2]; + } = {}) { + let dashboardLocation = `/create`; + if (id) { + const edit = editMode ? `?_a=(viewMode:edit)` : ''; + dashboardLocation = `/view/${id}${edit}`; + } + this.common.navigateToActualUrl('dashboard', dashboardLocation, args); + } + + public async gotoDashboardListingURL({ + args, + }: { + args?: Parameters['navigateToActualUrl']>[2]; + } = {}) { + await this.common.navigateToActualUrl('dashboard', '/list', args); + } + public async renameDashboard(dashboardName: string) { this.log.debug(`Naming dashboard ` + dashboardName); await this.testSubjects.click('dashboardRenameButton'); diff --git a/test/functional/page_objects/discover_page.ts b/test/functional/page_objects/discover_page.ts index 5a6f842086498..cc398f8d67be6 100644 --- a/test/functional/page_objects/discover_page.ts +++ b/test/functional/page_objects/discover_page.ts @@ -486,7 +486,7 @@ export class DiscoverPageObject extends FtrService { public async clickFieldListItemVisualize(fieldName: string) { const field = await this.testSubjects.find(`field-${fieldName}-showDetails`); - const isActive = await field.elementHasClass('dscSidebarItem--active'); + const isActive = await field.elementHasClass('kbnFieldButton-isActive'); if (!isActive) { // expand the field to show the "Visualize" button @@ -494,6 +494,7 @@ export class DiscoverPageObject extends FtrService { } await this.testSubjects.click(`fieldVisualize-${fieldName}`); + await this.header.waitUntilLoadingHasFinished(); } public async expectFieldListItemVisualize(field: string) { diff --git a/test/functional/page_objects/unified_search_page.ts b/test/functional/page_objects/unified_search_page.ts index c46e79a2f1546..6dc77ce91cc85 100644 --- a/test/functional/page_objects/unified_search_page.ts +++ b/test/functional/page_objects/unified_search_page.ts @@ -13,13 +13,21 @@ export class UnifiedSearchPageObject extends FtrService { private readonly testSubjects = this.ctx.getService('testSubjects'); private readonly find = this.ctx.getService('find'); - public async switchDataView(switchButtonSelector: string, dataViewTitle: string) { + public async switchDataView( + switchButtonSelector: string, + dataViewTitle: string, + transitionFromTextBasedLanguages?: boolean + ) { await this.testSubjects.click(switchButtonSelector); const indexPatternSwitcher = await this.testSubjects.find('indexPattern-switcher', 500); await this.testSubjects.setValue('indexPattern-switcher--input', dataViewTitle); await (await indexPatternSwitcher.findByCssSelector(`[title="${dataViewTitle}"]`)).click(); + if (Boolean(transitionFromTextBasedLanguages)) { + await this.testSubjects.click('unifiedSearch_switch_noSave'); + } + await this.retry.waitFor( 'wait for updating switcher', async () => (await this.getSelectedDataView(switchButtonSelector)) === dataViewTitle @@ -66,4 +74,10 @@ export class UnifiedSearchPageObject extends FtrService { }); await this.testSubjects.click(adHoc ? 'exploreIndexPatternButton' : 'saveIndexPatternButton'); } + + public async selectTextBasedLanguage(language: string) { + await this.find.clickByCssSelector( + `[data-test-subj="text-based-languages-switcher"] [title="${language}"]` + ); + } } diff --git a/test/plugin_functional/test_suites/telemetry/telemetry.ts b/test/plugin_functional/test_suites/telemetry/telemetry.ts index 3b087c2705c10..1c68abd5426d3 100644 --- a/test/plugin_functional/test_suites/telemetry/telemetry.ts +++ b/test/plugin_functional/test_suites/telemetry/telemetry.ts @@ -14,7 +14,8 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide const browser = getService('browser'); const PageObjects = getPageObjects(['common']); - describe('Telemetry service', () => { + // FLAKY: https://github.com/elastic/kibana/issues/107034 + describe.skip('Telemetry service', () => { const checkCanSendTelemetry = (): Promise => { return browser.executeAsync((cb) => { (window as unknown as Record Promise>) diff --git a/x-pack/performance/jest.config.js b/x-pack/performance/jest.config.js new file mode 100644 index 0000000000000..b8afeee25a9ed --- /dev/null +++ b/x-pack/performance/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test/jest_node', + rootDir: '../..', + roots: ['/x-pack/performance'], +}; diff --git a/x-pack/performance/services/lib/time.test.ts b/x-pack/performance/services/lib/time.test.ts new file mode 100644 index 0000000000000..a1dab5878fcc2 --- /dev/null +++ b/x-pack/performance/services/lib/time.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ms, toMs } from './time'; + +describe('ms()', () => { + it('converts simple timestrings to milliseconds', () => { + expect(ms('1s')).toMatchInlineSnapshot(`1000`); + expect(ms('10s')).toMatchInlineSnapshot(`10000`); + expect(ms('1m')).toMatchInlineSnapshot(`60000`); + expect(ms('10m')).toMatchInlineSnapshot(`600000`); + expect(ms('0.5s')).toMatchInlineSnapshot(`500`); + expect(ms('0.5m')).toMatchInlineSnapshot(`30000`); + }); +}); + +describe('toMs()', () => { + it('converts strings to ms, returns number directly', () => { + expect(toMs(1000)).toBe(1000); + expect(toMs('1s')).toBe(1000); + }); +}); diff --git a/x-pack/performance/services/lib/time.ts b/x-pack/performance/services/lib/time.ts new file mode 100644 index 0000000000000..4557ca71d2d36 --- /dev/null +++ b/x-pack/performance/services/lib/time.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const SECOND = 1000; +export const MINUTE = 60 * SECOND; + +const TIME_STR_RE = /^((?:\d+)(?:\.\d+)?)(m|s)$/i; + +/** + * Either a number of milliseconds or a simple time string (eg. 2m or 30s) + */ +export type TimeOrMilliseconds = number | string; + +export function toMs(timeOrMs: TimeOrMilliseconds) { + return typeof timeOrMs === 'number' ? timeOrMs : ms(timeOrMs); +} + +/** + * Convert a basic time string into milliseconds. The string can end with + * `m` (for minutes) or `s` (for seconds) and have any number before it. + */ +export function ms(time: string) { + const match = time.match(TIME_STR_RE); + if (!match) { + throw new Error('invalid time string, expected a number followed by "m" or "s"'); + } + + const [, num, unit] = match; + switch (unit.toLowerCase()) { + case 's': + return Number.parseFloat(num) * SECOND; + case 'm': + return Number.parseFloat(num) * MINUTE; + default: + throw new Error(`unexpected timestring unit [time=${time}] [unit=${unit}]`); + } +} diff --git a/x-pack/performance/services/toasts.ts b/x-pack/performance/services/toasts.ts index b3859ddb92ec4..4a556e3780105 100644 --- a/x-pack/performance/services/toasts.ts +++ b/x-pack/performance/services/toasts.ts @@ -9,6 +9,8 @@ import { ToolingLog } from '@kbn/tooling-log'; import { subj } from '@kbn/test-subj-selector'; import { Page } from 'playwright'; +import { toMs, type TimeOrMilliseconds } from './lib/time'; + export class ToastsService { constructor(private readonly log: ToolingLog, private readonly page: Page) {} @@ -16,13 +18,18 @@ export class ToastsService { * Wait for a toast with some bit of text matching the provided `textSnipped`, then clear * it and resolve the promise. */ - async waitForAndClear(textSnippet: string) { + async waitForAndClear( + textSnippet: string, + options?: { + /** How long should we wait for the toast to show up? */ + timeout?: TimeOrMilliseconds; + } + ) { const txt = JSON.stringify(textSnippet); this.log.info(`waiting for toast that has the text ${txt}`); - const toastSel = `.euiToast:has-text(${txt})`; - const toast = this.page.locator(toastSel); - await toast.waitFor(); + const toast = this.page.locator(`.euiToast:has-text(${txt})`); + await toast.waitFor({ timeout: toMs(options?.timeout ?? '2m') }); this.log.info('toast found, closing'); diff --git a/x-pack/performance/tsconfig.json b/x-pack/performance/tsconfig.json index caff6d53f4476..923a42ffe52f3 100644 --- a/x-pack/performance/tsconfig.json +++ b/x-pack/performance/tsconfig.json @@ -5,7 +5,7 @@ "emitDeclarationOnly": true, "declaration": true, "declarationMap": true, - "types": ["node", "mocha"] + "types": ["node", "jest"] }, "include": ["**/*.ts"], } diff --git a/x-pack/plugins/actions/server/config.test.ts b/x-pack/plugins/actions/server/config.test.ts index e6e3a24db5214..475b88089581f 100644 --- a/x-pack/plugins/actions/server/config.test.ts +++ b/x-pack/plugins/actions/server/config.test.ts @@ -163,6 +163,28 @@ describe('config validation', () => { `); }); + test('validates proxyUrl', () => { + const proxyUrl = 'https://test.com'; + const badProxyUrl = 'bad url'; + let validated: ActionsConfig; + + validated = configSchema.validate({ proxyUrl }); + expect(validated.proxyUrl).toEqual(proxyUrl); + expect(getValidatedConfig(mockLogger, validated).proxyUrl).toEqual(proxyUrl); + expect(mockLogger.warn.mock.calls).toMatchInlineSnapshot(`Array []`); + + validated = configSchema.validate({ proxyUrl: badProxyUrl }); + expect(validated.proxyUrl).toEqual(badProxyUrl); + expect(getValidatedConfig(mockLogger, validated).proxyUrl).toEqual(badProxyUrl); + expect(mockLogger.warn.mock.calls).toMatchInlineSnapshot(` + Array [ + Array [ + "The confguration xpack.actions.proxyUrl: bad url is invalid.", + ], + ] + `); + }); + // Most of the customHostSettings tests are in ./lib/custom_host_settings.test.ts // but this one seemed more relevant for this test suite, since url is the one // required property. diff --git a/x-pack/plugins/actions/server/config.ts b/x-pack/plugins/actions/server/config.ts index 4c8ca7ff9fff7..76270a466ee8f 100644 --- a/x-pack/plugins/actions/server/config.ts +++ b/x-pack/plugins/actions/server/config.ts @@ -127,6 +127,15 @@ export type ActionsConfig = TypeOf; export function getValidatedConfig(logger: Logger, originalConfig: ActionsConfig): ActionsConfig { const proxyBypassHosts = originalConfig.proxyBypassHosts; const proxyOnlyHosts = originalConfig.proxyOnlyHosts; + const proxyUrl = originalConfig.proxyUrl; + + if (proxyUrl) { + try { + new URL(proxyUrl); + } catch (err) { + logger.warn(`The confguration xpack.actions.proxyUrl: ${proxyUrl} is invalid.`); + } + } if (proxyBypassHosts && proxyOnlyHosts) { logger.warn( diff --git a/x-pack/plugins/aiops/public/components/document_count_content/document_count_chart/document_count_chart.tsx b/x-pack/plugins/aiops/public/components/document_count_content/document_count_chart/document_count_chart.tsx index 1989316b15ec1..ad317fbf222ec 100644 --- a/x-pack/plugins/aiops/public/components/document_count_content/document_count_chart/document_count_chart.tsx +++ b/x-pack/plugins/aiops/public/components/document_count_content/document_count_chart/document_count_chart.tsx @@ -120,7 +120,7 @@ export const DocumentCountChart: FC = ({ const overallSeriesNameWithSplit = i18n.translate( 'xpack.aiops.dataGrid.field.documentCountChartSplit.seriesLabel', { - defaultMessage: 'other document count', + defaultMessage: 'Other document count', } ); diff --git a/x-pack/plugins/aiops/public/components/document_count_content/document_count_content/document_count_content.tsx b/x-pack/plugins/aiops/public/components/document_count_content/document_count_content/document_count_content.tsx index 1f179be0ba975..e262ad0348d98 100644 --- a/x-pack/plugins/aiops/public/components/document_count_content/document_count_content/document_count_content.tsx +++ b/x-pack/plugins/aiops/public/components/document_count_content/document_count_content/document_count_content.tsx @@ -5,13 +5,12 @@ * 2.0. */ -import React, { useEffect, useState, FC, useMemo } from 'react'; +import React, { useEffect, useState, FC } from 'react'; import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import type { WindowParameters } from '@kbn/aiops-utils'; -import type { ChangePoint } from '@kbn/ml-agg-utils'; import { DocumentCountChart, DocumentCountChartPoint } from '../document_count_chart'; import { TotalCountHeader } from '../total_count_header'; @@ -27,9 +26,9 @@ const clearSelectionLabel = i18n.translate( export interface DocumentCountContentProps { brushSelectionUpdateHandler: (d: WindowParameters) => void; clearSelectionHandler: () => void; - changePoint?: ChangePoint; documentCountStats?: DocumentCountStats; documentCountStatsSplit?: DocumentCountStats; + documentCountStatsSplitLabel?: string; totalCount: number; windowParameters?: WindowParameters; } @@ -37,9 +36,9 @@ export interface DocumentCountContentProps { export const DocumentCountContent: FC = ({ brushSelectionUpdateHandler, clearSelectionHandler, - changePoint, documentCountStats, documentCountStatsSplit, + documentCountStatsSplitLabel = '', totalCount, windowParameters, }) => { @@ -52,10 +51,6 @@ export const DocumentCountContent: FC = ({ const bucketTimestamps = Object.keys(documentCountStats?.buckets ?? {}).map((time) => +time); const timeRangeEarliest = Math.min(...bucketTimestamps); const timeRangeLatest = Math.max(...bucketTimestamps); - const chartPointsSplitLabel = useMemo( - () => `${changePoint?.fieldName}:${changePoint?.fieldValue}`, - [changePoint] - ); if ( documentCountStats === undefined || @@ -121,7 +116,7 @@ export const DocumentCountContent: FC = ({ timeRangeEarliest={timeRangeEarliest} timeRangeLatest={timeRangeLatest} interval={documentCountStats.interval} - chartPointsSplitLabel={chartPointsSplitLabel} + chartPointsSplitLabel={documentCountStatsSplitLabel} isBrushCleared={isBrushCleared} /> )} diff --git a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_analysis.tsx b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_analysis.tsx index a0fb825ee4064..2425161615915 100644 --- a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_analysis.tsx +++ b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_analysis.tsx @@ -23,7 +23,6 @@ import { useFetchStream } from '@kbn/aiops-utils'; import type { WindowParameters } from '@kbn/aiops-utils'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import type { ChangePoint } from '@kbn/ml-agg-utils'; import type { Query } from '@kbn/es-query'; import { useAiopsAppContext } from '../../hooks/use_aiops_app_context'; @@ -32,7 +31,7 @@ import type { ApiExplainLogRateSpikes } from '../../../common/api'; import { SpikeAnalysisGroupsTable } from '../spike_analysis_table'; import { SpikeAnalysisTable } from '../spike_analysis_table'; -import { GroupTableItem } from '../spike_analysis_table/spike_analysis_table_groups'; +import { useSpikeAnalysisTableRowContext } from '../spike_analysis_table/spike_analysis_table_row_provider'; const groupResultsMessage = i18n.translate( 'xpack.aiops.spikeAnalysisTable.groupedSwitchLabel.groupResults', @@ -54,10 +53,6 @@ interface ExplainLogRateSpikesAnalysisProps { /** Window parameters for the analysis */ windowParameters: WindowParameters; searchQuery: Query['query']; - onPinnedChangePoint?: (changePoint: ChangePoint | null) => void; - onSelectedChangePoint?: (changePoint: ChangePoint | null) => void; - selectedChangePoint?: ChangePoint; - onSelectedGroup?: (group: GroupTableItem | null) => void; } export const ExplainLogRateSpikesAnalysis: FC = ({ @@ -66,14 +61,12 @@ export const ExplainLogRateSpikesAnalysis: FC latest, windowParameters, searchQuery, - onPinnedChangePoint, - onSelectedChangePoint, - selectedChangePoint, - onSelectedGroup, }) => { const { http } = useAiopsAppContext(); const basePath = http.basePath.get() ?? ''; + const { clearAllRowState } = useSpikeAnalysisTableRowContext(); + const [currentAnalysisWindowParameters, setCurrentAnalysisWindowParameters] = useState< WindowParameters | undefined >(); @@ -81,6 +74,9 @@ export const ExplainLogRateSpikesAnalysis: FC const onSwitchToggle = (e: { target: { checked: React.SetStateAction } }) => { setGroupResults(e.target.checked); + + // When toggling the group switch, clear all row selections + clearAllRowState(); }; const { @@ -109,15 +105,9 @@ export const ExplainLogRateSpikesAnalysis: FC // Start handler clears possibly hovered or pinned // change points on analysis refresh. function startHandler() { - // Reset grouping to false when restarting the analysis. + // Reset grouping to false and clear all row selections when restarting the analysis. setGroupResults(false); - - if (onPinnedChangePoint) { - onPinnedChangePoint(null); - } - if (onSelectedChangePoint) { - onSelectedChangePoint(null); - } + clearAllRowState(); setCurrentAnalysisWindowParameters(windowParameters); start(); @@ -249,10 +239,6 @@ export const ExplainLogRateSpikesAnalysis: FC changePoints={data.changePoints} groupTableItems={groupTableItems} loading={isRunning} - onPinnedChangePoint={onPinnedChangePoint} - onSelectedChangePoint={onSelectedChangePoint} - selectedChangePoint={selectedChangePoint} - onSelectedGroup={onSelectedGroup} dataViewId={dataView.id} /> ) : null} @@ -260,9 +246,6 @@ export const ExplainLogRateSpikesAnalysis: FC ) : null} diff --git a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_app_state.tsx b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_app_state.tsx index 9b9395721e535..34460240d0134 100644 --- a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_app_state.tsx +++ b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_app_state.tsx @@ -36,6 +36,8 @@ import { import type { AiopsAppDependencies } from '../../hooks/use_aiops_app_context'; import { AiopsAppContext } from '../../hooks/use_aiops_app_context'; +import { SpikeAnalysisTableRowStateProvider } from '../spike_analysis_table/spike_analysis_table_row_provider'; + import { ExplainLogRateSpikesPage } from './explain_log_rate_spikes_page'; export interface ExplainLogRateSpikesAppStateProps { @@ -164,7 +166,9 @@ export const ExplainLogRateSpikesAppState: FC return ( - + + + ); diff --git a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_page.tsx b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_page.tsx index feff4f2e8211f..63ccb20e4e6b0 100644 --- a/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_page.tsx +++ b/x-pack/plugins/aiops/public/components/explain_log_rate_spikes/explain_log_rate_spikes_page.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { useCallback, useEffect, useMemo, useState, FC } from 'react'; +import React, { useCallback, useEffect, useState, FC } from 'react'; import { EuiEmptyPrompt, EuiFlexGroup, @@ -19,6 +19,7 @@ import { EuiTitle, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import type { DataView } from '@kbn/data-views-plugin/public'; import type { WindowParameters } from '@kbn/aiops-utils'; import type { ChangePoint } from '@kbn/ml-agg-utils'; @@ -38,10 +39,21 @@ import { SearchPanel } from '../search_panel'; import { restorableDefaults } from './explain_log_rate_spikes_app_state'; import { ExplainLogRateSpikesAnalysis } from './explain_log_rate_spikes_analysis'; import type { GroupTableItem } from '../spike_analysis_table/spike_analysis_table_groups'; +import { useSpikeAnalysisTableRowContext } from '../spike_analysis_table/spike_analysis_table_row_provider'; // TODO port to `@emotion/react` once `useEuiBreakpoint` is available https://github.com/elastic/eui/pull/6057 import './explain_log_rate_spikes_page.scss'; +function getDocumentCountStatsSplitLabel(changePoint?: ChangePoint, group?: GroupTableItem) { + if (changePoint) { + return `${changePoint?.fieldName}:${changePoint?.fieldValue}`; + } else if (group) { + return i18n.translate('xpack.aiops.spikeAnalysisPage.documentCountStatsSplitGroupLabel', { + defaultMessage: 'Selected group', + }); + } +} + /** * ExplainLogRateSpikes props require a data view. */ @@ -58,6 +70,15 @@ export const ExplainLogRateSpikesPage: FC = ({ }) => { const { data: dataService } = useAiopsAppContext(); + const { + currentSelectedChangePoint, + currentSelectedGroup, + setPinnedChangePoint, + setPinnedGroup, + setSelectedChangePoint, + setSelectedGroup, + } = useSpikeAnalysisTableRowContext(); + const [aiopsListState, setAiopsListState] = usePageUrlState(AppStateKey, restorableDefaults); const [globalState, setGlobalState] = useUrlState('_g'); @@ -93,19 +114,6 @@ export const ExplainLogRateSpikesPage: FC = ({ [currentSavedSearch, aiopsListState, setAiopsListState] ); - const [pinnedChangePoint, setPinnedChangePoint] = useState(null); - const [selectedChangePoint, setSelectedChangePoint] = useState(null); - const [selectedGroup, setSelectedGroup] = useState(null); - - // If a row is pinned, still overrule with a potentially hovered row. - const currentSelectedChangePoint = useMemo(() => { - if (selectedChangePoint) { - return selectedChangePoint; - } else if (pinnedChangePoint) { - return pinnedChangePoint; - } - }, [pinnedChangePoint, selectedChangePoint]); - const { documentStats, timefilter, @@ -119,8 +127,7 @@ export const ExplainLogRateSpikesPage: FC = ({ aiopsListState, setGlobalState, currentSelectedChangePoint, - undefined, - selectedGroup + currentSelectedGroup ); const { totalCount, documentCountStats, documentCountStatsCompare } = documentStats; @@ -170,6 +177,7 @@ export const ExplainLogRateSpikesPage: FC = ({ function clearSelection() { setWindowParameters(undefined); setPinnedChangePoint(null); + setPinnedGroup(null); setSelectedChangePoint(null); setSelectedGroup(null); } @@ -230,12 +238,15 @@ export const ExplainLogRateSpikesPage: FC = ({ clearSelectionHandler={clearSelection} documentCountStats={documentCountStats} documentCountStatsSplit={ - currentSelectedChangePoint || selectedGroup + currentSelectedChangePoint || currentSelectedGroup ? documentCountStatsCompare : undefined } + documentCountStatsSplitLabel={getDocumentCountStatsSplitLabel( + currentSelectedChangePoint, + currentSelectedGroup + )} totalCount={totalCount} - changePoint={currentSelectedChangePoint} windowParameters={windowParameters} /> @@ -250,10 +261,6 @@ export const ExplainLogRateSpikesPage: FC = ({ latest={latest} windowParameters={windowParameters} searchQuery={searchQuery} - onPinnedChangePoint={setPinnedChangePoint} - onSelectedChangePoint={setSelectedChangePoint} - selectedChangePoint={currentSelectedChangePoint} - onSelectedGroup={setSelectedGroup} /> )} {windowParameters === undefined && ( diff --git a/x-pack/plugins/aiops/public/components/log_categorization/category_table/category_table.tsx b/x-pack/plugins/aiops/public/components/log_categorization/category_table/category_table.tsx index 1aa613962ff9e..9c5862d34dbde 100644 --- a/x-pack/plugins/aiops/public/components/log_categorization/category_table/category_table.tsx +++ b/x-pack/plugins/aiops/public/components/log_categorization/category_table/category_table.tsx @@ -10,6 +10,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import type { TimefilterContract } from '@kbn/data-plugin/public'; import { + useEuiBackgroundColor, EuiButton, EuiSpacer, EuiFlexGroup, @@ -62,6 +63,7 @@ export const CategoryTable: FC = ({ setSelectedCategory, }) => { const euiTheme = useEuiTheme(); + const primaryBackgroundColor = useEuiBackgroundColor('primary'); const { openInDiscoverWithFilter } = useDiscoverLinks(); const [selectedCategories, setSelectedCategories] = useState([]); const { onTableChange, pagination, sorting } = useTableState(categories ?? [], 'key'); @@ -193,22 +195,18 @@ export const CategoryTable: FC = ({ pinnedCategory.key === category.key ) { return { - backgroundColor: 'rgb(227,240,249,0.37)', + backgroundColor: primaryBackgroundColor, }; } - if ( - selectedCategory && - selectedCategory.key === category.key && - selectedCategory.key === category.key - ) { + if (selectedCategory && selectedCategory.key === category.key) { return { backgroundColor: euiTheme.euiColorLightestShade, }; } return { - backgroundColor: 'white', + backgroundColor: euiTheme.euiColorEmptyShade, }; }; diff --git a/x-pack/plugins/aiops/public/components/log_categorization/information_text.tsx b/x-pack/plugins/aiops/public/components/log_categorization/information_text.tsx new file mode 100644 index 0000000000000..bf80b55fee37c --- /dev/null +++ b/x-pack/plugins/aiops/public/components/log_categorization/information_text.tsx @@ -0,0 +1,101 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FC } from 'react'; + +import { FormattedMessage } from '@kbn/i18n-react'; +import { EuiEmptyPrompt } from '@elastic/eui'; + +interface Props { + eventRateLength: number; + fieldSelected: boolean; + categoriesLength: number | null; + loading: boolean; +} + +export const InformationText: FC = ({ + eventRateLength, + fieldSelected, + categoriesLength, + loading, +}) => { + if (loading === true) { + return null; + } + return ( + <> + {eventRateLength === 0 ? ( + + + + } + titleSize="xs" + body={ +

+ +

+ } + data-test-subj="aiopsNoWindowParametersEmptyPrompt" + /> + ) : null} + + {eventRateLength > 0 && categoriesLength === null ? ( + + + + } + titleSize="xs" + body={ +

+ +

+ } + data-test-subj="aiopsNoWindowParametersEmptyPrompt" + /> + ) : null} + + {eventRateLength > 0 && categoriesLength !== null && categoriesLength === 0 ? ( + + + + } + titleSize="xs" + body={ +

+ +

+ } + data-test-subj="aiopsNoWindowParametersEmptyPrompt" + /> + ) : null} + + ); +}; diff --git a/x-pack/plugins/aiops/public/components/log_categorization/log_categorization_page.tsx b/x-pack/plugins/aiops/public/components/log_categorization/log_categorization_page.tsx index 6bc90db0a7b71..4eb6da0e58b9f 100644 --- a/x-pack/plugins/aiops/public/components/log_categorization/log_categorization_page.tsx +++ b/x-pack/plugins/aiops/public/components/log_categorization/log_categorization_page.tsx @@ -40,6 +40,7 @@ import { useCategorizeRequest } from './use_categorize_request'; import type { EventRate, Category, SparkLinesPerCategory } from './use_categorize_request'; import { CategoryTable } from './category_table'; import { DocumentCountChart } from './document_count_chart'; +import { InformationText } from './information_text'; export interface LogCategorizationPageProps { dataView: DataView; @@ -116,6 +117,7 @@ export const LogCategorizationPage: FC = ({ aiopsListState, setGlobalState, undefined, + undefined, BAR_TARGET ); @@ -159,6 +161,7 @@ export const LogCategorizationPage: FC = ({ docCount, })) ); + setCategories(null); setTotalCount(documentStats.totalCount); } }, [documentStats, earliest, latest, searchQueryLanguage, searchString, searchQuery]); @@ -209,6 +212,7 @@ export const LogCategorizationPage: FC = ({ ]); const onFieldChange = (value: EuiComboBoxOptionOption[] | undefined) => { + setCategories(null); setSelectedField(value && value.length ? value[0].label : undefined); }; @@ -312,8 +316,17 @@ export const LogCategorizationPage: FC = ({ ) : null} + {loading === true ? : null} - {categories !== null ? ( + + + + {selectedField !== undefined && categories !== null && categories.length > 0 ? ( void; - onSelectedChangePoint?: (changePoint: ChangePoint | null) => void; - selectedChangePoint?: ChangePoint; } export const SpikeAnalysisTable: FC = ({ changePoints, dataViewId, loading, - onPinnedChangePoint, - onSelectedChangePoint, - selectedChangePoint, }) => { const euiTheme = useEuiTheme(); + const primaryBackgroundColor = useEuiBackgroundColor('primary'); + + const { pinnedChangePoint, selectedChangePoint, setPinnedChangePoint, setSelectedChangePoint } = + useSpikeAnalysisTableRowContext(); const [pageIndex, setPageIndex] = useState(0); const [pageSize, setPageSize] = useState(10); @@ -318,6 +318,32 @@ export const SpikeAnalysisTable: FC = ({ }; }, [pageIndex, pageSize, sortField, sortDirection, changePoints]); + const getRowStyle = (changePoint: ChangePoint) => { + if ( + pinnedChangePoint && + pinnedChangePoint.fieldName === changePoint.fieldName && + pinnedChangePoint.fieldValue === changePoint.fieldValue + ) { + return { + backgroundColor: primaryBackgroundColor, + }; + } + + if ( + selectedChangePoint && + selectedChangePoint.fieldName === changePoint.fieldName && + selectedChangePoint.fieldValue === changePoint.fieldValue + ) { + return { + backgroundColor: euiTheme.euiColorLightestShade, + }; + } + + return { + backgroundColor: euiTheme.euiColorEmptyShade, + }; + }; + // Don't pass on the `loading` state to the table itself because // it disables hovering events. Because the mini histograms take a while // to load, hovering would not update the main chart. Instead, @@ -339,28 +365,22 @@ export const SpikeAnalysisTable: FC = ({ return { 'data-test-subj': `aiopsSpikeAnalysisTableRow row-${changePoint.fieldName}-${changePoint.fieldValue}`, onClick: () => { - if (onPinnedChangePoint) { - onPinnedChangePoint(changePoint); + if ( + changePoint.fieldName === pinnedChangePoint?.fieldName && + changePoint.fieldValue === pinnedChangePoint?.fieldValue + ) { + setPinnedChangePoint(null); + } else { + setPinnedChangePoint(changePoint); } }, onMouseEnter: () => { - if (onSelectedChangePoint) { - onSelectedChangePoint(changePoint); - } + setSelectedChangePoint(changePoint); }, onMouseLeave: () => { - if (onSelectedChangePoint) { - onSelectedChangePoint(null); - } + setSelectedChangePoint(null); }, - style: - selectedChangePoint && - selectedChangePoint.fieldValue === changePoint.fieldValue && - selectedChangePoint.fieldName === changePoint.fieldName - ? { - backgroundColor: euiTheme.euiColorLightestShade, - } - : null, + style: getRowStyle(changePoint), }; }} /> diff --git a/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_groups.tsx b/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_groups.tsx index a7503e7d49111..6c8da64cb0e89 100644 --- a/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_groups.tsx +++ b/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_groups.tsx @@ -9,6 +9,7 @@ import React, { FC, useCallback, useMemo, useState } from 'react'; import { sortBy } from 'lodash'; import { + useEuiBackgroundColor, EuiBadge, EuiBasicTable, EuiBasicTableColumn, @@ -34,6 +35,7 @@ import { MiniHistogram } from '../mini_histogram'; import { getFailedTransactionsCorrelationImpactLabel } from './get_failed_transactions_correlation_impact_label'; import { SpikeAnalysisTable } from './spike_analysis_table'; +import { useSpikeAnalysisTableRowContext } from './spike_analysis_table_row_provider'; const NARROW_COLUMN_WIDTH = '120px'; const EXPAND_COLUMN_WIDTH = '40px'; @@ -64,10 +66,6 @@ interface SpikeAnalysisTableProps { groupTableItems: GroupTableItem[]; dataViewId?: string; loading: boolean; - onPinnedChangePoint?: (changePoint: ChangePoint | null) => void; - onSelectedChangePoint?: (changePoint: ChangePoint | null) => void; - selectedChangePoint?: ChangePoint; - onSelectedGroup?: (group: GroupTableItem | null) => void; } export const SpikeAnalysisGroupsTable: FC = ({ @@ -75,10 +73,6 @@ export const SpikeAnalysisGroupsTable: FC = ({ groupTableItems, dataViewId, loading, - onPinnedChangePoint, - onSelectedChangePoint, - selectedChangePoint, - onSelectedGroup, }) => { const [pageIndex, setPageIndex] = useState(0); const [pageSize, setPageSize] = useState(10); @@ -89,6 +83,10 @@ export const SpikeAnalysisGroupsTable: FC = ({ ); const euiTheme = useEuiTheme(); + const primaryBackgroundColor = useEuiBackgroundColor('primary'); + + const { pinnedGroup, selectedGroup, setPinnedGroup, setSelectedGroup } = + useSpikeAnalysisTableRowContext(); const toggleDetails = (item: GroupTableItem) => { const itemIdToExpandedRowMapValues = { ...itemIdToExpandedRowMap }; @@ -121,9 +119,6 @@ export const SpikeAnalysisGroupsTable: FC = ({ ); @@ -233,9 +228,26 @@ export const SpikeAnalysisGroupsTable: FC = ({ { 'data-test-subj': 'aiopsSpikeAnalysisGroupsTableColumnGroup', field: 'group', - name: i18n.translate('xpack.aiops.explainLogRateSpikes.spikeAnalysisTableGroups.groupLabel', { - defaultMessage: 'Group', - }), + name: ( + + <> + + + + + ), render: (_, { group, repeatedValues }) => { const valuesBadges = []; for (const fieldName in group) { @@ -292,7 +304,7 @@ export const SpikeAnalysisGroupsTable: FC = ({ 'xpack.aiops.explainLogRateSpikes.spikeAnalysisTableGroups.logRateColumnTooltip', { defaultMessage: - 'A visual representation of the impact of the field on the message rate difference', + 'A visual representation of the impact of the group on the message rate difference', } )} > @@ -366,9 +378,9 @@ export const SpikeAnalysisGroupsTable: FC = ({ @@ -458,6 +470,24 @@ export const SpikeAnalysisGroupsTable: FC = ({ }; }, [pageIndex, pageSize, sortField, sortDirection, groupTableItems]); + const getRowStyle = (group: GroupTableItem) => { + if (pinnedGroup && pinnedGroup.id === group.id) { + return { + backgroundColor: primaryBackgroundColor, + }; + } + + if (selectedGroup && selectedGroup.id === group.id) { + return { + backgroundColor: euiTheme.euiColorLightestShade, + }; + } + + return { + backgroundColor: euiTheme.euiColorEmptyShade, + }; + }; + return ( = ({ rowProps={(group) => { return { 'data-test-subj': `aiopsSpikeAnalysisGroupsTableRow row-${group.id}`, - onMouseEnter: () => { - if (onSelectedGroup) { - onSelectedGroup(group); + onClick: () => { + if (group.id === pinnedGroup?.id) { + setPinnedGroup(null); + } else { + setPinnedGroup(group); } }, + onMouseEnter: () => { + setSelectedGroup(group); + }, onMouseLeave: () => { - if (onSelectedGroup) { - onSelectedGroup(null); - } + setSelectedGroup(null); }, + style: getRowStyle(group), }; }} /> diff --git a/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_row_provider.tsx b/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_row_provider.tsx new file mode 100644 index 0000000000000..88b6e508d2f4c --- /dev/null +++ b/x-pack/plugins/aiops/public/components/spike_analysis_table/spike_analysis_table_row_provider.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { + createContext, + useContext, + useMemo, + useState, + type FC, + type Dispatch, + type SetStateAction, +} from 'react'; + +import type { ChangePoint } from '@kbn/ml-agg-utils'; + +import type { GroupTableItem } from './spike_analysis_table_groups'; + +type ChangePointOrNull = ChangePoint | null; +type GroupOrNull = GroupTableItem | null; + +interface SpikeAnalysisTableRow { + pinnedChangePoint: ChangePointOrNull; + setPinnedChangePoint: Dispatch>; + pinnedGroup: GroupOrNull; + setPinnedGroup: Dispatch>; + selectedChangePoint: ChangePointOrNull; + setSelectedChangePoint: Dispatch>; + selectedGroup: GroupOrNull; + setSelectedGroup: Dispatch>; + currentSelectedChangePoint?: ChangePoint; + currentSelectedGroup?: GroupTableItem; + clearAllRowState: () => void; +} + +export const spikeAnalysisTableRowContext = createContext( + undefined +); + +export const SpikeAnalysisTableRowStateProvider: FC = ({ children }) => { + // State that will be shared with all components + const [pinnedChangePoint, setPinnedChangePoint] = useState(null); + const [pinnedGroup, setPinnedGroup] = useState(null); + const [selectedChangePoint, setSelectedChangePoint] = useState(null); + const [selectedGroup, setSelectedGroup] = useState(null); + + // If a row is pinned, still overrule with a potentially hovered row. + const currentSelectedChangePoint = useMemo(() => { + if (selectedChangePoint) { + return selectedChangePoint; + } else if (pinnedChangePoint) { + return pinnedChangePoint; + } + }, [pinnedChangePoint, selectedChangePoint]); + + // If a group is pinned, still overrule with a potentially hovered group. + const currentSelectedGroup = useMemo(() => { + if (selectedGroup) { + return selectedGroup; + } else if (pinnedGroup) { + return pinnedGroup; + } + }, [selectedGroup, pinnedGroup]); + + const contextValue: SpikeAnalysisTableRow = useMemo( + () => ({ + pinnedChangePoint, + setPinnedChangePoint, + pinnedGroup, + setPinnedGroup, + selectedChangePoint, + setSelectedChangePoint, + selectedGroup, + setSelectedGroup, + currentSelectedChangePoint, + currentSelectedGroup, + clearAllRowState: () => { + setPinnedChangePoint(null); + setPinnedGroup(null); + setSelectedChangePoint(null); + setSelectedGroup(null); + }, + }), + [ + pinnedChangePoint, + setPinnedChangePoint, + pinnedGroup, + setPinnedGroup, + selectedChangePoint, + setSelectedChangePoint, + selectedGroup, + setSelectedGroup, + currentSelectedChangePoint, + currentSelectedGroup, + ] + ); + + return ( + // Provider managing the state + + {children} + + ); +}; + +export const useSpikeAnalysisTableRowContext = () => { + const spikeAnalysisTableRow = useContext(spikeAnalysisTableRowContext); + + // If `undefined`, throw an error. + if (spikeAnalysisTableRow === undefined) { + throw new Error('useSpikeAnalysisTableRowContext was used outside of its Provider'); + } + + return spikeAnalysisTableRow; +}; diff --git a/x-pack/plugins/aiops/public/hooks/use_data.ts b/x-pack/plugins/aiops/public/hooks/use_data.ts index 05736fe00e4fc..9d8f889dd8476 100644 --- a/x-pack/plugins/aiops/public/hooks/use_data.ts +++ b/x-pack/plugins/aiops/public/hooks/use_data.ts @@ -40,8 +40,8 @@ export const useData = ( aiopsListState: AiOpsIndexBasedAppState, onUpdate: (params: Dictionary) => void, selectedChangePoint?: ChangePoint, - barTarget: number = DEFAULT_BAR_TARGET, - selectedGroup?: GroupTableItem | null + selectedGroup?: GroupTableItem | null, + barTarget: number = DEFAULT_BAR_TARGET ) => { const { uiSettings, @@ -49,6 +49,7 @@ export const useData = ( query: { filterManager }, }, } = useAiopsAppContext(); + const [lastRefresh, setLastRefresh] = useState(0); const [fieldStatsRequest, setFieldStatsRequest] = useState< DocumentStatsSearchStrategyParams | undefined diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index eed17e563860b..ffe17b91b8aeb 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -770,25 +770,10 @@ This factory returns an instance of `Alert`. The `Alert` class has the following |Method|Description| |---|---| |getState()|Get the current state of the alert.| -|scheduleActions(actionGroup, context)|Call this to schedule the execution of actions. The actionGroup is a string `id` that relates to the group of alert `actions` to execute and the context will be used for templating purposes. `scheduleActions` or `scheduleActionsWithSubGroup` should only be called once per alert.| -|scheduleActionsWithSubGroup(actionGroup, subgroup, context)|Call this to schedule the execution of actions within a subgroup. The actionGroup is a string `id` that relates to the group of alert `actions` to execute, the `subgroup` is a dynamic string that denotes a subgroup within the actionGroup and the context will be used for templating purposes. `scheduleActions` or `scheduleActionsWithSubGroup` should only be called once per alert.| -|replaceState(state)|Used to replace the current state of the alert. This doesn't work like React, the entire state must be provided. Use this feature as you see fit. The state that is set will persist between rule executions whenever you re-create an alert with the same id. The alert state will be erased when `scheduleActions` or `scheduleActionsWithSubGroup` aren't called during an execution.| +|scheduleActions(actionGroup, context)|Call this to schedule the execution of actions. The actionGroup is a string `id` that relates to the group of alert `actions` to execute and the context will be used for templating purposes. `scheduleActions` should only be called once per alert.| +|replaceState(state)|Used to replace the current state of the alert. This doesn't work like React, the entire state must be provided. Use this feature as you see fit. The state that is set will persist between rule executions whenever you re-create an alert with the same id. The alert state will be erased when `scheduleActions`isn't called during an execution.| |setContext(context)|Call this to set the context for this alert that is used for templating purposes. -### When should I use `scheduleActions` and `scheduleActionsWithSubGroup`? -The `scheduleActions` or `scheduleActionsWithSubGroup` methods are both used to achieve the same thing: schedule actions to be run under a specific action group. -It's important to note that when actions are scheduled for an alert, we check whether the alert was already active in this action group after the previous execution. If it was, then we might throttle the actions (adhering to the user's configuration), as we don't consider this a change in the alert. - -What happens though, if the alert _has_ changed, but they just happen to be in the same action group after this change? This is where subgroups come in. By specifying a subgroup (using the `scheduleActionsWithSubGroup` method), the alert becomes active within the action group, but it will also keep track of the subgroup. -If the subgroup changes, then the framework will treat the alert as if it had been placed in a new action group. It is important to note that we only use the subgroup to denote a change if both the current execution and the previous one specified a subgroup. - -You might wonder, why bother using a subgroup if you can just add a new action group? -Action Groups are static, and have to be define when the rule type is defined. -Action Subgroups are dynamic, and can be defined on the fly. - -This approach enables users to specify actions under specific action groups, but they can't specify actions that are specific to subgroups. -As subgroups fall under action groups, we will schedule the actions specified for the action group, but the subgroup allows the RuleType implementer to reuse the same action group for multiple different active subgroups. - ### When should I use `setContext`? `setContext` is intended to be used for setting context for recovered alerts. While rule type executors make the determination as to which alerts are active for an execution, the Alerting Framework automatically determines which alerts are recovered for an execution. `setContext` empowers rule type executors to provide additional contextual information for these recovered alerts that will be templated into actions. @@ -798,7 +783,7 @@ There needs to be a way to map rule context into action parameters. For this, we When an alert executes, the first argument is the `group` of actions to execute and the second is the context the rule exposes to templates. We iterate through each action parameter attributes recursively and render templates if they are a string. Templates have access to the following "variables": -- `context` - provided by context argument of `.scheduleActions(...)`, `.scheduleActionsWithSubGroup(...)` and `setContext(...)` on an alert. +- `context` - provided by context argument of `.scheduleActions(...)` and `setContext(...)` on an alert. - `state` - the alert's `state` provided by the most recent `replaceState` call on an alert. - `alertId` - the id of the rule - `alertInstanceId` - the alert id diff --git a/x-pack/plugins/alerting/common/alert_summary.ts b/x-pack/plugins/alerting/common/alert_summary.ts index b04ce59eed1bd..fc35e3403fe92 100644 --- a/x-pack/plugins/alerting/common/alert_summary.ts +++ b/x-pack/plugins/alerting/common/alert_summary.ts @@ -35,6 +35,5 @@ export interface AlertStatus { status: AlertStatusValues; muted: boolean; actionGroupId?: string; - actionSubgroup?: string; activeStartDate?: string; } diff --git a/x-pack/plugins/alerting/common/execution_log_types.ts b/x-pack/plugins/alerting/common/execution_log_types.ts index 1938d8be4acd3..b08a0bf76d69e 100644 --- a/x-pack/plugins/alerting/common/execution_log_types.ts +++ b/x-pack/plugins/alerting/common/execution_log_types.ts @@ -26,6 +26,17 @@ export const actionErrorLogSortableColumns = [ 'event.action', ]; +export const EMPTY_EXECUTION_KPI_RESULT = { + success: 0, + unknown: 0, + failure: 0, + activeAlerts: 0, + newAlerts: 0, + recoveredAlerts: 0, + erroredActions: 0, + triggeredActions: 0, +}; + export type ExecutionLogSortFields = typeof executionLogSortableColumns[number]; export type ActionErrorLogSortFields = typeof actionErrorLogSortableColumns[number]; @@ -68,3 +79,5 @@ export interface IExecutionLogResult { total: number; data: IExecutionLog[]; } + +export type IExecutionKPIResult = typeof EMPTY_EXECUTION_KPI_RESULT; diff --git a/x-pack/plugins/alerting/server/alert/alert.test.ts b/x-pack/plugins/alerting/server/alert/alert.test.ts index eae1b18164b0f..d9e05e55a67fd 100644 --- a/x-pack/plugins/alerting/server/alert/alert.test.ts +++ b/x-pack/plugins/alerting/server/alert/alert.test.ts @@ -81,10 +81,10 @@ describe('isThrottled', () => { }); }); -describe('scheduledActionGroupOrSubgroupHasChanged()', () => { +describe('scheduledActionGroupHasChanged()', () => { test('should be false if no last scheduled and nothing scheduled', () => { const alert = new Alert('1'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(false); + expect(alert.scheduledActionGroupHasChanged()).toEqual(false); }); test('should be false if group does not change', () => { @@ -97,54 +97,13 @@ describe('scheduledActionGroupOrSubgroupHasChanged()', () => { }, }); alert.scheduleActions('default'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(false); - }); - - test('should be false if group and subgroup does not change', () => { - const alert = new Alert('1', { - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'subgroup', - }, - }, - }); - alert.scheduleActionsWithSubGroup('default', 'subgroup'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(false); - }); - - test('should be false if group does not change and subgroup goes from undefined to defined', () => { - const alert = new Alert('1', { - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - }, - }, - }); - alert.scheduleActionsWithSubGroup('default', 'subgroup'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(false); - }); - - test('should be false if group does not change and subgroup goes from defined to undefined', () => { - const alert = new Alert('1', { - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'subgroup', - }, - }, - }); - alert.scheduleActions('default'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(false); + expect(alert.scheduledActionGroupHasChanged()).toEqual(false); }); test('should be true if no last scheduled and has scheduled action', () => { const alert = new Alert('1'); alert.scheduleActions('default'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(true); + expect(alert.scheduledActionGroupHasChanged()).toEqual(true); }); test('should be true if group does change', () => { @@ -157,35 +116,7 @@ describe('scheduledActionGroupOrSubgroupHasChanged()', () => { }, }); alert.scheduleActions('penguin'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(true); - }); - - test('should be true if group does change and subgroup does change', () => { - const alert = new Alert('1', { - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'subgroup', - }, - }, - }); - alert.scheduleActionsWithSubGroup('penguin', 'fish'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(true); - }); - - test('should be true if group does not change and subgroup does change', () => { - const alert = new Alert('1', { - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'subgroup', - }, - }, - }); - alert.scheduleActionsWithSubGroup('default', 'fish'); - expect(alert.scheduledActionGroupOrSubgroupHasChanged()).toEqual(true); + expect(alert.scheduledActionGroupHasChanged()).toEqual(true); }); }); @@ -296,137 +227,6 @@ describe('scheduleActions()', () => { }); }); -describe('scheduleActionsWithSubGroup()', () => { - test('makes hasScheduledActions() return true', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - }, - }, - }); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.hasScheduledActions()).toEqual(true); - }); - - test('makes isThrottled() return true when throttled and subgroup is the same', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'subgroup', - }, - }, - }); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.isThrottled('1m')).toEqual(true); - }); - - test('makes isThrottled() return true when throttled and last schedule had no subgroup', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - }, - }, - }); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.isThrottled('1m')).toEqual(true); - }); - - test('makes isThrottled() return false when throttled and subgroup is the different', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - subgroup: 'prev-subgroup', - }, - }, - }); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.isThrottled('1m')).toEqual(false); - }); - - test('make isThrottled() return false when throttled expired', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: { - lastScheduledActions: { - date: new Date(), - group: 'default', - }, - }, - }); - clock.tick(120000); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.isThrottled('1m')).toEqual(false); - }); - - test('makes getScheduledActionOptions() return given options', () => { - const alert = new Alert('1', { - state: { foo: true }, - meta: {}, - }); - alert - .replaceState({ otherField: true }) - .scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(alert.getScheduledActionOptions()).toEqual({ - actionGroup: 'default', - subgroup: 'subgroup', - context: { field: true }, - state: { otherField: true }, - }); - }); - - test('cannot schdule for execution twice', () => { - const alert = new Alert('1'); - alert.scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(() => - alert.scheduleActionsWithSubGroup('default', 'subgroup', { field: false }) - ).toThrowErrorMatchingInlineSnapshot( - `"Alert instance execution has already been scheduled, cannot schedule twice"` - ); - }); - - test('cannot schdule for execution twice with different subgroups', () => { - const alert = new Alert('1'); - alert.scheduleActionsWithSubGroup('default', 'subgroup', { field: true }); - expect(() => - alert.scheduleActionsWithSubGroup('default', 'subgroup', { field: false }) - ).toThrowErrorMatchingInlineSnapshot( - `"Alert instance execution has already been scheduled, cannot schedule twice"` - ); - }); - - test('cannot schdule for execution twice whether there are subgroups', () => { - const alert = new Alert('1'); - alert.scheduleActions('default', { field: true }); - expect(() => - alert.scheduleActionsWithSubGroup('default', 'subgroup', { field: false }) - ).toThrowErrorMatchingInlineSnapshot( - `"Alert instance execution has already been scheduled, cannot schedule twice"` - ); - }); -}); - describe('replaceState()', () => { test('replaces previous state', () => { const alert = new Alert('1', { diff --git a/x-pack/plugins/alerting/server/alert/alert.ts b/x-pack/plugins/alerting/server/alert/alert.ts index bf29cacf556c1..e24b15de41db4 100644 --- a/x-pack/plugins/alerting/server/alert/alert.ts +++ b/x-pack/plugins/alerting/server/alert/alert.ts @@ -23,7 +23,6 @@ interface ScheduledExecutionOptions< ActionGroupIds extends string = DefaultActionGroupId > { actionGroup: ActionGroupIds; - subgroup?: string; context: Context; state: State; } @@ -34,13 +33,7 @@ export type PublicAlert< ActionGroupIds extends string = DefaultActionGroupId > = Pick< Alert, - | 'getState' - | 'replaceState' - | 'scheduleActions' - | 'scheduleActionsWithSubGroup' - | 'setContext' - | 'getContext' - | 'hasContext' + 'getState' | 'replaceState' | 'scheduleActions' | 'setContext' | 'getContext' | 'hasContext' >; export class Alert< @@ -80,10 +73,6 @@ export class Alert< this.meta.lastScheduledActions, this.scheduledExecutionOptions ) && - this.scheduledActionSubgroupIsUnchanged( - this.meta.lastScheduledActions, - this.scheduledExecutionOptions - ) && this.meta.lastScheduledActions.date.getTime() + throttleMills > Date.now() ) { return true; @@ -91,7 +80,7 @@ export class Alert< return false; } - scheduledActionGroupOrSubgroupHasChanged(): boolean { + scheduledActionGroupHasChanged(): boolean { if (!this.meta.lastScheduledActions && this.scheduledExecutionOptions) { // it is considered a change when there are no previous scheduled actions // and new scheduled actions @@ -100,18 +89,11 @@ export class Alert< if (this.meta.lastScheduledActions && this.scheduledExecutionOptions) { // compare previous and new scheduled actions if both exist - return ( - !this.scheduledActionGroupIsUnchanged( - this.meta.lastScheduledActions, - this.scheduledExecutionOptions - ) || - !this.scheduledActionSubgroupIsUnchanged( - this.meta.lastScheduledActions, - this.scheduledExecutionOptions - ) + return !this.scheduledActionGroupIsUnchanged( + this.meta.lastScheduledActions, + this.scheduledExecutionOptions ); } - // no previous and no new scheduled actions return false; } @@ -123,15 +105,6 @@ export class Alert< return lastScheduledActions.group === scheduledExecutionOptions.actionGroup; } - private scheduledActionSubgroupIsUnchanged( - lastScheduledActions: NonNullable, - scheduledExecutionOptions: ScheduledExecutionOptions - ) { - return lastScheduledActions.subgroup && scheduledExecutionOptions.subgroup - ? lastScheduledActions.subgroup === scheduledExecutionOptions.subgroup - : true; - } - getLastScheduledActions() { return this.meta.lastScheduledActions; } @@ -168,22 +141,6 @@ export class Alert< return this; } - scheduleActionsWithSubGroup( - actionGroup: ActionGroupIds, - subgroup: string, - context: Context = {} as Context - ) { - this.ensureHasNoScheduledActions(); - this.setContext(context); - this.scheduledExecutionOptions = { - actionGroup, - subgroup, - context, - state: this.state, - }; - return this; - } - setContext(context: Context) { this.context = context; return this; @@ -200,8 +157,8 @@ export class Alert< return this; } - updateLastScheduledActions(group: ActionGroupIds, subgroup?: string) { - this.meta.lastScheduledActions = { group, subgroup, date: new Date() }; + updateLastScheduledActions(group: ActionGroupIds) { + this.meta.lastScheduledActions = { group, date: new Date() }; } /** diff --git a/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts b/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts index 0c501f25a857d..7138aabe9d263 100644 --- a/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts +++ b/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts @@ -35,6 +35,7 @@ export enum ReadOperations { Find = 'find', GetAuthorizedAlertsIndices = 'getAuthorizedAlertsIndices', RunSoon = 'runSoon', + GetRuleExecutionKPI = 'getRuleExecutionKPI', } export enum WriteOperations { diff --git a/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.test.ts b/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.test.ts index d2040f8e63f3a..56a862f2ad6ca 100644 --- a/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.test.ts +++ b/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.test.ts @@ -121,14 +121,12 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": true, "status": "OK", }, "alert-2": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": true, "status": "OK", @@ -233,7 +231,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "OK", @@ -274,7 +271,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "OK", @@ -314,7 +310,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "OK", @@ -355,7 +350,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": "action group A", - "actionSubgroup": undefined, "activeStartDate": "2020-06-18T00:00:00.000Z", "muted": false, "status": "Active", @@ -396,7 +390,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": "2020-06-18T00:00:00.000Z", "muted": false, "status": "Active", @@ -437,7 +430,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": "action group B", - "actionSubgroup": undefined, "activeStartDate": "2020-06-18T00:00:00.000Z", "muted": false, "status": "Active", @@ -476,7 +468,6 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": "action group A", - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "Active", @@ -519,14 +510,12 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": "action group A", - "actionSubgroup": undefined, "activeStartDate": "2020-06-18T00:00:00.000Z", "muted": true, "status": "Active", }, "alert-2": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": true, "status": "OK", @@ -576,14 +565,12 @@ describe('alertSummaryFromEventLog', () => { "alerts": Object { "alert-1": Object { "actionGroupId": "action group B", - "actionSubgroup": undefined, "activeStartDate": "2020-06-18T00:00:00.000Z", "muted": false, "status": "Active", }, "alert-2": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "OK", diff --git a/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.ts b/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.ts index 54ac23bf94f2a..d8e5f4dea9b41 100644 --- a/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.ts +++ b/x-pack/plugins/alerting/server/lib/alert_summary_from_event_log.ts @@ -87,14 +87,12 @@ export function alertSummaryFromEventLog(params: AlertSummaryFromEventLogParams) case EVENT_LOG_ACTIONS.activeInstance: status.status = 'Active'; status.actionGroupId = event?.kibana?.alerting?.action_group_id; - status.actionSubgroup = event?.kibana?.alerting?.action_subgroup; break; case LEGACY_EVENT_LOG_ACTIONS.resolvedInstance: case EVENT_LOG_ACTIONS.recoveredInstance: status.status = 'OK'; status.activeStartDate = undefined; status.actionGroupId = undefined; - status.actionSubgroup = undefined; } } @@ -153,7 +151,6 @@ function getAlertStatus(alerts: Map, alertId: string): Aler status: 'OK', muted: false, actionGroupId: undefined, - actionSubgroup: undefined, activeStartDate: undefined, }; alerts.set(alertId, status); diff --git a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.test.ts b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.test.ts index 91904901adcfd..8fe081864b118 100644 --- a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.test.ts +++ b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.test.ts @@ -59,9 +59,8 @@ const contextWithName = { ...contextWithScheduleDelay, ruleName: 'my-super-cool- const alert = { action: EVENT_LOG_ACTIONS.activeInstance, id: 'aaabbb', - message: `.test-rule-type:123: 'my rule' active alert: 'aaabbb' in actionGroup: 'aGroup'; actionSubGroup: 'bSubGroup'`, + message: `.test-rule-type:123: 'my rule' active alert: 'aaabbb' in actionGroup: 'aGroup';`, group: 'aGroup', - subgroup: 'bSubgroup', state: { start: '2020-01-01T02:00:00.000Z', end: '2020-01-01T03:00:00.000Z', @@ -74,7 +73,6 @@ const action = { typeId: '.email', alertId: '123', alertGroup: 'aGroup', - alertSubgroup: 'bSubgroup', }; describe('AlertingEventLogger', () => { @@ -1006,14 +1004,13 @@ describe('createAlertRecord', () => { expect(record.event?.end).toEqual(alert.state.end); expect(record.event?.duration).toEqual(alert.state.duration); expect(record.message).toEqual( - `.test-rule-type:123: 'my rule' active alert: 'aaabbb' in actionGroup: 'aGroup'; actionSubGroup: 'bSubGroup'` + `.test-rule-type:123: 'my rule' active alert: 'aaabbb' in actionGroup: 'aGroup';` ); expect(record.kibana?.alert?.rule?.rule_type_id).toEqual(contextWithName.ruleType.id); expect(record.kibana?.alert?.rule?.consumer).toEqual(contextWithName.consumer); expect(record.kibana?.alert?.rule?.execution?.uuid).toEqual(contextWithName.executionId); expect(record.kibana?.alerting?.instance_id).toEqual(alert.id); expect(record.kibana?.alerting?.action_group_id).toEqual(alert.group); - expect(record.kibana?.alerting?.action_subgroup).toEqual(alert.subgroup); expect(record.kibana?.saved_objects).toEqual([ { id: contextWithName.ruleId, @@ -1059,14 +1056,13 @@ describe('createActionExecuteRecord', () => { expect(record.event?.kind).toEqual('alert'); expect(record.event?.category).toEqual([contextWithName.ruleType.producer]); expect(record.message).toEqual( - `alert: test:123: 'my-super-cool-rule' instanceId: '123' scheduled actionGroup(subgroup): 'aGroup(bSubgroup)' action: .email:abc` + `alert: test:123: 'my-super-cool-rule' instanceId: '123' scheduled actionGroup: 'aGroup' action: .email:abc` ); expect(record.kibana?.alert?.rule?.rule_type_id).toEqual(contextWithName.ruleType.id); expect(record.kibana?.alert?.rule?.consumer).toEqual(contextWithName.consumer); expect(record.kibana?.alert?.rule?.execution?.uuid).toEqual(contextWithName.executionId); expect(record.kibana?.alerting?.instance_id).toEqual(action.alertId); expect(record.kibana?.alerting?.action_group_id).toEqual(action.alertGroup); - expect(record.kibana?.alerting?.action_subgroup).toEqual(action.alertSubgroup); expect(record.kibana?.saved_objects).toEqual([ { id: contextWithName.ruleId, diff --git a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts index 96be872d81b8c..18e4044172eb4 100644 --- a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts +++ b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts @@ -47,7 +47,6 @@ interface AlertOpts { id: string; message: string; group?: string; - subgroup?: string; state?: AlertInstanceState; } @@ -56,7 +55,6 @@ interface ActionOpts { typeId: string; alertId: string; alertGroup?: string; - alertSubgroup?: string; } export class AlertingEventLogger { @@ -232,7 +230,6 @@ export function createAlertRecord(context: RuleContextOpts, alert: AlertOpts) { state: alert.state, instanceId: alert.id, group: alert.group, - subgroup: alert.subgroup, message: alert.message, savedObjects: [ { @@ -257,14 +254,7 @@ export function createActionExecuteRecord(context: RuleContextOpts, action: Acti action: EVENT_LOG_ACTIONS.executeAction, instanceId: action.alertId, group: action.alertGroup, - subgroup: action.alertSubgroup, - message: `alert: ${context.ruleType.id}:${context.ruleId}: '${context.ruleName}' instanceId: '${ - action.alertId - }' scheduled ${ - action.alertSubgroup - ? `actionGroup(subgroup): '${action.alertGroup}(${action.alertSubgroup})'` - : `actionGroup: '${action.alertGroup}'` - } action: ${action.typeId}:${action.id}`, + message: `alert: ${context.ruleType.id}:${context.ruleId}: '${context.ruleName}' instanceId: '${action.alertId}' scheduled actionGroup: '${action.alertGroup}' action: ${action.typeId}:${action.id}`, savedObjects: [ { id: context.ruleId, diff --git a/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.test.ts b/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.test.ts index ba16b7c553e86..8f73ba3a56860 100644 --- a/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.test.ts +++ b/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.test.ts @@ -99,7 +99,6 @@ describe('createAlertEventLogRecordObject', () => { group: 'group 1', message: 'message text here', namespace: 'default', - subgroup: 'subgroup value', state: { start: '1970-01-01T00:00:00.000Z', end: '1970-01-01T00:05:00.000Z', @@ -136,7 +135,6 @@ describe('createAlertEventLogRecordObject', () => { }, alerting: { action_group_id: 'group 1', - action_subgroup: 'subgroup value', instance_id: 'test1', }, saved_objects: [ @@ -174,7 +172,6 @@ describe('createAlertEventLogRecordObject', () => { group: 'group 1', message: 'action execution start', namespace: 'default', - subgroup: 'subgroup value', state: { start: '1970-01-01T00:00:00.000Z', end: '1970-01-01T00:05:00.000Z', @@ -216,7 +213,6 @@ describe('createAlertEventLogRecordObject', () => { }, alerting: { action_group_id: 'group 1', - action_subgroup: 'subgroup value', instance_id: 'test1', }, saved_objects: [ diff --git a/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.ts b/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.ts index cd7eda500d15b..a0f229c0b46d9 100644 --- a/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.ts +++ b/x-pack/plugins/alerting/server/lib/create_alert_event_log_record_object.ts @@ -23,7 +23,6 @@ interface CreateAlertEventLogRecordParams { message?: string; state?: AlertInstanceState; group?: string; - subgroup?: string; namespace?: string; timestamp?: string; task?: { @@ -48,18 +47,16 @@ export function createAlertEventLogRecordObject(params: CreateAlertEventLogRecor task, ruleId, group, - subgroup, namespace, consumer, spaceId, } = params; const alerting = - params.instanceId || group || subgroup + params.instanceId || group ? { alerting: { ...(params.instanceId ? { instance_id: params.instanceId } : {}), ...(group ? { action_group_id: group } : {}), - ...(subgroup ? { action_subgroup: subgroup } : {}), }, } : undefined; diff --git a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.test.ts b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.test.ts index e48483785490a..eb46ae67e2ef1 100644 --- a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.test.ts +++ b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.test.ts @@ -13,6 +13,8 @@ import { formatSortForBucketSort, formatSortForTermSort, ExecutionUuidAggResult, + getExecutionKPIAggregation, + formatExecutionKPIResult, } from './get_execution_log_aggregation'; describe('formatSortForBucketSort', () => { @@ -1689,3 +1691,584 @@ describe('formatExecutionLogResult', () => { }); }); }); + +describe('getExecutionKPIAggregation', () => { + test('should correctly generate aggregation', () => { + expect(getExecutionKPIAggregation()).toEqual({ + excludeExecuteStart: { + filter: { + bool: { + must_not: [ + { + term: { + 'event.action': 'execute-start', + }, + }, + ], + }, + }, + aggs: { + executionUuid: { + terms: { + field: 'kibana.alert.rule.execution.uuid', + size: 1000, + }, + aggs: { + executionUuidSorted: { + bucket_sort: { + from: 0, + size: 1000, + gap_policy: 'insert_zeros', + }, + }, + actionExecution: { + filter: { + bool: { + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'actions', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + actionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + ruleExecution: { + filter: { + bool: { + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'alerting', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + numTriggeredActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_triggered_actions', + missing: 0, + }, + }, + numGeneratedActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_generated_actions', + missing: 0, + }, + }, + numActiveAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.active', + missing: 0, + }, + }, + numRecoveredAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.recovered', + missing: 0, + }, + }, + numNewAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.new', + missing: 0, + }, + }, + ruleExecutionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + minExecutionUuidBucket: { + bucket_selector: { + buckets_path: { + count: 'ruleExecution._count', + }, + script: { + source: 'params.count > 0', + }, + }, + }, + }, + }, + }, + }, + }); + }); + + test('should correctly generate aggregation with a defined filter in the form of a string', () => { + expect(getExecutionKPIAggregation('test:test')).toEqual({ + excludeExecuteStart: { + filter: { + bool: { + must_not: [ + { + term: { + 'event.action': 'execute-start', + }, + }, + ], + }, + }, + aggs: { + executionUuid: { + terms: { + field: 'kibana.alert.rule.execution.uuid', + size: 1000, + }, + aggs: { + executionUuidSorted: { + bucket_sort: { + from: 0, + size: 1000, + gap_policy: 'insert_zeros', + }, + }, + actionExecution: { + filter: { + bool: { + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'actions', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + actionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + ruleExecution: { + filter: { + bool: { + filter: { + bool: { + should: [ + { + match: { + test: 'test', + }, + }, + ], + minimum_should_match: 1, + }, + }, + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'alerting', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + numTriggeredActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_triggered_actions', + missing: 0, + }, + }, + numGeneratedActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_generated_actions', + missing: 0, + }, + }, + numActiveAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.active', + missing: 0, + }, + }, + numRecoveredAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.recovered', + missing: 0, + }, + }, + numNewAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.new', + missing: 0, + }, + }, + ruleExecutionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + minExecutionUuidBucket: { + bucket_selector: { + buckets_path: { + count: 'ruleExecution._count', + }, + script: { + source: 'params.count > 0', + }, + }, + }, + }, + }, + }, + }, + }); + }); + + test('should correctly generate aggregation with a defined filter in the form of a KueryNode', () => { + expect(getExecutionKPIAggregation(fromKueryExpression('test:test'))).toEqual({ + excludeExecuteStart: { + filter: { + bool: { + must_not: [ + { + term: { + 'event.action': 'execute-start', + }, + }, + ], + }, + }, + aggs: { + executionUuid: { + terms: { + field: 'kibana.alert.rule.execution.uuid', + size: 1000, + }, + aggs: { + executionUuidSorted: { + bucket_sort: { + from: 0, + size: 1000, + gap_policy: 'insert_zeros', + }, + }, + actionExecution: { + filter: { + bool: { + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'actions', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + actionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + ruleExecution: { + filter: { + bool: { + filter: { + bool: { + should: [ + { + match: { + test: 'test', + }, + }, + ], + minimum_should_match: 1, + }, + }, + must: [ + { + bool: { + must: [ + { + match: { + 'event.action': 'execute', + }, + }, + { + match: { + 'event.provider': 'alerting', + }, + }, + ], + }, + }, + ], + }, + }, + aggs: { + numTriggeredActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_triggered_actions', + missing: 0, + }, + }, + numGeneratedActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_generated_actions', + missing: 0, + }, + }, + numActiveAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.active', + missing: 0, + }, + }, + numRecoveredAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.recovered', + missing: 0, + }, + }, + numNewAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.new', + missing: 0, + }, + }, + ruleExecutionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + minExecutionUuidBucket: { + bucket_selector: { + buckets_path: { + count: 'ruleExecution._count', + }, + script: { + source: 'params.count > 0', + }, + }, + }, + }, + }, + }, + }, + }); + }); +}); + +describe('formatExecutionKPIAggBuckets', () => { + test('should return empty results if aggregations are undefined', () => { + expect( + formatExecutionKPIResult({ + aggregations: undefined, + }) + ).toEqual({ + activeAlerts: 0, + erroredActions: 0, + failure: 0, + newAlerts: 0, + recoveredAlerts: 0, + success: 0, + triggeredActions: 0, + unknown: 0, + }); + }); + + test('should format results correctly', () => { + const results = { + aggregations: { + excludeExecuteStart: { + meta: {}, + doc_count: 875, + executionUuid: { + meta: {}, + doc_count_error_upper_bound: 0, + sum_other_doc_count: 0, + buckets: [ + { + ruleExecution: { + meta: {}, + doc_count: 3, + numTriggeredActions: { + value: 5.0, + }, + numGeneratedActions: { + value: 5.0, + }, + numActiveAlerts: { + value: 5.0, + }, + numNewAlerts: { + value: 5.0, + }, + numRecoveredAlerts: { + value: 0.0, + }, + ruleExecutionOutcomes: { + doc_count_error_upper_bound: 0, + sum_other_doc_count: 0, + buckets: [ + { + key: 'success', + doc_count: 3, + }, + ], + }, + }, + actionExecution: { + meta: {}, + doc_count: 5, + actionOutcomes: { + doc_count_error_upper_bound: 0, + sum_other_doc_count: 0, + buckets: [ + { + key: 'success', + doc_count: 5, + }, + ], + }, + }, + }, + { + ruleExecution: { + meta: {}, + doc_count: 2, + numTriggeredActions: { + value: 5.0, + }, + numGeneratedActions: { + value: 5.0, + }, + numActiveAlerts: { + value: 5.0, + }, + numNewAlerts: { + value: 5.0, + }, + numRecoveredAlerts: { + value: 0.0, + }, + ruleExecutionOutcomes: { + doc_count_error_upper_bound: 0, + sum_other_doc_count: 0, + buckets: [ + { + key: 'success', + doc_count: 2, + }, + ], + }, + }, + actionExecution: { + meta: {}, + doc_count: 3, + actionOutcomes: { + doc_count_error_upper_bound: 0, + sum_other_doc_count: 0, + buckets: [ + { + key: 'failure', + doc_count: 3, + }, + ], + }, + }, + }, + ], + }, + }, + }, + }; + + expect(formatExecutionKPIResult(results)).toEqual({ + success: 5, + unknown: 0, + failure: 0, + activeAlerts: 10, + newAlerts: 10, + recoveredAlerts: 0, + erroredActions: 3, + triggeredActions: 10, + }); + }); +}); diff --git a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts index 0854488d5f29e..fedc827a46c73 100644 --- a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts @@ -12,7 +12,7 @@ import { flatMap, get } from 'lodash'; import { AggregateEventsBySavedObjectResult } from '@kbn/event-log-plugin/server'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { parseDuration } from '.'; -import { IExecutionLog, IExecutionLogResult } from '../../common'; +import { IExecutionLog, IExecutionLogResult, EMPTY_EXECUTION_KPI_RESULT } from '../../common'; const DEFAULT_MAX_BUCKETS_LIMIT = 1000; // do not retrieve more than this number of executions @@ -51,6 +51,21 @@ interface IActionExecution buckets: Array<{ key: string; doc_count: number }>; } +interface IExecutionUuidKpiAggBucket extends estypes.AggregationsStringTermsBucketKeys { + actionExecution: { + doc_count: number; + actionOutcomes: IActionExecution; + }; + ruleExecution: { + doc_count: number; + numTriggeredActions: estypes.AggregationsSumAggregate; + numGeneratedActions: estypes.AggregationsSumAggregate; + numActiveAlerts: estypes.AggregationsSumAggregate; + numRecoveredAlerts: estypes.AggregationsSumAggregate; + numNewAlerts: estypes.AggregationsSumAggregate; + ruleExecutionOutcomes: IActionExecution; + }; +} interface IExecutionUuidAggBucket extends estypes.AggregationsStringTermsBucketKeys { timeoutMessage: estypes.AggregationsMultiBucketBase; ruleExecution: { @@ -76,12 +91,22 @@ export interface ExecutionUuidAggResult buckets: TBucket[]; } +export interface ExecutionUuidKPIAggResult + extends estypes.AggregationsAggregateBase { + buckets: TBucket[]; +} + interface ExcludeExecuteStartAggResult extends estypes.AggregationsAggregateBase { executionUuid: ExecutionUuidAggResult; executionUuidCardinality: { executionUuidCardinality: estypes.AggregationsCardinalityAggregate; }; } + +interface ExcludeExecuteStartKpiAggResult extends estypes.AggregationsAggregateBase { + executionUuid: ExecutionUuidKPIAggResult; +} + export interface IExecutionLogAggOptions { filter?: string | KueryNode; page: number; @@ -102,6 +127,115 @@ const ExecutionLogSortFields: Record = { num_new_alerts: 'ruleExecution>numNewAlerts', }; +export const getExecutionKPIAggregation = (filter?: IExecutionLogAggOptions['filter']) => { + const dslFilterQuery: estypes.QueryDslBoolQuery['filter'] = buildDslFilterQuery(filter); + + return { + excludeExecuteStart: { + filter: { + bool: { + must_not: [ + { + term: { + 'event.action': 'execute-start', + }, + }, + ], + }, + }, + aggs: { + executionUuid: { + // Bucket by execution UUID + terms: { + field: EXECUTION_UUID_FIELD, + size: DEFAULT_MAX_BUCKETS_LIMIT, + }, + aggs: { + executionUuidSorted: { + bucket_sort: { + from: 0, + size: 1000, + gap_policy: 'insert_zeros' as estypes.AggregationsGapPolicy, + }, + }, + actionExecution: { + filter: { + bool: { + must: [getProviderAndActionFilter('actions', 'execute')], + }, + }, + aggs: { + actionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + ruleExecution: { + filter: { + bool: { + ...(dslFilterQuery ? { filter: dslFilterQuery } : {}), + must: [getProviderAndActionFilter('alerting', 'execute')], + }, + }, + aggs: { + numTriggeredActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_triggered_actions', + missing: 0, + }, + }, + numGeneratedActions: { + sum: { + field: 'kibana.alert.rule.execution.metrics.number_of_generated_actions', + missing: 0, + }, + }, + numActiveAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.active', + missing: 0, + }, + }, + numRecoveredAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.recovered', + missing: 0, + }, + }, + numNewAlerts: { + sum: { + field: 'kibana.alert.rule.execution.metrics.alert_counts.new', + missing: 0, + }, + }, + ruleExecutionOutcomes: { + terms: { + field: 'event.outcome', + size: 2, + }, + }, + }, + }, + minExecutionUuidBucket: { + bucket_selector: { + buckets_path: { + count: 'ruleExecution._count', + }, + script: { + source: 'params.count > 0', + }, + }, + }, + }, + }, + }, + }, + }; +}; + export function getExecutionLogAggregation({ filter, page, @@ -130,13 +264,7 @@ export function getExecutionLogAggregation({ throw Boom.badRequest(`Invalid perPage field "${perPage}" - must be greater than 0`); } - let dslFilterQuery: estypes.QueryDslBoolQuery['filter']; - try { - const filterKueryNode = typeof filter === 'string' ? fromKueryExpression(filter) : filter; - dslFilterQuery = filter ? toElasticsearchQuery(filterKueryNode) : undefined; - } catch (err) { - throw Boom.badRequest(`Invalid kuery syntax for filter ${filter}`); - } + const dslFilterQuery: estypes.QueryDslBoolQuery['filter'] = buildDslFilterQuery(filter); return { excludeExecuteStart: { @@ -295,6 +423,15 @@ export function getExecutionLogAggregation({ }; } +function buildDslFilterQuery(filter: IExecutionLogAggOptions['filter']) { + try { + const filterKueryNode = typeof filter === 'string' ? fromKueryExpression(filter) : filter; + return filter ? toElasticsearchQuery(filterKueryNode) : undefined; + } catch (err) { + throw Boom.badRequest(`Invalid kuery syntax for filter ${filter}`); + } +} + function getProviderAndActionFilter(provider: string, action: string) { return { bool: { @@ -362,6 +499,52 @@ function formatExecutionLogAggBucket(bucket: IExecutionUuidAggBucket): IExecutio }; } +function formatExecutionKPIAggBuckets(buckets: IExecutionUuidKpiAggBucket[]) { + const objToReturn = { + success: 0, + unknown: 0, + failure: 0, + activeAlerts: 0, + newAlerts: 0, + recoveredAlerts: 0, + erroredActions: 0, + triggeredActions: 0, + }; + + buckets.forEach((bucket) => { + const ruleExecutionOutcomes = bucket?.ruleExecution?.ruleExecutionOutcomes?.buckets ?? []; + const actionExecutionOutcomes = bucket?.actionExecution?.actionOutcomes?.buckets ?? []; + + const ruleExecutionCount = bucket?.ruleExecution?.doc_count ?? 0; + const successRuleExecution = + ruleExecutionOutcomes.find((subBucket) => subBucket?.key === 'success')?.doc_count ?? 0; + const failureRuleExecution = + ruleExecutionOutcomes.find((subBucket) => subBucket?.key === 'failure')?.doc_count ?? 0; + + objToReturn.success += successRuleExecution; + objToReturn.unknown += ruleExecutionCount - (successRuleExecution + failureRuleExecution); + objToReturn.failure += failureRuleExecution; + objToReturn.activeAlerts += bucket?.ruleExecution?.numActiveAlerts.value ?? 0; + objToReturn.newAlerts += bucket?.ruleExecution?.numNewAlerts.value ?? 0; + objToReturn.recoveredAlerts += bucket?.ruleExecution?.numRecoveredAlerts.value ?? 0; + objToReturn.erroredActions += + actionExecutionOutcomes.find((subBucket) => subBucket?.key === 'failure')?.doc_count ?? 0; + objToReturn.triggeredActions += bucket?.ruleExecution?.numTriggeredActions.value ?? 0; + }); + + return objToReturn; +} + +export function formatExecutionKPIResult(results: AggregateEventsBySavedObjectResult) { + const { aggregations } = results; + if (!aggregations || !aggregations.excludeExecuteStart) { + return EMPTY_EXECUTION_KPI_RESULT; + } + const aggs = aggregations.excludeExecuteStart as ExcludeExecuteStartKpiAggResult; + const buckets = aggs.executionUuid.buckets; + return formatExecutionKPIAggBuckets(buckets); +} + export function formatExecutionLogResult( results: AggregateEventsBySavedObjectResult ): IExecutionLogResult { diff --git a/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.test.ts b/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.test.ts new file mode 100644 index 0000000000000..89b21547c892a --- /dev/null +++ b/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { httpServiceMock } from '@kbn/core/server/mocks'; +import { licenseStateMock } from '../lib/license_state.mock'; +import { mockHandlerArguments } from './_mock_handler_arguments'; +import { rulesClientMock } from '../rules_client.mock'; +import { getGlobalExecutionKPIRoute } from './get_global_execution_kpi'; + +const rulesClient = rulesClientMock.create(); +jest.mock('../lib/license_api_access', () => ({ + verifyApiAccess: jest.fn(), +})); + +beforeEach(() => { + jest.resetAllMocks(); +}); + +describe('getGlobalExecutionKPIRoute', () => { + const dateString = new Date().toISOString(); + const mockedExecutionLog = { + success: 3, + unknown: 0, + failure: 0, + activeAlerts: 5, + newAlerts: 5, + recoveredAlerts: 0, + erroredActions: 0, + triggeredActions: 5, + }; + + it('gets global execution KPI', async () => { + const licenseState = licenseStateMock.create(); + const router = httpServiceMock.createRouter(); + + getGlobalExecutionKPIRoute(router, licenseState); + + const [config, handler] = router.get.mock.calls[0]; + + expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/_global_execution_kpi"`); + + rulesClient.getGlobalExecutionKpiWithAuth.mockResolvedValue(mockedExecutionLog); + + const [context, req, res] = mockHandlerArguments( + { rulesClient }, + { + query: { + date_start: dateString, + }, + }, + ['ok'] + ); + + await handler(context, req, res); + + expect(rulesClient.getGlobalExecutionKpiWithAuth).toHaveBeenCalledTimes(1); + expect(rulesClient.getGlobalExecutionKpiWithAuth.mock.calls[0]).toEqual([ + { + dateStart: dateString, + }, + ]); + + expect(res.ok).toHaveBeenCalled(); + }); +}); diff --git a/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.ts b/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.ts new file mode 100644 index 0000000000000..29937cc3d8c98 --- /dev/null +++ b/x-pack/plugins/alerting/server/routes/get_global_execution_kpi.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { IRouter } from '@kbn/core/server'; +import { schema } from '@kbn/config-schema'; +import { AlertingRequestHandlerContext, INTERNAL_BASE_ALERTING_API_PATH } from '../types'; +import { RewriteRequestCase, verifyAccessAndContext } from './lib'; +import { GetGlobalExecutionKPIParams } from '../rules_client'; +import { ILicenseState } from '../lib'; + +const querySchema = schema.object({ + date_start: schema.string(), + date_end: schema.maybe(schema.string()), + filter: schema.maybe(schema.string()), +}); + +const rewriteReq: RewriteRequestCase = ({ + date_start: dateStart, + date_end: dateEnd, + ...rest +}) => ({ + ...rest, + dateStart, + dateEnd, +}); + +export const getGlobalExecutionKPIRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { + router.get( + { + path: `${INTERNAL_BASE_ALERTING_API_PATH}/_global_execution_kpi`, + validate: { + query: querySchema, + }, + }, + router.handleLegacyErrors( + verifyAccessAndContext(licenseState, async function (context, req, res) { + const rulesClient = (await context.alerting).getRulesClient(); + return res.ok({ + body: await rulesClient.getGlobalExecutionKpiWithAuth(rewriteReq(req.query)), + }); + }) + ) + ); +}; diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts new file mode 100644 index 0000000000000..db5033404788c --- /dev/null +++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts @@ -0,0 +1,102 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { httpServiceMock } from '@kbn/core/server/mocks'; +import { licenseStateMock } from '../lib/license_state.mock'; +import { mockHandlerArguments } from './_mock_handler_arguments'; +import { SavedObjectsErrorHelpers } from '@kbn/core/server'; +import { rulesClientMock } from '../rules_client.mock'; +import { getRuleExecutionKPIRoute } from './get_rule_execution_kpi'; + +const rulesClient = rulesClientMock.create(); +jest.mock('../lib/license_api_access', () => ({ + verifyApiAccess: jest.fn(), +})); + +beforeEach(() => { + jest.resetAllMocks(); +}); + +describe('getRuleExecutionKPIRoute', () => { + const dateString = new Date().toISOString(); + const mockedExecutionLog = { + success: 3, + unknown: 0, + failure: 0, + activeAlerts: 5, + newAlerts: 5, + recoveredAlerts: 0, + erroredActions: 0, + triggeredActions: 5, + }; + + it('gets rule execution KPI', async () => { + const licenseState = licenseStateMock.create(); + const router = httpServiceMock.createRouter(); + + getRuleExecutionKPIRoute(router, licenseState); + + const [config, handler] = router.get.mock.calls[0]; + + expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/_execution_kpi"`); + + rulesClient.getRuleExecutionKPI.mockResolvedValue(mockedExecutionLog); + + const [context, req, res] = mockHandlerArguments( + { rulesClient }, + { + params: { + id: '1', + }, + query: { + date_start: dateString, + }, + }, + ['ok'] + ); + + await handler(context, req, res); + + expect(rulesClient.getRuleExecutionKPI).toHaveBeenCalledTimes(1); + expect(rulesClient.getRuleExecutionKPI.mock.calls[0]).toEqual([ + { + dateStart: dateString, + id: '1', + }, + ]); + + expect(res.ok).toHaveBeenCalled(); + }); + + it('returns NOT-FOUND when rule is not found', async () => { + const licenseState = licenseStateMock.create(); + const router = httpServiceMock.createRouter(); + + getRuleExecutionKPIRoute(router, licenseState); + + const [, handler] = router.get.mock.calls[0]; + + rulesClient.getRuleExecutionKPI = jest + .fn() + .mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + + const [context, req, res] = mockHandlerArguments( + { rulesClient }, + { + params: { + id: '1', + }, + query: {}, + }, + ['notFound'] + ); + + expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( + `[Error: Saved object [alert/1] not found]` + ); + }); +}); diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.ts new file mode 100644 index 0000000000000..11f7085c53290 --- /dev/null +++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { IRouter } from '@kbn/core/server'; +import { schema } from '@kbn/config-schema'; +import { AlertingRequestHandlerContext, INTERNAL_BASE_ALERTING_API_PATH } from '../types'; +import { RewriteRequestCase, verifyAccessAndContext } from './lib'; +import { GetRuleExecutionKPIParams } from '../rules_client'; +import { ILicenseState } from '../lib'; + +const paramSchema = schema.object({ + id: schema.string(), +}); + +const querySchema = schema.object({ + date_start: schema.string(), + date_end: schema.maybe(schema.string()), + filter: schema.maybe(schema.string()), +}); + +const rewriteReq: RewriteRequestCase = ({ + date_start: dateStart, + date_end: dateEnd, + ...rest +}) => ({ + ...rest, + dateStart, + dateEnd, +}); + +export const getRuleExecutionKPIRoute = ( + router: IRouter, + licenseState: ILicenseState +) => { + router.get( + { + path: `${INTERNAL_BASE_ALERTING_API_PATH}/rule/{id}/_execution_kpi`, + validate: { + params: paramSchema, + query: querySchema, + }, + }, + router.handleLegacyErrors( + verifyAccessAndContext(licenseState, async function (context, req, res) { + const rulesClient = (await context.alerting).getRulesClient(); + const { id } = req.params; + return res.ok({ + body: await rulesClient.getRuleExecutionKPI(rewriteReq({ id, ...req.query })), + }); + }) + ) + ); +}; diff --git a/x-pack/plugins/alerting/server/routes/index.ts b/x-pack/plugins/alerting/server/routes/index.ts index dca2e214d0786..de9e2f112d9e9 100644 --- a/x-pack/plugins/alerting/server/routes/index.ts +++ b/x-pack/plugins/alerting/server/routes/index.ts @@ -22,7 +22,9 @@ import { findRulesRoute, findInternalRulesRoute } from './find_rules'; import { getRuleAlertSummaryRoute } from './get_rule_alert_summary'; import { getRuleExecutionLogRoute } from './get_rule_execution_log'; import { getGlobalExecutionLogRoute } from './get_global_execution_logs'; +import { getGlobalExecutionKPIRoute } from './get_global_execution_kpi'; import { getActionErrorLogRoute } from './get_action_error_log'; +import { getRuleExecutionKPIRoute } from './get_rule_execution_kpi'; import { getRuleStateRoute } from './get_rule_state'; import { healthRoute } from './health'; import { resolveRuleRoute } from './resolve_rule'; @@ -63,6 +65,8 @@ export function defineRoutes(opts: RouteOptions) { getRuleExecutionLogRoute(router, licenseState); getGlobalExecutionLogRoute(router, licenseState); getActionErrorLogRoute(router, licenseState); + getRuleExecutionKPIRoute(router, licenseState); + getGlobalExecutionKPIRoute(router, licenseState); getRuleStateRoute(router, licenseState); healthRoute(router, licenseState, encryptedSavedObjects); ruleTypesRoute(router, licenseState); diff --git a/x-pack/plugins/alerting/server/rules_client.mock.ts b/x-pack/plugins/alerting/server/rules_client.mock.ts index 7333ad59bbb71..2092b98e48c0d 100644 --- a/x-pack/plugins/alerting/server/rules_client.mock.ts +++ b/x-pack/plugins/alerting/server/rules_client.mock.ts @@ -30,6 +30,8 @@ const createRulesClientMock = () => { listAlertTypes: jest.fn(), getAlertSummary: jest.fn(), getExecutionLogForRule: jest.fn(), + getRuleExecutionKPI: jest.fn(), + getGlobalExecutionKpiWithAuth: jest.fn(), getGlobalExecutionLogWithAuth: jest.fn(), getActionErrorLog: jest.fn(), getSpaceId: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/audit_events.ts b/x-pack/plugins/alerting/server/rules_client/audit_events.ts index c29bc99aa6ed7..30b759c895c46 100644 --- a/x-pack/plugins/alerting/server/rules_client/audit_events.ts +++ b/x-pack/plugins/alerting/server/rules_client/audit_events.ts @@ -26,7 +26,9 @@ export enum RuleAuditAction { BULK_EDIT = 'rule_bulk_edit', GET_EXECUTION_LOG = 'rule_get_execution_log', GET_GLOBAL_EXECUTION_LOG = 'rule_get_global_execution_log', + GET_GLOBAL_EXECUTION_KPI = 'rule_get_global_execution_kpi', GET_ACTION_ERROR_LOG = 'rule_get_action_error_log', + GET_RULE_EXECUTION_KPI = 'rule_get_execution_kpi', SNOOZE = 'rule_snooze', UNSNOOZE = 'rule_unsnooze', RUN_SOON = 'rule_run_soon', @@ -68,6 +70,16 @@ const eventVerbs: Record = { rule_snooze: ['snooze', 'snoozing', 'snoozed'], rule_unsnooze: ['unsnooze', 'unsnoozing', 'unsnoozed'], rule_run_soon: ['run', 'running', 'ran'], + rule_get_execution_kpi: [ + 'access execution KPI for', + 'accessing execution KPI for', + 'accessed execution KPI for', + ], + rule_get_global_execution_kpi: [ + 'access global execution KPI for', + 'accessing global execution KPI for', + 'accessed global execution KPI for', + ], }; const eventTypes: Record = { @@ -92,6 +104,8 @@ const eventTypes: Record = { rule_snooze: 'change', rule_unsnooze: 'change', rule_run_soon: 'access', + rule_get_execution_kpi: 'access', + rule_get_global_execution_kpi: 'access', }; export interface RuleAuditEventParams { diff --git a/x-pack/plugins/alerting/server/rules_client/rules_client.ts b/x-pack/plugins/alerting/server/rules_client/rules_client.ts index 79837cdfed4cc..89ce20b59ae9b 100644 --- a/x-pack/plugins/alerting/server/rules_client/rules_client.ts +++ b/x-pack/plugins/alerting/server/rules_client/rules_client.ts @@ -22,7 +22,7 @@ import { } from 'lodash'; import { i18n } from '@kbn/i18n'; import { AlertConsumers } from '@kbn/rule-data-utils'; -import { fromKueryExpression, KueryNode, nodeBuilder } from '@kbn/es-query'; +import { KueryNode, nodeBuilder } from '@kbn/es-query'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { Logger, @@ -118,7 +118,9 @@ import { import { AlertingRulesConfig } from '../config'; import { formatExecutionLogResult, + formatExecutionKPIResult, getExecutionLogAggregation, + getExecutionKPIAggregation, } from '../lib/get_execution_log_aggregation'; import { IExecutionLogResult, IExecutionErrorsResult } from '../../common'; import { validateSnoozeStartDate } from '../lib/validate_snooze_date'; @@ -381,6 +383,19 @@ export interface GetExecutionLogByIdParams { sort: estypes.Sort; } +export interface GetRuleExecutionKPIParams { + id: string; + dateStart: string; + dateEnd?: string; + filter?: string; +} + +export interface GetGlobalExecutionKPIParams { + dateStart: string; + dateEnd?: string; + filter?: string; +} + export interface GetGlobalExecutionLogParams { dateStart: string; dateEnd?: string; @@ -1039,6 +1054,125 @@ export class RulesClient { } } + public async getGlobalExecutionKpiWithAuth({ + dateStart, + dateEnd, + filter, + }: GetGlobalExecutionKPIParams) { + this.logger.debug(`getGlobalExecutionLogWithAuth(): getting global execution log`); + + let authorizationTuple; + try { + authorizationTuple = await this.authorization.getFindAuthorizationFilter( + AlertingAuthorizationEntity.Alert, + { + type: AlertingAuthorizationFilterType.KQL, + fieldNames: { + ruleTypeId: 'kibana.alert.rule.rule_type_id', + consumer: 'kibana.alert.rule.consumer', + }, + } + ); + } catch (error) { + this.auditLogger?.log( + ruleAuditEvent({ + action: RuleAuditAction.GET_GLOBAL_EXECUTION_KPI, + error, + }) + ); + throw error; + } + + this.auditLogger?.log( + ruleAuditEvent({ + action: RuleAuditAction.GET_GLOBAL_EXECUTION_KPI, + }) + ); + + const dateNow = new Date(); + const parsedDateStart = parseDate(dateStart, 'dateStart', dateNow); + const parsedDateEnd = parseDate(dateEnd, 'dateEnd', dateNow); + + const eventLogClient = await this.getEventLogClient(); + + try { + const aggResult = await eventLogClient.aggregateEventsWithAuthFilter( + 'alert', + authorizationTuple.filter as KueryNode, + { + start: parsedDateStart.toISOString(), + end: parsedDateEnd.toISOString(), + aggs: getExecutionKPIAggregation(filter), + } + ); + + return formatExecutionKPIResult(aggResult); + } catch (err) { + this.logger.debug( + `rulesClient.getGlobalExecutionKpiWithAuth(): error searching global execution KPI: ${err.message}` + ); + throw err; + } + } + + public async getRuleExecutionKPI({ id, dateStart, dateEnd, filter }: GetRuleExecutionKPIParams) { + this.logger.debug(`getRuleExecutionKPI(): getting execution KPI for rule ${id}`); + const rule = (await this.get({ id, includeLegacyId: true })) as SanitizedRuleWithLegacyId; + + try { + // Make sure user has access to this rule + await this.authorization.ensureAuthorized({ + ruleTypeId: rule.alertTypeId, + consumer: rule.consumer, + operation: ReadOperations.GetRuleExecutionKPI, + entity: AlertingAuthorizationEntity.Rule, + }); + } catch (error) { + this.auditLogger?.log( + ruleAuditEvent({ + action: RuleAuditAction.GET_RULE_EXECUTION_KPI, + savedObject: { type: 'alert', id }, + error, + }) + ); + throw error; + } + + this.auditLogger?.log( + ruleAuditEvent({ + action: RuleAuditAction.GET_RULE_EXECUTION_KPI, + savedObject: { type: 'alert', id }, + }) + ); + + // default duration of instance summary is 60 * rule interval + const dateNow = new Date(); + const parsedDateStart = parseDate(dateStart, 'dateStart', dateNow); + const parsedDateEnd = parseDate(dateEnd, 'dateEnd', dateNow); + + const eventLogClient = await this.getEventLogClient(); + + try { + const aggResult = await eventLogClient.aggregateEventsBySavedObjectIds( + 'alert', + [id], + { + start: parsedDateStart.toISOString(), + end: parsedDateEnd.toISOString(), + aggs: getExecutionKPIAggregation(filter), + }, + rule.legacyId !== null ? [rule.legacyId] : undefined + ); + + return formatExecutionKPIResult(aggResult); + } catch (err) { + this.logger.debug( + `rulesClient.getRuleExecutionKPI(): error searching execution KPI for rule ${id}: ${err.message}` + ); + throw err; + } + } + public async find({ options: { fields, ...options } = {}, excludeFromPublicApi = false, @@ -1110,7 +1244,7 @@ export class RulesClient { filter: (authorizationFilter && filterKueryNode ? nodeBuilder.and([filterKueryNode, authorizationFilter as KueryNode]) - : authorizationFilter) ?? options.filter, + : authorizationFilter) ?? filterKueryNode, fields: fields ? this.includeFieldsRequiredForAuthentication(fields) : fields, type: 'alert', }); @@ -1569,14 +1703,7 @@ export class RulesClient { ); } - let qNodeQueryFilter: null | KueryNode; - if (!queryFilter) { - qNodeQueryFilter = null; - } else if (typeof queryFilter === 'string') { - qNodeQueryFilter = fromKueryExpression(queryFilter); - } else { - qNodeQueryFilter = queryFilter; - } + const qNodeQueryFilter = buildKueryNodeFilter(queryFilter); const qNodeFilter = ids ? convertRuleIdsToKueryNode(ids) : qNodeQueryFilter; let authorizationTuple; @@ -1797,12 +1924,11 @@ export class RulesClient { break; } if (operation.operation === 'set') { - const snoozeAttributes = getSnoozeAttributes(attributes, operation.value); - const schedules = snoozeAttributes.snoozeSchedule.filter((snooze) => snooze.id); - if (schedules.length > 5) { - throw Error( - `Error updating rule: rule cannot have more than 5 snooze schedules` - ); + const snoozeAttributes = getBulkSnoozeAttributes(attributes, operation.value); + try { + verifySnoozeScheduleLimit(snoozeAttributes); + } catch (error) { + throw Error(`Error updating rule: could not add snooze - ${error.message}`); } attributes = { ...attributes, @@ -1820,7 +1946,7 @@ export class RulesClient { } attributes = { ...attributes, - ...getUnsnoozeAttributes(attributes, idsToDelete), + ...getBulkUnsnoozeAttributes(attributes, idsToDelete), }; } break; @@ -2278,7 +2404,7 @@ export class RulesClient { const recoveredAlertInstanceIds = Object.keys(recoveredAlertInstances); for (const instanceId of recoveredAlertInstanceIds) { - const { group: actionGroup, subgroup: actionSubgroup } = + const { group: actionGroup } = recoveredAlertInstances[instanceId].getLastScheduledActions() ?? {}; const instanceState = recoveredAlertInstances[instanceId].getState(); const message = `instance '${instanceId}' has recovered due to the rule was disabled`; @@ -2293,7 +2419,6 @@ export class RulesClient { message, state: instanceState, group: actionGroup, - subgroup: actionSubgroup, namespace: this.namespace, spaceId: this.spaceId, savedObjects: [ @@ -2433,6 +2558,12 @@ export class RulesClient { const newAttrs = getSnoozeAttributes(attributes, snoozeSchedule); + try { + verifySnoozeScheduleLimit(newAttrs); + } catch (error) { + throw Boom.badRequest(error.message); + } + const updateAttributes = this.updateMeta({ ...newAttrs, updatedBy: await this.getUserName(), @@ -3249,6 +3380,33 @@ function getSnoozeAttributes(attributes: RawRule, snoozeSchedule: RuleSnoozeSche }; } +function getBulkSnoozeAttributes(attributes: RawRule, snoozeSchedule: RuleSnoozeSchedule) { + // If duration is -1, instead mute all + const { id: snoozeId, duration } = snoozeSchedule; + + if (duration === -1) { + return { + muteAll: true, + snoozeSchedule: clearUnscheduledSnooze(attributes), + }; + } + + // Bulk adding snooze schedule, don't touch the existing snooze/indefinite snooze + if (snoozeId) { + const existingSnoozeSchedules = attributes.snoozeSchedule || []; + return { + muteAll: attributes.muteAll, + snoozeSchedule: [...existingSnoozeSchedules, snoozeSchedule], + }; + } + + // Bulk snoozing, don't touch the existing snooze schedules + return { + muteAll: false, + snoozeSchedule: [...clearUnscheduledSnooze(attributes), snoozeSchedule], + }; +} + function getUnsnoozeAttributes(attributes: RawRule, scheduleIds?: string[]) { const snoozeSchedule = scheduleIds ? clearScheduledSnoozesById(attributes, scheduleIds) @@ -3260,6 +3418,27 @@ function getUnsnoozeAttributes(attributes: RawRule, scheduleIds?: string[]) { }; } +function getBulkUnsnoozeAttributes(attributes: RawRule, scheduleIds?: string[]) { + // Bulk removing snooze schedules, don't touch the current snooze/indefinite snooze + if (scheduleIds) { + const newSchedules = clearScheduledSnoozesById(attributes, scheduleIds); + // Unscheduled snooze is also known as snooze now + const unscheduledSnooze = + attributes.snoozeSchedule?.filter((s) => typeof s.id === 'undefined') || []; + + return { + snoozeSchedule: [...unscheduledSnooze, ...newSchedules], + muteAll: attributes.muteAll, + }; + } + + // Bulk unsnoozing, don't touch current snooze schedules that are NOT active + return { + snoozeSchedule: clearCurrentActiveSnooze(attributes), + muteAll: false, + }; +} + function clearUnscheduledSnooze(attributes: RawRule) { // Clear any snoozes that have no ID property. These are "simple" snoozes created with the quick UI, e.g. snooze for 3 days starting now return attributes.snoozeSchedule @@ -3299,3 +3478,14 @@ function clearCurrentActiveSnooze(attributes: RawRule) { }); return clearedSnoozesAndSkippedRecurringSnoozes; } + +function verifySnoozeScheduleLimit(attributes: Partial) { + const schedules = attributes.snoozeSchedule?.filter((snooze) => snooze.id); + if (schedules && schedules.length > 5) { + throw Error( + i18n.translate('xpack.alerting.rulesClient.snoozeSchedule.limitReached', { + defaultMessage: 'Rule cannot have more than 5 snooze schedules', + }) + ); + } +} diff --git a/x-pack/plugins/alerting/server/rules_client/tests/bulk_edit.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/bulk_edit.test.ts index 5ab3de879c3c9..5e440d2e6b6d7 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/bulk_edit.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/bulk_edit.test.ts @@ -26,9 +26,11 @@ jest.mock('../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation })); jest.mock('../../lib/snooze/is_snooze_active', () => ({ - isSnoozeActive: jest.fn(() => true), + isSnoozeActive: jest.fn(), })); +const { isSnoozeActive } = jest.requireMock('../../lib/snooze/is_snooze_active'); + const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); @@ -310,9 +312,13 @@ describe('bulkEdit()', () => { }); describe('snoozeSchedule operations', () => { - const getSnoozeSchedule = () => { + afterEach(() => { + isSnoozeActive.mockImplementation(() => false); + }); + + const getSnoozeSchedule = (useId: boolean = true) => { return { - id: uuid.v4(), + ...(useId && { id: uuid.v4() }), duration: 28800000, rRule: { dtstart: '2010-09-19T11:49:59.329Z', @@ -321,8 +327,10 @@ describe('bulkEdit()', () => { }, }; }; - test('should add snooze', async () => { - unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue({ + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const getMockAttribute = (override: Record = {}) => { + return { saved_objects: [ { id: '1', @@ -339,15 +347,137 @@ describe('bulkEdit()', () => { notifyWhen: null, actions: [], snoozeSchedule: [], + ...override, }, references: [], version: '123', }, ], + }; + }; + + test('should snooze', async () => { + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + const snoozePayload = getSnoozeSchedule(false); + await rulesClient.bulkEdit({ + filter: '', + operations: [ + { + operation: 'set', + field: 'snoozeSchedule', + value: snoozePayload, + }, + ], + }); + + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledWith( + [ + expect.objectContaining({ + id: '1', + type: 'alert', + attributes: expect.objectContaining({ + snoozeSchedule: [snoozePayload], + }), + }), + ], + { overwrite: true } + ); + }); + + test('should add snooze schedule', async () => { + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + + const snoozePayload = getSnoozeSchedule(); + await rulesClient.bulkEdit({ + filter: '', + operations: [ + { + operation: 'set', + field: 'snoozeSchedule', + value: snoozePayload, + }, + ], + }); + + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledWith( + [ + expect.objectContaining({ + id: '1', + type: 'alert', + attributes: expect.objectContaining({ + snoozeSchedule: [snoozePayload], + }), + }), + ], + { overwrite: true } + ); + }); + + test('should not unsnooze a snoozed rule when bulk adding snooze schedules', async () => { + const existingSnooze = [getSnoozeSchedule(false), getSnoozeSchedule()]; + + mockCreatePointInTimeFinderAsInternalUser({ + saved_objects: [ + { + ...existingDecryptedRule, + attributes: { + ...existingDecryptedRule.attributes, + snoozeSchedule: existingSnooze, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any, + }, + ], }); + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + const snoozePayload = getSnoozeSchedule(); + await rulesClient.bulkEdit({ + filter: '', + operations: [ + { + operation: 'set', + field: 'snoozeSchedule', + value: snoozePayload, + }, + ], + }); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledWith( + [ + expect.objectContaining({ + id: '1', + type: 'alert', + attributes: expect.objectContaining({ + snoozeSchedule: [...existingSnooze, snoozePayload], + }), + }), + ], + { overwrite: true } + ); + }); + + test('should not unsnooze an indefinitely snoozed rule when bulk adding snooze schedules', async () => { + mockCreatePointInTimeFinderAsInternalUser({ + saved_objects: [ + { + ...existingDecryptedRule, + attributes: { + ...existingDecryptedRule.attributes, + muteAll: true, + snoozeSchedule: [], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any, + }, + ], + }); + + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + + const snoozePayload = getSnoozeSchedule(); await rulesClient.bulkEdit({ filter: '', operations: [ @@ -366,6 +496,7 @@ describe('bulkEdit()', () => { id: '1', type: 'alert', attributes: expect.objectContaining({ + muteAll: true, snoozeSchedule: [snoozePayload], }), }), @@ -374,39 +505,74 @@ describe('bulkEdit()', () => { ); }); - test('should delete snooze', async () => { - const existingSnooze = [getSnoozeSchedule(), getSnoozeSchedule()]; + test('should unsnooze', async () => { + const existingSnooze = [getSnoozeSchedule(false), getSnoozeSchedule(), getSnoozeSchedule()]; - unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue({ + mockCreatePointInTimeFinderAsInternalUser({ saved_objects: [ { + ...existingDecryptedRule, + attributes: { + ...existingDecryptedRule.attributes, + snoozeSchedule: existingSnooze, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any, + }, + ], + }); + + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + + await rulesClient.bulkEdit({ + filter: '', + operations: [ + { + operation: 'delete', + field: 'snoozeSchedule', + }, + ], + }); + + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledWith( + [ + expect.objectContaining({ id: '1', type: 'alert', + attributes: expect.objectContaining({ + snoozeSchedule: [existingSnooze[1], existingSnooze[2]], + }), + }), + ], + { overwrite: true } + ); + }); + + test('should remove snooze schedules', async () => { + const existingSnooze = [getSnoozeSchedule(), getSnoozeSchedule()]; + + mockCreatePointInTimeFinderAsInternalUser({ + saved_objects: [ + { + ...existingDecryptedRule, attributes: { - enabled: true, - tags: ['foo', 'test-1'], - alertTypeId: 'myType', - schedule: { interval: '1m' }, - consumer: 'myApp', - scheduledTaskId: 'task-123', - params: {}, - throttle: null, - notifyWhen: null, - actions: [], + ...existingDecryptedRule.attributes, snoozeSchedule: existingSnooze, - }, - references: [], - version: '123', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any, }, ], }); + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + await rulesClient.bulkEdit({ filter: '', operations: [ { operation: 'delete', field: 'snoozeSchedule', + value: [], }, ], }); @@ -426,14 +592,8 @@ describe('bulkEdit()', () => { ); }); - test('should error if adding snooze schedule to rule with 5 schedules', async () => { - const existingSnooze = [ - getSnoozeSchedule(), - getSnoozeSchedule(), - getSnoozeSchedule(), - getSnoozeSchedule(), - getSnoozeSchedule(), - ]; + test('should not unsnooze rule when removing snooze schedules', async () => { + const existingSnooze = [getSnoozeSchedule(false), getSnoozeSchedule(), getSnoozeSchedule()]; mockCreatePointInTimeFinderAsInternalUser({ saved_objects: [ @@ -448,30 +608,58 @@ describe('bulkEdit()', () => { ], }); - unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: [ + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + + await rulesClient.bulkEdit({ + filter: '', + operations: [ { + operation: 'delete', + field: 'snoozeSchedule', + value: [], + }, + ], + }); + + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.bulkCreate).toHaveBeenCalledWith( + [ + expect.objectContaining({ id: '1', type: 'alert', + attributes: expect.objectContaining({ + snoozeSchedule: [existingSnooze[0]], + }), + }), + ], + { overwrite: true } + ); + }); + + test('should error if adding snooze schedule to rule with 5 schedules', async () => { + const existingSnooze = [ + getSnoozeSchedule(), + getSnoozeSchedule(), + getSnoozeSchedule(), + getSnoozeSchedule(), + getSnoozeSchedule(), + ]; + + mockCreatePointInTimeFinderAsInternalUser({ + saved_objects: [ + { + ...existingDecryptedRule, attributes: { - enabled: true, - tags: ['foo', 'test-1'], - alertTypeId: 'myType', - schedule: { interval: '1m' }, - consumer: 'myApp', - scheduledTaskId: 'task-123', - params: {}, - throttle: null, - notifyWhen: null, - actions: [], + ...existingDecryptedRule.attributes, snoozeSchedule: existingSnooze, - }, - references: [], - version: '123', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any, }, ], }); + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); + const snoozePayload = getSnoozeSchedule(); const response = await rulesClient.bulkEdit({ @@ -486,7 +674,7 @@ describe('bulkEdit()', () => { }); expect(response.errors.length).toEqual(1); expect(response.errors[0].message).toEqual( - 'Error updating rule: rule cannot have more than 5 snooze schedules' + 'Error updating rule: could not add snooze - Rule cannot have more than 5 snooze schedules' ); }); @@ -501,29 +689,7 @@ describe('bulkEdit()', () => { ], }); - unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: [ - { - id: '1', - type: 'alert', - attributes: { - enabled: true, - tags: ['foo', 'test-1'], - alertTypeId: 'myType', - schedule: { interval: '1m' }, - consumer: 'myApp', - scheduledTaskId: 'task-123', - params: {}, - throttle: null, - notifyWhen: null, - actions: [], - snoozeSchedule: [], - }, - references: [], - version: '123', - }, - ], - }); + unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue(getMockAttribute()); const snoozePayload = getSnoozeSchedule(); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts index cca7cd0d70322..558d33ecca87c 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts @@ -250,7 +250,6 @@ describe('disable()', () => { meta: { lastScheduledActions: { group: 'default', - subgroup: 'newSubgroup', date: new Date().toISOString(), }, }, @@ -319,7 +318,6 @@ describe('disable()', () => { }, alerting: { action_group_id: 'default', - action_subgroup: 'newSubgroup', instance_id: '1', }, saved_objects: [ diff --git a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts index e26004de99a31..4cfa13f69b84d 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts @@ -176,7 +176,7 @@ describe('find()', () => { Array [ Object { "fields": undefined, - "filter": undefined, + "filter": null, "sortField": undefined, "type": "alert", }, @@ -277,7 +277,7 @@ describe('find()', () => { Array [ Object { "fields": undefined, - "filter": undefined, + "filter": null, "sortField": undefined, "type": "alert", }, @@ -730,6 +730,8 @@ describe('find()', () => { expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledWith({ fields: ['tags', 'alertTypeId', 'consumer'], + filter: null, + sortField: undefined, type: 'alert', }); expect(ensureRuleTypeIsAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'rule'); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts index 6dcd64565c562..4aa7ae40f8782 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts @@ -156,21 +156,18 @@ describe('getAlertSummary()', () => { "alerts": Object { "alert-currently-active": Object { "actionGroupId": "action group A", - "actionSubgroup": undefined, "activeStartDate": "2019-02-12T21:01:22.479Z", "muted": false, "status": "Active", }, "alert-muted-no-activity": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": true, "status": "OK", }, "alert-previously-active": Object { "actionGroupId": undefined, - "actionSubgroup": undefined, "activeStartDate": undefined, "muted": false, "status": "OK", diff --git a/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts b/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts index 7146ef4a5225c..51ba1404b2a4f 100644 --- a/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts +++ b/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts @@ -65,7 +65,6 @@ export function createExecutionHandler< return async ({ actionGroup, - actionSubgroup, context, state, ruleRunMetricsStore, @@ -92,7 +91,6 @@ export function createExecutionHandler< alertInstanceId: alertId, alertActionGroup: actionGroup, alertActionGroupName: ruleTypeActionGroups.get(actionGroup)!, - alertActionSubgroup: actionSubgroup, context, actionParams: action.params, actionId: action.id, @@ -203,7 +201,6 @@ export function createExecutionHandler< typeId: actionTypeId, alertId, alertGroup: actionGroup, - alertSubgroup: actionSubgroup, }); } diff --git a/x-pack/plugins/alerting/server/task_runner/fixtures.ts b/x-pack/plugins/alerting/server/task_runner/fixtures.ts index 39b90efbc786e..0a90456dbdad6 100644 --- a/x-pack/plugins/alerting/server/task_runner/fixtures.ts +++ b/x-pack/plugins/alerting/server/task_runner/fixtures.ts @@ -178,7 +178,7 @@ export const mockTaskInstance = () => ({ ownerId: null, }); -export const generateAlertOpts = ({ action, group, subgroup, state, id }: GeneratorParams = {}) => { +export const generateAlertOpts = ({ action, group, state, id }: GeneratorParams = {}) => { id = id ?? '1'; let message: string = ''; switch (action) { @@ -186,9 +186,7 @@ export const generateAlertOpts = ({ action, group, subgroup, state, id }: Genera message = `test:1: 'rule-name' created new alert: '${id}'`; break; case EVENT_LOG_ACTIONS.activeInstance: - message = subgroup - ? `test:1: 'rule-name' active alert: '${id}' in actionGroup(subgroup): 'default(${subgroup})'` - : `test:1: 'rule-name' active alert: '${id}' in actionGroup: 'default'`; + message = `test:1: 'rule-name' active alert: '${id}' in actionGroup: 'default'`; break; case EVENT_LOG_ACTIONS.recoveredInstance: message = `test:1: 'rule-name' alert '${id}' has recovered`; @@ -200,21 +198,14 @@ export const generateAlertOpts = ({ action, group, subgroup, state, id }: Genera message, state, ...(group ? { group } : {}), - ...(subgroup ? { subgroup } : {}), }; }; -export const generateActionOpts = ({ - subgroup, - id, - alertGroup, - alertId, -}: GeneratorParams = {}) => ({ +export const generateActionOpts = ({ id, alertGroup, alertId }: GeneratorParams = {}) => ({ id: id ?? '1', typeId: 'action', alertId: alertId ?? '1', alertGroup: alertGroup ?? 'default', - ...(subgroup ? { alertSubgroup: subgroup } : {}), }); export const generateRunnerResult = ({ @@ -280,7 +271,6 @@ export const generateAlertInstance = ({ id, duration, start }: GeneratorParams = lastScheduledActions: { date: new Date(DATE_1970), group: 'default', - subgroup: undefined, }, }, state: { diff --git a/x-pack/plugins/alerting/server/task_runner/log_alerts.ts b/x-pack/plugins/alerting/server/task_runner/log_alerts.ts index 87da1fb67f332..2abe72ed06cb5 100644 --- a/x-pack/plugins/alerting/server/task_runner/log_alerts.ts +++ b/x-pack/plugins/alerting/server/task_runner/log_alerts.ts @@ -92,8 +92,7 @@ export function logAlerts< ruleRunMetricsStore.setNumberOfRecoveredAlerts(recoveredAlertIds.length); for (const id of recoveredAlertIds) { - const { group: actionGroup, subgroup: actionSubgroup } = - recoveredAlerts[id].getLastScheduledActions() ?? {}; + const { group: actionGroup } = recoveredAlerts[id].getLastScheduledActions() ?? {}; const state = recoveredAlerts[id].getState(); const message = `${ruleLogPrefix} alert '${id}' has recovered`; @@ -101,41 +100,32 @@ export function logAlerts< action: EVENT_LOG_ACTIONS.recoveredInstance, id, group: actionGroup, - subgroup: actionSubgroup, message, state, }); } for (const id of newAlertIds) { - const { actionGroup, subgroup: actionSubgroup } = - activeAlerts[id].getScheduledActionOptions() ?? {}; + const { actionGroup } = activeAlerts[id].getScheduledActionOptions() ?? {}; const state = activeAlerts[id].getState(); const message = `${ruleLogPrefix} created new alert: '${id}'`; alertingEventLogger.logAlert({ action: EVENT_LOG_ACTIONS.newInstance, id, group: actionGroup, - subgroup: actionSubgroup, message, state, }); } for (const id of activeAlertIds) { - const { actionGroup, subgroup: actionSubgroup } = - activeAlerts[id].getScheduledActionOptions() ?? {}; + const { actionGroup } = activeAlerts[id].getScheduledActionOptions() ?? {}; const state = activeAlerts[id].getState(); - const message = `${ruleLogPrefix} active alert: '${id}' in ${ - actionSubgroup - ? `actionGroup(subgroup): '${actionGroup}(${actionSubgroup})'` - : `actionGroup: '${actionGroup}'` - }`; + const message = `${ruleLogPrefix} active alert: '${id}' in actionGroup: '${actionGroup}'`; alertingEventLogger.logAlert({ action: EVENT_LOG_ACTIONS.activeInstance, id, group: actionGroup, - subgroup: actionSubgroup, message, state, }); diff --git a/x-pack/plugins/alerting/server/task_runner/schedule_actions_for_alerts.ts b/x-pack/plugins/alerting/server/task_runner/schedule_actions_for_alerts.ts index e0cc6d5b81c3a..8c1d62ecf4e32 100644 --- a/x-pack/plugins/alerting/server/task_runner/schedule_actions_for_alerts.ts +++ b/x-pack/plugins/alerting/server/task_runner/schedule_actions_for_alerts.ts @@ -49,16 +49,8 @@ export async function scheduleActionsForAlerts< notifyWhen ); if (executeAction && alert.hasScheduledActions()) { - const { actionGroup, subgroup: actionSubgroup, state } = alert.getScheduledActionOptions()!; - await executeAlert( - alertId, - alert, - executionHandler, - ruleRunMetricsStore, - actionGroup, - state, - actionSubgroup - ); + const { actionGroup, state } = alert.getScheduledActionOptions()!; + await executeAlert(alertId, alert, executionHandler, ruleRunMetricsStore, actionGroup, state); } } @@ -94,14 +86,12 @@ async function executeAlert< executionHandler: ExecutionHandler, ruleRunMetricsStore: RuleRunMetricsStore, actionGroup: ActionGroupIds | RecoveryActionGroupId, - state: InstanceState, - actionSubgroup?: string + state: InstanceState ) { - alert.updateLastScheduledActions(actionGroup, actionSubgroup); + alert.updateLastScheduledActions(actionGroup); alert.unscheduleActions(); return executionHandler({ actionGroup, - actionSubgroup, context: alert.getContext(), state, alertId, @@ -133,10 +123,7 @@ function shouldExecuteAction< muted ? 'muted' : 'throttled' }` ); - } else if ( - notifyWhen === 'onActionGroupChange' && - !alert.scheduledActionGroupOrSubgroupHasChanged() - ) { + } else if (notifyWhen === 'onActionGroupChange' && !alert.scheduledActionGroupHasChanged()) { executeAction = false; logger.debug( `skipping scheduling of actions for '${alertId}' in rule ${ruleLabel}: alert is active but action group has not changed` diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts index 4ce85f54c3dc5..a199fb3b55998 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts @@ -312,9 +312,7 @@ describe('Task Runner', () => { AlertInstanceContext, string >) => { - executorServices.alertFactory - .create('1') - .scheduleActionsWithSubGroup('default', 'subDefault'); + executorServices.alertFactory.create('1').scheduleActions('default'); } ); const taskRunner = new TaskRunner( @@ -360,7 +358,6 @@ describe('Task Runner', () => { generateAlertOpts({ action: EVENT_LOG_ACTIONS.newInstance, group: 'default', - subgroup: 'subDefault', state: { start: DATE_1970, duration: '0' }, }) ); @@ -369,14 +366,10 @@ describe('Task Runner', () => { generateAlertOpts({ action: EVENT_LOG_ACTIONS.activeInstance, group: 'default', - subgroup: 'subDefault', state: { start: DATE_1970, duration: '0' }, }) ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith( - 1, - generateActionOpts({ subgroup: 'subDefault' }) - ); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts()); expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); } @@ -859,90 +852,6 @@ describe('Task Runner', () => { } ); - test.each(ephemeralTestParams)( - 'actionsPlugin.execute is called when notifyWhen=onActionGroupChange and alert state subgroup has changed %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertFactory - .create('1') - .scheduleActionsWithSubGroup('default', 'subgroup1'); - } - ); - const taskRunner = new TaskRunner( - ruleType, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: { - lastScheduledActions: { - group: 'default', - subgroup: 'newSubgroup', - date: new Date().toISOString(), - }, - }, - state: { bar: false }, - }, - }, - }, - }, - customTaskRunnerFactoryInitializerParams, - inMemoryMetrics - ); - expect(AlertingEventLogger).toHaveBeenCalled(); - - rulesClient.get.mockResolvedValue({ - ...mockedRuleTypeSavedObject, - notifyWhen: 'onActionGroupChange', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(SAVED_OBJECT); - await taskRunner.run(); - - testAlertingEventLogCalls({ - activeAlerts: 1, - triggeredActions: 1, - generatedActions: 1, - status: 'active', - logAlert: 1, - logAction: 1, - }); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 1, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.activeInstance, - state: { bar: false }, - group: 'default', - subgroup: 'subgroup1', - }) - ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith( - 1, - generateActionOpts({ subgroup: 'subgroup1' }) - ); - - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); - test.each(ephemeralTestParams)( 'includes the apiKey in the request used to initialize the actionsClient %s', async ( diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.ts index 457b2872faa62..41029af567524 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -420,7 +420,6 @@ export class TaskRunner< checkHasReachedAlertLimit(); this.alertingEventLogger.setExecutionSucceeded(`rule executed: ${ruleLabel}`); - ruleRunMetricsStore.setSearchMetrics([ wrappedScopedClusterClient.getMetrics(), wrappedSearchSourceClient.getMetrics(), diff --git a/x-pack/plugins/alerting/server/task_runner/transform_action_params.test.ts b/x-pack/plugins/alerting/server/task_runner/transform_action_params.test.ts index 6235e630ba0bb..ababe16dea378 100644 --- a/x-pack/plugins/alerting/server/task_runner/transform_action_params.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/transform_action_params.test.ts @@ -417,7 +417,6 @@ test('rule variables are passed to templates', () => { alertInstanceId: '2', alertActionGroup: 'action-group', alertActionGroupName: 'Action Group', - alertActionSubgroup: 'subgroup', alertParams: {}, }); expect(result).toMatchInlineSnapshot(` @@ -429,8 +428,7 @@ test('rule variables are passed to templates', () => { test('rule alert variables are passed to templates', () => { const actionParams = { - message: - 'Value "{{alert.id}}", "{{alert.actionGroup}}", "{{alert.actionGroupName}}" and "{{alert.actionSubgroup}}" exist', + message: 'Value "{{alert.id}}", "{{alert.actionGroup}}" and "{{alert.actionGroupName}}" exist', }; const result = transformActionParams({ actionsPlugin, @@ -447,12 +445,11 @@ test('rule alert variables are passed to templates', () => { alertInstanceId: '2', alertActionGroup: 'action-group', alertActionGroupName: 'Action Group', - alertActionSubgroup: 'subgroup', alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { - "message": "Value \\"2\\", \\"action-group\\", \\"Action Group\\" and \\"subgroup\\" exist", + "message": "Value \\"2\\", \\"action-group\\" and \\"Action Group\\" exist", } `); }); diff --git a/x-pack/plugins/alerting/server/task_runner/transform_action_params.ts b/x-pack/plugins/alerting/server/task_runner/transform_action_params.ts index 322a16c1c238e..61ec54c48886f 100644 --- a/x-pack/plugins/alerting/server/task_runner/transform_action_params.ts +++ b/x-pack/plugins/alerting/server/task_runner/transform_action_params.ts @@ -25,7 +25,6 @@ interface TransformActionParamsOptions { alertInstanceId: string; alertActionGroup: string; alertActionGroupName: string; - alertActionSubgroup?: string; actionParams: RuleActionParams; alertParams: RuleTypeParams; state: AlertInstanceState; @@ -44,7 +43,6 @@ export function transformActionParams({ tags, alertInstanceId, alertActionGroup, - alertActionSubgroup, alertActionGroupName, context, actionParams, @@ -63,7 +61,6 @@ export function transformActionParams({ alertInstanceId, alertActionGroup, alertActionGroupName, - alertActionSubgroup, context, date: new Date().toISOString(), state, @@ -80,7 +77,6 @@ export function transformActionParams({ id: alertInstanceId, actionGroup: alertActionGroup, actionGroupName: alertActionGroupName, - actionSubgroup: alertActionSubgroup, }, }; return actionsPlugin.renderActionParameterTemplates( diff --git a/x-pack/plugins/alerting/server/task_runner/types.ts b/x-pack/plugins/alerting/server/task_runner/types.ts index 87bd65b028481..ce439fa3b3b0a 100644 --- a/x-pack/plugins/alerting/server/task_runner/types.ts +++ b/x-pack/plugins/alerting/server/task_runner/types.ts @@ -116,7 +116,6 @@ export interface CreateExecutionHandlerOptions< export interface ExecutionHandlerOptions { actionGroup: ActionGroupIds; - actionSubgroup?: string; alertId: string; context: AlertInstanceContext; state: AlertInstanceState; diff --git a/x-pack/plugins/apm/ftr_e2e/cypress/e2e/power_user/storage_explorer/storage_explorer.cy.ts b/x-pack/plugins/apm/ftr_e2e/cypress/e2e/power_user/storage_explorer/storage_explorer.cy.ts new file mode 100644 index 0000000000000..e989ea5cf0faf --- /dev/null +++ b/x-pack/plugins/apm/ftr_e2e/cypress/e2e/power_user/storage_explorer/storage_explorer.cy.ts @@ -0,0 +1,192 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import moment from 'moment'; +import url from 'url'; +import { synthtrace } from '../../../../synthtrace'; +import { opbeans } from '../../../fixtures/synthtrace/opbeans'; +import { checkA11y } from '../../../support/commands'; + +const timeRange = { + rangeFrom: '2021-10-10T00:00:00.000Z', + rangeTo: '2021-10-10T00:15:00.000Z', +}; + +const storageExplorerHref = url.format({ + pathname: '/app/apm/storage-explorer', + query: timeRange, +}); + +const mainApiRequestsToIntercept = [ + { + endpoint: '/internal/apm/storage_chart', + aliasName: 'storageChartRequest', + }, + { + endpoint: '/internal/apm/storage_explorer_summary_stats', + aliasName: 'summaryStatsRequest', + }, + { + endpoint: '/internal/apm/storage_explorer', + aliasName: 'storageExlorerRequest', + }, +]; + +const mainAliasNames = mainApiRequestsToIntercept.map( + ({ aliasName }) => `@${aliasName}` +); + +describe('Storage Explorer', () => { + before(() => { + const { rangeFrom, rangeTo } = timeRange; + synthtrace.index( + opbeans({ + from: new Date(rangeFrom).getTime(), + to: new Date(rangeTo).getTime(), + }) + ); + }); + + after(() => { + synthtrace.clean(); + }); + + describe('When navigating to storage explorer without the required permissions', () => { + beforeEach(() => { + cy.loginAsViewerUser(); + cy.visitKibana(storageExplorerHref); + }); + + it('displays a prompt for permissions', () => { + cy.contains('You need permission'); + }); + }); + + describe('When navigating to storage explorer with the required permissions', () => { + beforeEach(() => { + cy.loginAsMonitorUser(); + cy.visitKibana(storageExplorerHref); + }); + + it('has no detectable a11y violations on load', () => { + cy.contains('h1', 'Storage explorer'); + // set skipFailures to true to not fail the test when there are accessibility failures + checkA11y({ skipFailures: true }); + }); + + it('has a list of summary stats', () => { + cy.contains('Total APM size'); + cy.contains('Daily data generation'); + cy.contains('Traces per minute'); + cy.contains('Number of services'); + }); + + it('renders the storage timeseries chart', () => { + cy.get('[data-test-subj="storageExplorerTimeseriesChart"]'); + }); + + it('has a list of services and environments', () => { + cy.contains('opbeans-node'); + cy.contains('opbeans-java'); + cy.contains('opbeans-rum'); + cy.get('td:contains(production)').should('have.length', 3); + }); + + it('when clicking on a service it loads the service overview for that service', () => { + cy.contains('opbeans-node').click({ force: true }); + cy.url().should('include', '/apm/services/opbeans-node/overview'); + cy.contains('h1', 'opbeans-node'); + }); + }); + + describe('Calls APIs', () => { + beforeEach(() => { + mainApiRequestsToIntercept.forEach(({ endpoint, aliasName }) => { + cy.intercept({ pathname: endpoint }).as(aliasName); + }); + + cy.loginAsMonitorUser(); + cy.visitKibana(storageExplorerHref); + }); + + it('with the correct environment when changing the environment', () => { + cy.wait(mainAliasNames); + + cy.get('[data-test-subj="environmentFilter"]').type('production'); + + cy.contains('button', 'production').click({ force: true }); + + cy.expectAPIsToHaveBeenCalledWith({ + apisIntercepted: mainAliasNames, + value: 'environment=production', + }); + }); + + it('when clicking the refresh button', () => { + cy.wait(mainAliasNames); + cy.contains('Refresh').click(); + cy.wait(mainAliasNames); + }); + + it('when selecting a different time range and clicking the update button', () => { + cy.wait(mainAliasNames); + + cy.selectAbsoluteTimeRange( + moment(timeRange.rangeFrom).subtract(5, 'm').toISOString(), + moment(timeRange.rangeTo).subtract(5, 'm').toISOString() + ); + cy.contains('Update').click(); + cy.wait(mainAliasNames); + + cy.contains('Refresh').click(); + cy.wait(mainAliasNames); + }); + + it('with the correct lifecycle phase when changing the lifecycle phase', () => { + cy.wait(mainAliasNames); + + cy.get('[data-test-subj="storageExplorerLifecyclePhaseSelect"]').click(); + cy.contains('button', 'Warm').click(); + + cy.expectAPIsToHaveBeenCalledWith({ + apisIntercepted: mainAliasNames, + value: 'indexLifecyclePhase=warm', + }); + }); + }); + + describe('Storage details per service', () => { + beforeEach(() => { + const apiRequestsToIntercept = [ + ...mainApiRequestsToIntercept, + { + endpoint: '/internal/apm/services/opbeans-node/storage_details', + aliasName: 'storageDetailsRequest', + }, + ]; + + apiRequestsToIntercept.forEach(({ endpoint, aliasName }) => { + cy.intercept({ pathname: endpoint }).as(aliasName); + }); + + cy.loginAsMonitorUser(); + cy.visitKibana(storageExplorerHref); + }); + + it('shows storage details', () => { + cy.wait(mainAliasNames); + cy.contains('opbeans-node'); + + cy.get('[data-test-subj="storageDetailsButton_opbeans-node"]').click(); + cy.get('[data-test-subj="loadingSpinner"]').should('be.visible'); + cy.wait('@storageDetailsRequest'); + + cy.contains('Service storage details'); + cy.get('[data-test-subj="storageExplorerTimeseriesChart"]'); + cy.get('[data-test-subj="serviceStorageDetailsTable"]'); + }); + }); +}); diff --git a/x-pack/plugins/apm/ftr_e2e/cypress/support/commands.ts b/x-pack/plugins/apm/ftr_e2e/cypress/support/commands.ts index 692926d3049ca..7830e791c3655 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress/support/commands.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress/support/commands.ts @@ -9,13 +9,21 @@ import { Interception } from 'cypress/types/net-stubbing'; import 'cypress-axe'; import moment from 'moment'; import { AXE_CONFIG, AXE_OPTIONS } from '@kbn/axe-config'; +import { ApmUsername } from '../../../server/test_helpers/create_apm_users/authentication'; Cypress.Commands.add('loginAsViewerUser', () => { - return cy.loginAs({ username: 'viewer', password: 'changeme' }); + return cy.loginAs({ username: ApmUsername.viewerUser, password: 'changeme' }); }); Cypress.Commands.add('loginAsEditorUser', () => { - return cy.loginAs({ username: 'editor', password: 'changeme' }); + return cy.loginAs({ username: ApmUsername.editorUser, password: 'changeme' }); +}); + +Cypress.Commands.add('loginAsMonitorUser', () => { + return cy.loginAs({ + username: ApmUsername.apmMonitorIndices, + password: 'changeme', + }); }); Cypress.Commands.add( diff --git a/x-pack/plugins/apm/ftr_e2e/cypress/support/types.d.ts b/x-pack/plugins/apm/ftr_e2e/cypress/support/types.d.ts index 27720210b668a..2235847e584a4 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress/support/types.d.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress/support/types.d.ts @@ -9,6 +9,7 @@ declare namespace Cypress { interface Chainable { loginAsViewerUser(): Cypress.Chainable>; loginAsEditorUser(): Cypress.Chainable>; + loginAsMonitorUser(): Cypress.Chainable>; loginAs(params: { username: string; password: string; diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_test_runner.ts b/x-pack/plugins/apm/ftr_e2e/cypress_test_runner.ts index 8af466b872629..eba57b28ec0b9 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress_test_runner.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress_test_runner.ts @@ -11,7 +11,7 @@ import { esTestConfig } from '@kbn/test'; import { apm, createLogger, LogLevel } from '@kbn/apm-synthtrace'; import path from 'path'; import { FtrProviderContext } from './ftr_provider_context'; -import { createApmUsers } from '../scripts/create_apm_users/create_apm_users'; +import { createApmUsers } from '../server/test_helpers/create_apm_users/create_apm_users'; export async function cypressTestRunner({ getService }: FtrProviderContext) { const config = getService('config'); @@ -26,12 +26,6 @@ export async function cypressTestRunner({ getService }: FtrProviderContext) { const username = config.get('servers.elasticsearch.username'); const password = config.get('servers.elasticsearch.password'); - // Creates APM users - await createApmUsers({ - elasticsearch: { username, password }, - kibana: { hostname: kibanaUrl }, - }); - const esNode = Url.format({ protocol: config.get('servers.elasticsearch.protocol'), port: config.get('servers.elasticsearch.port'), @@ -39,6 +33,12 @@ export async function cypressTestRunner({ getService }: FtrProviderContext) { auth: `${username}:${password}`, }); + // Creates APM users + await createApmUsers({ + elasticsearch: { node: esNode, username, password }, + kibana: { hostname: kibanaUrl }, + }); + const esRequestTimeout = config.get('timeouts.esRequestTimeout'); const kibanaClient = new apm.ApmSynthtraceKibanaClient( createLogger(LogLevel.info) diff --git a/x-pack/plugins/apm/ftr_e2e/tsconfig.json b/x-pack/plugins/apm/ftr_e2e/tsconfig.json index 84a66afe4588d..730971a284ed5 100644 --- a/x-pack/plugins/apm/ftr_e2e/tsconfig.json +++ b/x-pack/plugins/apm/ftr_e2e/tsconfig.json @@ -18,5 +18,6 @@ "references": [ { "path": "../../../test/tsconfig.json" }, { "path": "../../../../test/tsconfig.json" }, + { "path": "../tsconfig.json" }, ] } diff --git a/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/select_services.tsx b/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/select_services.tsx index 251fa03735f16..7a97583bbd4ae 100644 --- a/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/select_services.tsx +++ b/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/select_services.tsx @@ -36,7 +36,7 @@ const CentralizedContainer = styled.div` `; const MAX_CONTAINER_HEIGHT = 600; -const MODAL_HEADER_HEIGHT = 122; +const MODAL_HEADER_HEIGHT = 180; const MODAL_FOOTER_HEIGHT = 80; const suggestedFieldsWhitelist = [ @@ -118,10 +118,73 @@ export function SelectServices({ 'xpack.apm.serviceGroups.selectServicesForm.subtitle', { defaultMessage: - 'Use a query to select services for this group. Services that match this query within the last 24 hours will be assigned to the group.', + 'Use a query to select services for this group. The preview shows services that match this query within the last 24 hours.', } )} + + + { + setKuery(value); + }} + onChange={(value) => { + setStagedKuery(value); + }} + value={kuery} + suggestionFilter={(querySuggestion) => { + if ('field' in querySuggestion) { + const { + field: { + spec: { name: fieldName }, + }, + } = querySuggestion; + + return ( + fieldName.startsWith('label') || + suggestedFieldsWhitelist.includes(fieldName) + ); + } + return true; + }} + /> + + + { + setKuery(stagedKuery); + }} + iconType={!kuery ? 'search' : 'refresh'} + isDisabled={isServiceListPreviewLoading || !stagedKuery} + > + {!kuery + ? i18n.translate( + 'xpack.apm.serviceGroups.selectServicesForm.preview', + { defaultMessage: 'Preview' } + ) + : i18n.translate( + 'xpack.apm.serviceGroups.selectServicesForm.refresh', + { defaultMessage: 'Refresh' } + )} + + + + {kuery && data?.items && ( + + {i18n.translate( + 'xpack.apm.serviceGroups.selectServicesForm.matchingServiceCount', + { + defaultMessage: + '{servicesCount} {servicesCount, plural, =0 {services} one {service} other {services}} match the query', + values: { servicesCount: data?.items.length }, + } + )} + + )} - - - - { - setKuery(value); - }} - onChange={(value) => { - setStagedKuery(value); - }} - value={kuery} - suggestionFilter={(querySuggestion) => { - if ('field' in querySuggestion) { - const { - field: { - spec: { name: fieldName }, - }, - } = querySuggestion; - - return ( - fieldName.startsWith('label') || - suggestedFieldsWhitelist.includes(fieldName) - ); - } - return true; - }} - /> - - - { - setKuery(stagedKuery); - }} - iconType={!kuery ? 'search' : 'refresh'} - isDisabled={isServiceListPreviewLoading || !stagedKuery} - > - {!kuery - ? i18n.translate( - 'xpack.apm.serviceGroups.selectServicesForm.preview', - { defaultMessage: 'Preview' } - ) - : i18n.translate( - 'xpack.apm.serviceGroups.selectServicesForm.refresh', - { defaultMessage: 'Refresh' } - )} - - - - - {kuery && data?.items && ( - - - {i18n.translate( - 'xpack.apm.serviceGroups.selectServicesForm.matchingServiceCount', - { - defaultMessage: - '{servicesCount} {servicesCount, plural, =0 {services} one {service} other {services}} match the query', - values: { servicesCount: data?.items.length }, - } - )} - - - )} {!kuery && ( diff --git a/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/service_list_preview.tsx b/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/service_list_preview.tsx index eb366b84ceefd..66105c106805a 100644 --- a/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/service_list_preview.tsx +++ b/x-pack/plugins/apm/public/components/app/service_groups/service_group_save/service_list_preview.tsx @@ -37,7 +37,7 @@ type SORT_FIELD = 'serviceName' | 'environments' | 'agentName'; export function ServiceListPreview({ items, isLoading }: Props) { const [pageIndex, setPageIndex] = useState(0); - const [pageSize, setPageSize] = useState(5); + const [pageSize, setPageSize] = useState(10); const [sortField, setSortField] = useState(DEFAULT_SORT_FIELD); const [sortDirection, setSortDirection] = useState( DEFAULT_SORT_DIRECTION diff --git a/x-pack/plugins/apm/public/components/app/service_groups/service_groups_list/index.tsx b/x-pack/plugins/apm/public/components/app/service_groups/service_groups_list/index.tsx index d0bf3a9f24b7c..734298dabe9eb 100644 --- a/x-pack/plugins/apm/public/components/app/service_groups/service_groups_list/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_groups/service_groups_list/index.tsx @@ -156,6 +156,12 @@ export function ServiceGroupsList() { + + {i18n.translate('xpack.apm.serviceGroups.listDescription', { + defaultMessage: + 'Displayed service counts reflect the last 24 hours.', + })} + {items.length ? ( diff --git a/x-pack/plugins/apm/public/components/app/storage_explorer/index_lifecycle_phase_select.tsx b/x-pack/plugins/apm/public/components/app/storage_explorer/index_lifecycle_phase_select.tsx index 124579e0562e2..10554b4ff8278 100644 --- a/x-pack/plugins/apm/public/components/app/storage_explorer/index_lifecycle_phase_select.tsx +++ b/x-pack/plugins/apm/public/components/app/storage_explorer/index_lifecycle_phase_select.tsx @@ -130,6 +130,7 @@ export function IndexLifecyclePhaseSelect() { }} hasDividers style={{ minWidth: 200 }} + data-test-subj="storageExplorerLifecyclePhaseSelect" /> ); } diff --git a/x-pack/plugins/apm/public/components/app/storage_explorer/services_table/storage_details_per_service.tsx b/x-pack/plugins/apm/public/components/app/storage_explorer/services_table/storage_details_per_service.tsx index 3d9cd14c8e958..0a101d3357684 100644 --- a/x-pack/plugins/apm/public/components/app/storage_explorer/services_table/storage_details_per_service.tsx +++ b/x-pack/plugins/apm/public/components/app/storage_explorer/services_table/storage_details_per_service.tsx @@ -186,7 +186,10 @@ export function StorageDetailsPerService({ - + - + {processorEventStats.map( ({ processorEventLabel, docs, size }) => ( <> diff --git a/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users_cli.ts b/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users_cli.ts index 194639128b4cf..24cda99fd669b 100644 --- a/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users_cli.ts +++ b/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users_cli.ts @@ -8,13 +8,17 @@ /* eslint-disable no-console */ import { argv } from 'yargs'; -import { AbortError, isAxiosError } from './helpers/call_kibana'; -import { createApmUsers } from './create_apm_users'; -import { getKibanaVersion } from './helpers/get_version'; +import { + AbortError, + isAxiosError, +} from '../../server/test_helpers/create_apm_users/helpers/call_kibana'; +import { createApmUsers } from '../../server/test_helpers/create_apm_users/create_apm_users'; +import { getKibanaVersion } from '../../server/test_helpers/create_apm_users/helpers/get_version'; async function init() { const esUserName = (argv.username as string) || 'elastic'; const esPassword = argv.password as string | undefined; + const esUrl = argv.esUrl as string | undefined; const kibanaBaseUrl = argv.kibanaUrl as string | undefined; if (!esPassword) { @@ -24,6 +28,20 @@ async function init() { process.exit(); } + if (!esUrl) { + console.error( + 'Please specify the url for elasticsearch: `--es-url http://localhost:9200` ' + ); + process.exit(); + } + + if (!esUrl.startsWith('https://') && !esUrl.startsWith('http://')) { + console.error( + 'Elasticsearch url must be prefixed with http(s):// `--es-url http://localhost:9200`' + ); + process.exit(); + } + if (!kibanaBaseUrl) { console.error( 'Please specify the url for Kibana: `--kibana-url http://localhost:5601` ' @@ -42,7 +60,11 @@ async function init() { } const kibana = { hostname: kibanaBaseUrl }; - const elasticsearch = { username: esUserName, password: esPassword }; + const elasticsearch = { + node: esUrl, + username: esUserName, + password: esPassword, + }; console.log({ kibana, elasticsearch }); @@ -50,9 +72,7 @@ async function init() { console.log(`Connected to Kibana ${version}`); const users = await createApmUsers({ elasticsearch, kibana }); - const credentials = users - .map((u) => ` - ${u.username} / ${esPassword}`) - .join('\n'); + const credentials = users.map((u) => ` - ${u} / ${esPassword}`).join('\n'); console.log( `\nYou can now login to ${kibana.hostname} with:\n${credentials}` diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts index 167fb0d57208f..430930fb3f916 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts @@ -6,6 +6,7 @@ */ import { fromKueryExpression } from '@kbn/es-query'; import { flatten, merge, sortBy, sum, pickBy } from 'lodash'; +import { createHash } from 'crypto'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; @@ -1247,11 +1248,15 @@ export const tasks: TelemetryTask[] = [ }); const envBuckets = response.aggregations?.environments.buckets ?? []; const data: APMPerService[] = envBuckets.flatMap((envBucket) => { - const env = envBucket.key; + const envHash = createHash('sha256') + .update(envBucket.key as string) + .digest('hex'); const serviceBuckets = envBucket.service_names?.buckets ?? []; return serviceBuckets.map((serviceBucket) => { - const name = serviceBucket.key; - const fullServiceName = `${env}~${name}`; + const nameHash = createHash('sha256') + .update(serviceBucket.key as string) + .digest('hex'); + const fullServiceName = `${nameHash}~${envHash}`; return { service_id: fullServiceName, timed_out: response.timed_out, diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client.ts new file mode 100644 index 0000000000000..4cd9df6bf2137 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ESSearchRequest, InferSearchResponseOf } from '@kbn/es-types'; +import { APMRouteHandlerResources } from '../../../../routes/typings'; +import { getInfraMetricIndices } from '../../get_infra_metric_indices'; + +type InfraMetricsSearchParams = Omit; + +export type InfraMetricsClient = ReturnType; + +export function createInfraMetricsClient(resources: APMRouteHandlerResources) { + return { + async search( + opts: TParams + ): Promise> { + const { + savedObjects: { client: savedObjectsClient }, + elasticsearch: { client: esClient }, + } = await resources.context.core; + + const indexName = await getInfraMetricIndices({ + infraPlugin: resources.plugins.infra, + savedObjectsClient, + }); + + const searchParams = { + index: [indexName], + ...opts, + }; + + return esClient.asCurrentUser.search( + searchParams + ) as Promise; + }, + }; +} diff --git a/x-pack/plugins/apm/server/routes/infrastructure/get_host_names.ts b/x-pack/plugins/apm/server/routes/infrastructure/get_host_names.ts index 4890f8ab909eb..8f47c2d1664bf 100644 --- a/x-pack/plugins/apm/server/routes/infrastructure/get_host_names.ts +++ b/x-pack/plugins/apm/server/routes/infrastructure/get_host_names.ts @@ -5,106 +5,55 @@ * 2.0. */ -import { ElasticsearchClient } from '@kbn/core/server'; import { rangeQuery } from '@kbn/observability-plugin/server'; -import { InfraPluginStart, InfraPluginSetup } from '@kbn/infra-plugin/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { CONTAINER_ID, HOST_NAME, } from '../../../common/elasticsearch_fieldnames'; -import { ApmPluginRequestHandlerContext } from '../typings'; -import { getInfraMetricIndices } from '../../lib/helpers/get_infra_metric_indices'; +import { InfraMetricsClient } from '../../lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client'; -interface Aggs extends estypes.AggregationsMultiBucketAggregateBase { - buckets: Array<{ - key: string; - key_as_string?: string; - }>; -} - -interface InfraPlugin { - setup: InfraPluginSetup; - start: () => Promise; -} - -const getHostNames = async ({ - esClient, +export async function getContainerHostNames({ containerIds, - index, + infraMetricsClient, start, end, }: { - esClient: ElasticsearchClient; containerIds: string[]; - index: string; + infraMetricsClient: InfraMetricsClient; start: number; end: number; -}) => { - const response = await esClient.search({ - index: [index], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - [CONTAINER_ID]: containerIds, - }, +}): Promise { + if (!containerIds.length) { + return []; + } + + const response = await infraMetricsClient.search({ + size: 0, + query: { + bool: { + filter: [ + { + terms: { + [CONTAINER_ID]: containerIds, }, - ...rangeQuery(start, end), - ], - }, - }, - aggs: { - hostNames: { - terms: { - field: HOST_NAME, - size: 500, }, + ...rangeQuery(start, end), + ], + }, + }, + aggs: { + hostNames: { + terms: { + field: HOST_NAME, + size: 500, }, }, }, }); - return { - hostNames: - response.aggregations?.hostNames?.buckets.map( - (bucket) => bucket.key as string - ) ?? [], - }; -}; + const hostNames = response.aggregations?.hostNames?.buckets.map( + (bucket) => bucket.key as string + ); -export const getContainerHostNames = async ({ - containerIds, - context, - infra, - start, - end, -}: { - containerIds: string[]; - context: ApmPluginRequestHandlerContext; - infra: InfraPlugin; - start: number; - end: number; -}): Promise => { - if (containerIds.length) { - const esClient = (await context.core).elasticsearch.client.asCurrentUser; - const savedObjectsClient = (await context.core).savedObjects.client; - const metricIndices = await getInfraMetricIndices({ - infraPlugin: infra, - savedObjectsClient, - }); - - const containerHostNames = await getHostNames({ - esClient, - containerIds, - index: metricIndices, - start, - end, - }); - return containerHostNames.hostNames; - } - return []; -}; + return hostNames ?? []; +} diff --git a/x-pack/plugins/apm/server/routes/infrastructure/route.ts b/x-pack/plugins/apm/server/routes/infrastructure/route.ts index 756b29d5d4571..678f380bc4fd8 100644 --- a/x-pack/plugins/apm/server/routes/infrastructure/route.ts +++ b/x-pack/plugins/apm/server/routes/infrastructure/route.ts @@ -10,6 +10,7 @@ import { setupRequest } from '../../lib/helpers/setup_request'; import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; import { getInfrastructureData } from './get_infrastructure_data'; import { getContainerHostNames } from './get_host_names'; +import { createInfraMetricsClient } from '../../lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client'; const infrastructureRoute = createApmServerRoute({ endpoint: @@ -29,12 +30,9 @@ const infrastructureRoute = createApmServerRoute({ podNames: string[]; }> => { const setup = await setupRequest(resources); + const infraMetricsClient = createInfraMetricsClient(resources); - const { - context, - params, - plugins: { infra }, - } = resources; + const { params } = resources; const { path: { serviceName }, @@ -54,8 +52,7 @@ const infrastructureRoute = createApmServerRoute({ // due some limitations on the data we get from apm-metrics indices, if we have a service running in a container we want to query, to get the host.name, filtering by container.id const containerHostNames = await getContainerHostNames({ containerIds, - context, - infra, + infraMetricsClient, start, end, }); diff --git a/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts b/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts index 880e3d2488898..c820cdd8445fc 100644 --- a/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts +++ b/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts @@ -7,50 +7,72 @@ import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { rangeQuery, kqlQuery } from '@kbn/observability-plugin/server'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { Setup } from '../../lib/helpers/setup_request'; import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; +import { SavedServiceGroup } from '../../../common/service_groups'; export async function getServicesCounts({ setup, - kuery, - maxNumberOfServices, start, end, + serviceGroups, }: { setup: Setup; - kuery: string; - maxNumberOfServices: number; start: number; end: number; + serviceGroups: SavedServiceGroup[]; }) { const { apmEventClient } = setup; - const response = await apmEventClient.search('get_services_count', { + const serviceGroupsKueryMap: Record = + serviceGroups.reduce((acc, sg) => { + return { + ...acc, + [sg.id]: kqlQuery(sg.kuery)[0], + }; + }, {}); + + const params = { apm: { - events: [ - ProcessorEvent.metric, - ProcessorEvent.transaction, - ProcessorEvent.span, - ProcessorEvent.error, - ], + // We're limiting the service count to only metrics documents. If a user + // actively disables system/app metrics and a service only ingests error + // events, that service will not be included in the service groups count. + // This is an edge case that only effects the count preview label. + events: [ProcessorEvent.metric], }, body: { track_total_hits: 0, size: 0, query: { bool: { - filter: [...rangeQuery(start, end), ...kqlQuery(kuery)], + filter: rangeQuery(start, end), }, }, aggs: { - services_count: { - cardinality: { - field: SERVICE_NAME, + service_groups: { + filters: { + filters: serviceGroupsKueryMap, + }, + aggs: { + services_count: { + cardinality: { + field: SERVICE_NAME, + }, + }, }, }, }, }, - }); + }; + const response = await apmEventClient.search('get_services_count', params); - return response?.aggregations?.services_count.value ?? 0; + const buckets: Record = + response?.aggregations?.service_groups.buckets ?? {}; + return Object.keys(buckets).reduce((acc, key) => { + return { + ...acc, + [key]: buckets[key].services_count.value, + }; + }, {}); } diff --git a/x-pack/plugins/apm/server/routes/service_groups/route.ts b/x-pack/plugins/apm/server/routes/service_groups/route.ts index ff37dc1f1c16a..4430aaae760eb 100644 --- a/x-pack/plugins/apm/server/routes/service_groups/route.ts +++ b/x-pack/plugins/apm/server/routes/service_groups/route.ts @@ -7,7 +7,6 @@ import * as t from 'io-ts'; import { apmServiceGroupMaxNumberOfServices } from '@kbn/observability-plugin/common'; -import { keyBy, mapValues } from 'lodash'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { kueryRt, rangeRt } from '../default_api_types'; @@ -52,50 +51,26 @@ const serviceGroupsWithServiceCountRoute = createApmServerRoute({ const { context, params } = resources; const { savedObjects: { client: savedObjectsClient }, - uiSettings: { client: uiSettingsClient }, } = await context.core; const { query: { start, end }, } = params; - const [setup, maxNumberOfServices] = await Promise.all([ - setupRequest(resources), - uiSettingsClient.get(apmServiceGroupMaxNumberOfServices), - ]); + const setup = await setupRequest(resources); const serviceGroups = await getServiceGroups({ savedObjectsClient, }); - const serviceGroupsWithServiceCount = await Promise.all( - serviceGroups.map( - async ({ - id, - kuery, - }): Promise<{ id: string; servicesCount: number }> => { - const servicesCount = await getServicesCounts({ - setup, - kuery, - maxNumberOfServices, - start, - end, - }); - - return { - id, - servicesCount, - }; - } - ) - ); - - const servicesCounts = mapValues( - keyBy(serviceGroupsWithServiceCount, 'id'), - 'servicesCount' - ); - - return { servicesCounts }; + return { + servicesCounts: await getServicesCounts({ + setup, + serviceGroups, + start, + end, + }), + }; }, }); diff --git a/x-pack/plugins/apm/server/routes/services/get_service_instance_container_metadata.ts b/x-pack/plugins/apm/server/routes/services/get_service_instance_container_metadata.ts index 729c2f1f1b1eb..ebce4f9338714 100644 --- a/x-pack/plugins/apm/server/routes/services/get_service_instance_container_metadata.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instance_container_metadata.ts @@ -5,10 +5,8 @@ * 2.0. */ -import { ElasticsearchClient } from '@kbn/core/server'; import { rangeQuery } from '@kbn/observability-plugin/server'; import { - CONTAINER, CONTAINER_ID, CONTAINER_IMAGE, KUBERNETES, @@ -21,6 +19,7 @@ import { } from '../../../common/elasticsearch_fieldnames'; import { Kubernetes } from '../../../typings/es_schemas/raw/fields/kubernetes'; import { maybe } from '../../../common/utils/maybe'; +import { InfraMetricsClient } from '../../lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client'; type ServiceInstanceContainerMetadataDetails = | { @@ -29,22 +28,16 @@ type ServiceInstanceContainerMetadataDetails = | undefined; export const getServiceInstanceContainerMetadata = async ({ - esClient, - indexName, + infraMetricsClient, containerId, start, end, }: { - esClient: ElasticsearchClient; - indexName?: string; + infraMetricsClient: InfraMetricsClient; containerId: string; start: number; end: number; }): Promise => { - if (!indexName) { - return undefined; - } - const should = [ { exists: { field: KUBERNETES } }, { exists: { field: CONTAINER_IMAGE } }, @@ -56,9 +49,7 @@ export const getServiceInstanceContainerMetadata = async ({ { exists: { field: KUBERNETES_DEPLOYMENT_NAME } }, ]; - const response = await esClient.search({ - index: [indexName], - _source: [KUBERNETES, CONTAINER], + const response = await infraMetricsClient.search({ size: 1, query: { bool: { diff --git a/x-pack/plugins/apm/server/routes/services/get_service_overview_container_metadata.ts b/x-pack/plugins/apm/server/routes/services/get_service_overview_container_metadata.ts index 5b267e4faa3fc..c1dcfe97e208b 100644 --- a/x-pack/plugins/apm/server/routes/services/get_service_overview_container_metadata.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_overview_container_metadata.ts @@ -5,10 +5,8 @@ * 2.0. */ -import { ElasticsearchClient } from '@kbn/core/server'; import { rangeQuery } from '@kbn/observability-plugin/server'; import { - CONTAINER, CONTAINER_ID, CONTAINER_IMAGE, KUBERNETES, @@ -19,43 +17,19 @@ import { KUBERNETES_REPLICASET_NAME, KUBERNETES_DEPLOYMENT_NAME, } from '../../../common/elasticsearch_fieldnames'; - -type ServiceOverviewContainerMetadataDetails = - | { - kubernetes: { - deployments?: string[]; - replicasets?: string[]; - namespaces?: string[]; - containerImages?: string[]; - }; - } - | undefined; - -interface ResponseAggregations { - [key: string]: { - buckets: Array<{ - key: string; - }>; - }; -} +import { InfraMetricsClient } from '../../lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client'; export const getServiceOverviewContainerMetadata = async ({ - esClient, - indexName, + infraMetricsClient, containerIds, start, end, }: { - esClient: ElasticsearchClient; - indexName?: string; + infraMetricsClient: InfraMetricsClient; containerIds: string[]; start: number; end: number; -}): Promise => { - if (!indexName) { - return undefined; - } - +}) => { const should = [ { exists: { field: KUBERNETES } }, { exists: { field: CONTAINER_IMAGE } }, @@ -67,9 +41,7 @@ export const getServiceOverviewContainerMetadata = async ({ { exists: { field: KUBERNETES_DEPLOYMENT_NAME } }, ]; - const response = await esClient.search({ - index: [indexName], - _source: [KUBERNETES, CONTAINER], + const response = await infraMetricsClient.search({ size: 0, query: { bool: { diff --git a/x-pack/plugins/apm/server/routes/services/route.ts b/x-pack/plugins/apm/server/routes/services/route.ts index 6b73d72367d0f..79ff09101aeca 100644 --- a/x-pack/plugins/apm/server/routes/services/route.ts +++ b/x-pack/plugins/apm/server/routes/services/route.ts @@ -55,7 +55,8 @@ import { ServiceHealthStatus } from '../../../common/service_health_status'; import { getServiceGroup } from '../service_groups/get_service_group'; import { offsetRt } from '../../../common/comparison_rt'; import { getRandomSampler } from '../../lib/helpers/get_random_sampler'; -import { getInfraMetricIndices } from '../../lib/helpers/get_infra_metric_indices'; +import { createInfraMetricsClient } from '../../lib/helpers/create_es_client/create_infra_metrics_client/create_infra_metrics_client'; + const servicesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services', params: t.type({ @@ -274,7 +275,8 @@ const serviceMetadataDetailsRoute = createApmServerRoute({ import('./get_service_metadata_details').ServiceMetadataDetails > => { const setup = await setupRequest(resources); - const { params, context, plugins } = resources; + const infraMetricsClient = createInfraMetricsClient(resources); + const { params } = resources; const { serviceName } = params.path; const { start, end } = params.query; @@ -295,19 +297,8 @@ const serviceMetadataDetailsRoute = createApmServerRoute({ }); if (serviceMetadataDetails?.container?.ids) { - const { - savedObjects: { client: savedObjectsClient }, - elasticsearch: { client: esClient }, - } = await context.core; - - const indexName = await getInfraMetricIndices({ - infraPlugin: plugins.infra, - savedObjectsClient, - }); - const containerMetadata = await getServiceOverviewContainerMetadata({ - esClient: esClient.asCurrentUser, - indexName, + infraMetricsClient, containerIds: serviceMetadataDetails.container.ids, start, end, @@ -911,7 +902,8 @@ export const serviceInstancesMetadataDetails = createApmServerRoute({ | undefined; }> => { const setup = await setupRequest(resources); - const { params, context, plugins } = resources; + const infraMetricsClient = createInfraMetricsClient(resources); + const { params } = resources; const { serviceName, serviceNodeName } = params.path; const { start, end } = params.query; @@ -925,19 +917,8 @@ export const serviceInstancesMetadataDetails = createApmServerRoute({ }); if (serviceInstanceMetadataDetails?.container?.id) { - const { - savedObjects: { client: savedObjectsClient }, - elasticsearch: { client: esClient }, - } = await context.core; - - const indexName = await getInfraMetricIndices({ - infraPlugin: plugins.infra, - savedObjectsClient, - }); - const containerMetadata = await getServiceInstanceContainerMetadata({ - esClient: esClient.asCurrentUser, - indexName, + infraMetricsClient, containerId: serviceInstanceMetadataDetails.container.id, start, end, diff --git a/x-pack/test/apm_api_integration/common/authentication.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/authentication.ts similarity index 61% rename from x-pack/test/apm_api_integration/common/authentication.ts rename to x-pack/plugins/apm/server/test_helpers/create_apm_users/authentication.ts index 93bae236d5dc5..f3d15ee6db21e 100644 --- a/x-pack/test/apm_api_integration/common/authentication.ts +++ b/x-pack/plugins/apm/server/test_helpers/create_apm_users/authentication.ts @@ -5,15 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; -import { PrivilegeType } from '@kbn/apm-plugin/common/privilege_type'; -import { ToolingLog } from '@kbn/tooling-log'; -import { omit } from 'lodash'; -import { KbnClientRequesterError } from '@kbn/test'; -import { AxiosError } from 'axios'; -import { SecurityServiceProvider } from '../../../../test/common/services/security'; - -type SecurityService = Awaited>; +import { PrivilegeType } from '../../../common/privilege_type'; export enum ApmUsername { noAccessUser = 'no_access_user', @@ -34,7 +26,7 @@ export enum ApmCustomRolename { apmMonitorIndices = 'apm_monitor_indices', } -const customRoles = { +export const customRoles = { [ApmCustomRolename.apmReadUserWithoutMlAccess]: { elasticsearch: { cluster: [], @@ -97,7 +89,7 @@ const customRoles = { }, }; -const users: Record< +export const users: Record< ApmUsername, { builtInRoleNames?: string[]; customRoleNames?: ApmCustomRolename[] } > = { @@ -132,70 +124,4 @@ const users: Record< }, }; -function logErrorResponse(logger: ToolingLog, e: Error) { - if (e instanceof KbnClientRequesterError) { - logger.error(`KbnClientRequesterError: ${JSON.stringify(e.axiosError?.response?.data)}`); - } else if (e instanceof AxiosError) { - logger.error(`AxiosError: ${JSON.stringify(e.response?.data)}`); - } else { - logger.error(`Unknown error: ${e.constructor.name}`); - } -} - -export async function createApmUser({ - username, - security, - es, - logger, -}: { - username: ApmUsername; - security: SecurityService; - es: Client; - logger: ToolingLog; -}) { - const user = users[username]; - - if (!user) { - throw new Error(`No configuration found for ${username}`); - } - - const { builtInRoleNames = [], customRoleNames = [] } = user; - - try { - // create custom roles - await Promise.all( - customRoleNames.map(async (roleName) => createCustomRole({ roleName, security, es })) - ); - - // create user - await security.user.create(username, { - full_name: username, - password: APM_TEST_PASSWORD, - roles: [...builtInRoleNames, ...customRoleNames], - }); - } catch (e) { - logErrorResponse(logger, e); - throw e; - } -} - -async function createCustomRole({ - roleName, - security, - es, -}: { - roleName: ApmCustomRolename; - security: SecurityService; - es: Client; -}) { - const role = customRoles[roleName]; - - // Add application privileges with es client as they are not supported by - // security.user.create. They are preserved when updating the role below - if ('applications' in role) { - await es.security.putRole({ name: roleName, body: role }); - } - await security.role.create(roleName, omit(role, 'applications')); -} - export const APM_TEST_PASSWORD = 'changeme'; diff --git a/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/create_apm_users.ts similarity index 69% rename from x-pack/plugins/apm/scripts/create_apm_users/create_apm_users.ts rename to x-pack/plugins/apm/server/test_helpers/create_apm_users/create_apm_users.ts index 7532392c9a8b4..8e9e39373752b 100644 --- a/x-pack/plugins/apm/scripts/create_apm_users/create_apm_users.ts +++ b/x-pack/plugins/apm/server/test_helpers/create_apm_users/create_apm_users.ts @@ -5,10 +5,13 @@ * 2.0. */ +import { asyncForEach } from '@kbn/std'; import { AbortError, callKibana } from './helpers/call_kibana'; import { createOrUpdateUser } from './helpers/create_or_update_user'; - +import { ApmUsername, users } from './authentication'; +import { createCustomRole } from './helpers/create_custom_role'; export interface Elasticsearch { + node: string; username: string; password: string; } @@ -28,6 +31,7 @@ export async function createApmUsers({ elasticsearch, kibana, }); + if (!isCredentialsValid) { throw new AbortError('Invalid username/password'); } @@ -36,24 +40,33 @@ export async function createApmUsers({ elasticsearch, kibana, }); + if (!isSecurityEnabled) { throw new AbortError('Security must be enabled!'); } - // user definitions - const users = [ - { username: 'viewer', roles: ['viewer'] }, - { username: 'editor', roles: ['editor'] }, - ]; + const apmUsers = Object.values(ApmUsername); + await asyncForEach(apmUsers, async (username) => { + const user = users[username]; + const { builtInRoleNames = [], customRoleNames = [] } = user; + + // create custom roles + await Promise.all( + customRoleNames.map(async (roleName) => + createCustomRole({ elasticsearch, kibana, roleName }) + ) + ); - // create users - await Promise.all( - users.map(async (user) => - createOrUpdateUser({ elasticsearch, kibana, user }) - ) - ); + // create user + const roles = builtInRoleNames.concat(customRoleNames); + await createOrUpdateUser({ + elasticsearch, + kibana, + user: { username, roles }, + }); + }); - return users; + return apmUsers; } async function getIsSecurityEnabled({ diff --git a/x-pack/plugins/apm/scripts/create_apm_users/helpers/call_kibana.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/call_kibana.ts similarity index 97% rename from x-pack/plugins/apm/scripts/create_apm_users/helpers/call_kibana.ts rename to x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/call_kibana.ts index 1e6bd2e02c416..72312645a644e 100644 --- a/x-pack/plugins/apm/scripts/create_apm_users/helpers/call_kibana.ts +++ b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/call_kibana.ts @@ -13,7 +13,7 @@ export async function callKibana({ kibana, options, }: { - elasticsearch: Elasticsearch; + elasticsearch: Omit; kibana: Kibana; options: AxiosRequestConfig; }): Promise { diff --git a/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts new file mode 100644 index 0000000000000..ac906fcbfb5e2 --- /dev/null +++ b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Client } from '@elastic/elasticsearch'; +import { omit } from 'lodash'; +import { Elasticsearch, Kibana } from '../create_apm_users'; +import { callKibana } from './call_kibana'; +import { customRoles, ApmCustomRolename } from '../authentication'; + +export async function createCustomRole({ + elasticsearch, + kibana, + roleName, +}: { + elasticsearch: Elasticsearch; + kibana: Kibana; + roleName: ApmCustomRolename; +}) { + const role = customRoles[roleName]; + + // Add application privileges with es client as they are not supported by + // the security API. They are preserved when updating the role below + if ('applications' in role) { + const esClient = getEsClient(elasticsearch); + await esClient.security.putRole({ name: roleName, body: role }); + } + + await callKibana({ + elasticsearch, + kibana, + options: { + method: 'PUT', + url: `/api/security/role/${roleName}`, + data: { + ...omit(role, 'applications'), + }, + }, + }); +} + +export function getEsClient(elasticsearch: Elasticsearch) { + const { node, username, password } = elasticsearch; + const client = new Client({ + node, + tls: { + rejectUnauthorized: false, + }, + requestTimeout: 120000, + auth: { + username, + password, + }, + }); + + return client; +} diff --git a/x-pack/plugins/apm/scripts/create_apm_users/helpers/create_or_update_user.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/create_or_update_user.ts similarity index 100% rename from x-pack/plugins/apm/scripts/create_apm_users/helpers/create_or_update_user.ts rename to x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/create_or_update_user.ts diff --git a/x-pack/plugins/apm/scripts/create_apm_users/helpers/get_version.ts b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/get_version.ts similarity index 96% rename from x-pack/plugins/apm/scripts/create_apm_users/helpers/get_version.ts rename to x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/get_version.ts index a809efe7402ea..a00747ae78582 100644 --- a/x-pack/plugins/apm/scripts/create_apm_users/helpers/get_version.ts +++ b/x-pack/plugins/apm/server/test_helpers/create_apm_users/helpers/get_version.ts @@ -13,7 +13,7 @@ export async function getKibanaVersion({ elasticsearch, kibana, }: { - elasticsearch: Elasticsearch; + elasticsearch: Omit; kibana: Kibana; }) { try { diff --git a/x-pack/plugins/banners/server/ui_settings.test.ts b/x-pack/plugins/banners/server/ui_settings.test.ts index f83ef6f4bba59..10cf250cc7468 100644 --- a/x-pack/plugins/banners/server/ui_settings.test.ts +++ b/x-pack/plugins/banners/server/ui_settings.test.ts @@ -13,7 +13,7 @@ const createConfig = (parts: Partial = {}): BannersConfigType placement: 'disabled', backgroundColor: '#0000', textColor: '#FFFFFF', - textContent: 'Hello from the banner', + textContent: 'some global banner text', disableSpaceBanners: false, ...parts, }); @@ -31,7 +31,9 @@ describe('registerSettings', () => { expect(uiSettings.register).toHaveBeenCalledTimes(1); expect(uiSettings.register).toHaveBeenCalledWith({ 'banners:placement': expect.any(Object), - 'banners:textContent': expect.any(Object), + 'banners:textContent': expect.objectContaining({ + value: 'some global banner text', + }), 'banners:textColor': expect.any(Object), 'banners:backgroundColor': expect.any(Object), }); diff --git a/x-pack/plugins/cases/common/ui/types.ts b/x-pack/plugins/cases/common/ui/types.ts index 9af253fc9559e..65a7fec902f7b 100644 --- a/x-pack/plugins/cases/common/ui/types.ts +++ b/x-pack/plugins/cases/common/ui/types.ts @@ -82,6 +82,7 @@ export type Case = Omit, 'comments'> & { comments export type Cases = Omit, 'cases'> & { cases: Case[] }; export type CasesStatus = SnakeToCamelCase; export type CasesMetrics = SnakeToCamelCase; +export type CaseUpdateRequest = SnakeToCamelCase; export interface ResolvedCase { case: Case; @@ -133,12 +134,6 @@ export interface ApiProps { signal: AbortSignal; } -export interface BulkUpdateStatus { - status: string; - id: string; - version: string; -} - export interface ActionLicense { id: string; name: string; @@ -147,11 +142,6 @@ export interface ActionLicense { enabledInLicense: boolean; } -export interface DeleteCase { - id: string; - title: string; -} - export interface FieldMappings { id: string; title?: string; diff --git a/x-pack/plugins/cases/docs/openapi/bundled.json b/x-pack/plugins/cases/docs/openapi/bundled.json index 3822f2f458a0b..4202c658ee4ff 100644 --- a/x-pack/plugins/cases/docs/openapi/bundled.json +++ b/x-pack/plugins/cases/docs/openapi/bundled.json @@ -29,4052 +29,13 @@ } ], "paths": { - "/api/cases": { - "post": { - "summary": "Creates a case in the default space.", - "operationId": "createCaseDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're creating.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "connector": { - "description": "An object that contains the connector configuration.", - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - }, - "required": [ - "fields", - "id", - "name", - "type" - ] - }, - "description": { - "description": "The description for the case.", - "type": "string" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "tags": { - "description": "The words and phrases that help categorize cases. It can be an empty array.", - "type": "array", - "items": { - "type": "string" - } - }, - "title": { - "description": "A title for the case.", - "type": "string" - } - }, - "required": [ - "connector", - "description", - "owner", - "settings", - "tags", - "title" - ] - }, - "examples": { - "createCaseRequest": { - "$ref": "#/components/examples/create_case_request" - } - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "createCaseResponse": { - "$ref": "#/components/examples/create_case_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "delete": { - "summary": "Deletes one or more cases from the default space.", - "operationId": "deleteCaseDefaultSpace", - "description": "You must have `read` or `all` privileges and the `delete` sub-feature privilege for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "name": "ids", - "description": "The cases that you want to removed. To retrieve case IDs, use the find cases API. All non-ASCII characters must be URL encoded.", - "in": "query", - "required": true, - "schema": { - "type": "string" - }, - "example": "d4e7abb0-b462-11ec-9a8d-698504725a43" - } - ], - "responses": { - "204": { - "description": "Indicates a successful call." - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "patch": { - "summary": "Updates one or more cases in the default space.", - "operationId": "updateCaseDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're updating.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "cases": { - "type": "array", - "items": { - "type": "object", - "properties": { - "connector": { - "description": "An object that contains the connector configuration.", - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - }, - "required": [ - "fields", - "id", - "name", - "type" - ] - }, - "description": { - "description": "The description for the case.", - "type": "string" - }, - "id": { - "description": "The identifier for the case.", - "type": "string" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "description": "The words and phrases that help categorize cases.", - "type": "array", - "items": { - "type": "string" - } - }, - "title": { - "description": "A title for the case.", - "type": "string" - }, - "version": { - "description": "The current version of the case.", - "type": "string" - } - }, - "required": [ - "id", - "version" - ] - } - } - } - }, - "examples": { - "updateCaseRequest": { - "$ref": "#/components/examples/update_case_request" - } - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "updateCaseResponse": { - "$ref": "#/components/examples/update_case_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/_find": { - "get": { - "summary": "Retrieves a paginated subset of cases from the default space.", - "operationId": "getCasesDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "name": "defaultSearchOperator", - "in": "query", - "description": "The default operator to use for the simple_query_string.", - "schema": { - "type": "string", - "default": "OR" - }, - "example": "OR" - }, - { - "name": "fields", - "in": "query", - "description": "The fields in the entity to return in the response.", - "schema": { - "type": "array", - "items": { - "type": "string" - } - } - }, - { - "name": "from", - "in": "query", - "description": "[preview] Returns only cases that were created after a specific date. The date must be specified as a KQL data range or date match expression. This functionality is in technical preview and may be changed or removed in a future release. Elastic will apply best effort to fix any issues, but features in technical preview are not subject to the support SLA of official GA features.\n", - "schema": { - "type": "string" - }, - "example": "now-1d", - "x-technical-preview": true - }, - { - "$ref": "#/components/parameters/owner" - }, - { - "name": "page", - "in": "query", - "description": "The page number to return.", - "schema": { - "type": "integer", - "default": 1 - }, - "example": 1 - }, - { - "name": "perPage", - "in": "query", - "description": "The number of rules to return per page.", - "schema": { - "type": "integer", - "default": 20 - }, - "example": 20 - }, - { - "name": "reporters", - "in": "query", - "description": "Filters the returned cases by the user name of the reporter.", - "schema": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "example": "elastic" - }, - { - "name": "search", - "in": "query", - "description": "An Elasticsearch simple_query_string query that filters the objects in the response.", - "schema": { - "type": "string" - } - }, - { - "name": "searchFields", - "in": "query", - "description": "The fields to perform the simple_query_string parsed query against.", - "schema": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - } - }, - { - "$ref": "#/components/parameters/severity" - }, - { - "name": "sortField", - "in": "query", - "description": "Determines which field is used to sort the results.", - "schema": { - "type": "string", - "enum": [ - "createdAt", - "updatedAt" - ], - "default": "createdAt" - }, - "example": "updatedAt" - }, - { - "name": "sortOrder", - "in": "query", - "description": "Determines the sort order.", - "schema": { - "type": "string", - "enum": [ - "asc", - "desc" - ], - "default": "desc" - }, - "example": "asc" - }, - { - "in": "query", - "name": "status", - "description": "Filters the returned cases by state.", - "schema": { - "type": "string", - "enum": [ - "closed", - "in-progress", - "open" - ] - }, - "example": "open" - }, - { - "name": "tags", - "in": "query", - "description": "Filters the returned cases by tags.", - "schema": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "example": "tag-1" - }, - { - "name": "to", - "in": "query", - "description": "Returns only cases that were created before a specific date. The date must be specified as a KQL data range or date match expression.", - "schema": { - "type": "string" - }, - "example": "now%2B1d", - "x-technical-preview": true - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "cases": { - "type": "array", - "items": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - } - }, - "count_closed_cases": { - "type": "integer" - }, - "count_in_progress_cases": { - "type": "integer" - }, - "count_open_cases": { - "type": "integer" - }, - "page": { - "type": "integer" - }, - "per_page": { - "type": "integer" - }, - "total": { - "type": "integer" - } - } - }, - "examples": { - "findCaseResponse": { - "$ref": "#/components/examples/find_case_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/alerts/{alertId}": { - "get": { - "summary": "Returns the cases associated with a specific alert in the default space.", - "operationId": "getCasesByAlertDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", - "x-technical-preview": true, - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/alert_id" - }, - { - "$ref": "#/components/parameters/owner" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The case identifier." - }, - "title": { - "type": "string", - "description": "The case title." - } - } - }, - "example": [ - { - "id": "06116b80-e1c3-11ec-be9b-9b1838238ee6", - "title": "security_case" - } - ] - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/configure": { - "get": { - "summary": "Retrieves external connection details, such as the closure type and default connector for cases in the default space.", - "operationId": "getCaseConfigurationDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/owner" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "closure_type": { - "$ref": "#/components/schemas/closure_types" - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-06-01T17:07:17.767Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - } - }, - "error": { - "type": "string", - "example": null - }, - "id": { - "type": "string", - "example": "4a97a440-e1cd-11ec-be9b-9b1838238ee6" - }, - "mappings": { - "type": "array", - "items": { - "type": "object", - "properties": { - "action_type": { - "type": "string", - "example": "overwrite" - }, - "source": { - "type": "string", - "example": "title" - }, - "target": { - "type": "string", - "example": "summary" - } - } - } - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": "2022-06-01T19:58:48.169Z" - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - }, - "nullable": true - }, - "version": { - "type": "string", - "example": "WzIwNzMsMV0=" - } - } - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "post": { - "summary": "Sets external connection details, such as the closure type and default connector for cases in the default space.", - "operationId": "setCaseConfigurationDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration. Connectors are used to interface with external systems. You must create a connector before you can use it in your cases. Refer to the add connectors API. If you set a default connector, it is automatically selected when you create cases in Kibana. If you use the create case API, however, you must still specify all of the connector details.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "closure_type": { - "$ref": "#/components/schemas/closure_types" - }, - "connector": { - "description": "An object that contains the connector configuration.", - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - }, - "required": [ - "fields", - "id", - "name", - "type" - ] - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "description": "An object that contains the case settings.", - "type": "object", - "properties": { - "syncAlerts": { - "description": "Turns alert syncing on or off.", - "type": "boolean", - "example": true - } - }, - "required": [ - "syncAlerts" - ] - } - }, - "required": [ - "closure_type", - "connector", - "owner" - ] - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "closure_type": { - "$ref": "#/components/schemas/closure_types" - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-06-01T17:07:17.767Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - } - }, - "error": { - "type": "string", - "example": null - }, - "id": { - "type": "string", - "example": "4a97a440-e1cd-11ec-be9b-9b1838238ee6" - }, - "mappings": { - "type": "array", - "items": { - "type": "object", - "properties": { - "action_type": { - "type": "string", - "example": "overwrite" - }, - "source": { - "type": "string", - "example": "title" - }, - "target": { - "type": "string", - "example": "summary" - } - } - } - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": "2022-06-01T19:58:48.169Z" - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - }, - "nullable": true - }, - "version": { - "type": "string", - "example": "WzIwNzMsMV0=" - } - } - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/configure/{configurationId}": { - "patch": { - "summary": "Updates external connection details, such as the closure type and default connector for cases in the default space.", - "operationId": "updateCaseConfigurationDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration. Connectors are used to interface with external systems. You must create a connector before you can use it in your cases. Refer to the add connectors API.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "$ref": "#/components/parameters/configuration_id" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "closure_type": { - "$ref": "#/components/schemas/closure_types" - }, - "connector": { - "description": "An object that contains the connector configuration.", - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - }, - "required": [ - "fields", - "id", - "name", - "type" - ] - }, - "version": { - "description": "The version of the connector. To retrieve the version value, use the get configuration API.\n", - "type": "string", - "example": "WzIwMiwxXQ==" - } - }, - "required": [ - "version" - ] - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "closure_type": { - "$ref": "#/components/schemas/closure_types" - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-06-01T17:07:17.767Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - } - }, - "error": { - "type": "string", - "example": null - }, - "id": { - "type": "string", - "example": "4a97a440-e1cd-11ec-be9b-9b1838238ee6" - }, - "mappings": { - "type": "array", - "items": { - "type": "object", - "properties": { - "action_type": { - "type": "string", - "example": "overwrite" - }, - "source": { - "type": "string", - "example": "title" - }, - "target": { - "type": "string", - "example": "summary" - } - } - } - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": "2022-06-01T19:58:48.169Z" - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - } - }, - "nullable": true - }, - "version": { - "type": "string", - "example": "WzIwNzMsMV0=" - } - } - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/configure/connectors/_find": { - "get": { - "summary": "Retrieves information about connectors for cases in the default space.", - "operationId": "getCaseConnectorsDefaultSpace", - "description": "In particular, only the connectors that are supported for use in cases are returned. You must have `read` privileges for the **Actions and Connectors** feature in the **Management** section of the Kibana feature privileges.\n", - "tags": [ - "cases", - "kibana" - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "actionTypeId": { - "$ref": "#/components/schemas/connector_types" - }, - "config": { - "type": "object", - "properties": { - "apiUrl": { - "type": "string" - }, - "projectKey": { - "type": "string" - } - }, - "additionalProperties": true - }, - "id": { - "type": "string" - }, - "isDeprecated": { - "type": "boolean" - }, - "isMissingSecrets": { - "type": "boolean" - }, - "isPreconfigured": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "referencedByCount": { - "type": "integer" - } - } - } - }, - "examples": { - "findCaseResponse": { - "$ref": "#/components/examples/find_connector_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/reporters": { - "get": { - "summary": "Returns information about the users who opened cases in the default space.", - "operationId": "getCaseReportersDefaultSpace", - "description": "You must have read privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases. The API returns information about the users as they existed at the time of the case creation, including their name, full name, and email address. If any of those details change thereafter or if a user is deleted, the information returned by this API is unchanged.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/owner" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - } - }, - "examples": { - "getReportersResponse": { - "$ref": "#/components/examples/get_reporters_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/status": { - "get": { - "summary": "Returns the number of cases that are open, closed, and in progress.", - "operationId": "getCaseStatusDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "deprecated": true, - "parameters": [ - { - "$ref": "#/components/parameters/owner" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "count_closed_cases": { - "type": "integer" - }, - "count_in_progress_cases": { - "type": "integer" - }, - "count_open_cases": { - "type": "integer" - } - } - }, - "examples": { - "getStatusResponse": { - "$ref": "#/components/examples/get_status_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/tags": { - "get": { - "summary": "Aggregates and returns a list of case tags in the default space.", - "operationId": "getCaseTagsDefaultSpace", - "description": "You must have read privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "in": "query", - "name": "owner", - "description": "A filter to limit the retrieved case statistics to a specific set of applications. If this parameter is omitted, the response contains tags from all cases that the user has access to read.", - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/owners" - }, - { - "type": "array", - "items": { - "$ref": "#/components/schemas/owners" - } - } - ] - } - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "examples": { - "getTagsResponse": { - "$ref": "#/components/examples/get_tags_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}": { - "get": { - "summary": "Retrieves information about a case in the default space.", - "operationId": "getCaseDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - }, - { - "in": "query", - "name": "includeComments", - "description": "Determines whether case comments are returned.", - "deprecated": true, - "schema": { - "type": "boolean", - "default": true - } - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "getCaseResponse": { - "$ref": "#/components/examples/get_case_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}/alerts": { - "get": { - "summary": "Gets all alerts attached to a case in the default space.", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", - "operationId": "getCaseAlertsDefaultSpace", - "tags": [ - "cases", - "kibana" - ], - "x-technical-preview": true, - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/alert_response_properties" - } - }, - "examples": { - "createCaseCommentResponse": { - "$ref": "#/components/examples/get_case_alerts_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}/comments": { - "post": { - "summary": "Adds a comment or alert to a case in the default space.", - "operationId": "addCaseCommentDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're creating.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "$ref": "#/components/parameters/case_id" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/add_alert_comment_request_properties" - }, - { - "$ref": "#/components/schemas/add_user_comment_request_properties" - } - ] - }, - "examples": { - "createCaseCommentRequest": { - "$ref": "#/components/examples/add_comment_request" - } - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "createCaseCommentResponse": { - "$ref": "#/components/examples/add_comment_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "delete": { - "summary": "Deletes all comments and alerts from a case in the default space.", - "operationId": "deleteCaseCommentsDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "$ref": "#/components/parameters/case_id" - } - ], - "responses": { - "204": { - "description": "Indicates a successful call." - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "patch": { - "summary": "Updates a comment or alert in a case in the default space.", - "operationId": "updateCaseCommentDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're updating. NOTE: You cannot change the comment type or the owner of a comment.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "$ref": "#/components/parameters/case_id" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/update_alert_comment_request_properties" - }, - { - "$ref": "#/components/schemas/update_user_comment_request_properties" - } - ] - }, - "examples": { - "updateCaseCommentRequest": { - "$ref": "#/components/examples/update_comment_request" - } - } - } - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "updateCaseCommentResponse": { - "$ref": "#/components/examples/update_comment_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "get": { - "summary": "Retrieves all the comments from a case in the default space.", - "operationId": "getAllCaseCommentsDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases with the comments you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "deprecated": true, - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - } - } - }, - "examples": {} - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}/comments/{commentId}": { - "delete": { - "summary": "Deletes a comment or alert from a case in the default space.", - "operationId": "deleteCaseCommentDefaultSpace", - "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/kbn_xsrf" - }, - { - "$ref": "#/components/parameters/case_id" - }, - { - "$ref": "#/components/parameters/comment_id" - } - ], - "responses": { - "204": { - "description": "Indicates a successful call." - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "get": { - "summary": "Retrieves a comment from a case in the default space.", - "operationId": "getCaseCommentDefaultSpace", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases with the comments you're seeking.\n", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - }, - { - "$ref": "#/components/parameters/comment_id" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "examples": { - "getCaseCommentResponse": { - "$ref": "#/components/examples/get_comment_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}/connector/{connectorId}/_push": { - "post": { - "summary": "Pushes a case to an external service.", - "description": "You must have `all` privileges for the **Actions and Connectors** feature in the **Management** section of the Kibana feature privileges. You must also have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're pushing.\n", - "operationId": "pushCaseDefaultSpace", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - }, - { - "$ref": "#/components/parameters/connector_id" - }, - { - "$ref": "#/components/parameters/kbn_xsrf" - } - ], - "requestBody": { - "content": { - "application/json": {} - } - }, - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "object", - "properties": { - "closed_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "closed_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "comments": { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/components/schemas/alert_comment_response_properties" - }, - { - "$ref": "#/components/schemas/user_comment_response_properties" - } - ] - }, - "example": [] - }, - "connector": { - "type": "object", - "properties": { - "fields": { - "description": "An object containing the connector fields. To create a case without a connector, specify null. If you want to omit any individual field, specify null as its value.", - "nullable": true, - "type": "object", - "properties": { - "caseId": { - "description": "The case identifier for Swimlane connectors.", - "type": "string" - }, - "category": { - "description": "The category of the incident for ServiceNow ITSM and ServiceNow SecOps connectors.", - "type": "string" - }, - "destIp": { - "description": "A comma-separated list of destination IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "impact": { - "description": "The effect an incident had on business for ServiceNow ITSM connectors.", - "type": "string" - }, - "issueType": { - "description": "The type of issue for Jira connectors.", - "type": "string" - }, - "issueTypes": { - "description": "The type of incident for IBM Resilient connectors.", - "type": "array", - "items": { - "type": "number" - } - }, - "malwareHash": { - "description": "A comma-separated list of malware hashes for ServiceNow SecOps connectors.", - "type": "string" - }, - "malwareUrl": { - "description": "A comma-separated list of malware URLs for ServiceNow SecOps connectors.", - "type": "string" - }, - "parent": { - "description": "The key of the parent issue, when the issue type is sub-task for Jira connectors.", - "type": "string" - }, - "priority": { - "description": "The priority of the issue for Jira and ServiceNow SecOps connectors.", - "type": "string" - }, - "severity": { - "description": "The severity of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "severityCode": { - "description": "The severity code of the incident for IBM Resilient connectors.", - "type": "number" - }, - "sourceIp": { - "description": "A comma-separated list of source IPs for ServiceNow SecOps connectors.", - "type": "string" - }, - "subcategory": { - "description": "The subcategory of the incident for ServiceNow ITSM connectors.", - "type": "string" - }, - "urgency": { - "description": "The extent to which the incident resolution can be delayed for ServiceNow ITSM connectors.", - "type": "string" - } - }, - "example": null - }, - "id": { - "description": "The identifier for the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "name": { - "description": "The name of the connector. To create a case without a connector, use `none`.", - "type": "string", - "example": "none" - }, - "type": { - "$ref": "#/components/schemas/connector_types" - } - } - }, - "created_at": { - "type": "string", - "format": "date-time", - "example": "2022-05-13T09:16:17.416Z" - }, - "created_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - } - }, - "description": { - "type": "string", - "example": "A case description." - }, - "duration": { - "type": "integer", - "description": "The elapsed time from the creation of the case to its closure (in seconds). If the case has not been closed, the duration is set to null. If the case was closed after less than half a second, the duration is rounded down to zero.\n", - "example": 120 - }, - "external_service": { - "$ref": "#/components/schemas/external_service" - }, - "id": { - "type": "string", - "example": "66b9aa00-94fa-11ea-9f74-e7e108796192" - }, - "owner": { - "$ref": "#/components/schemas/owners" - }, - "settings": { - "$ref": "#/components/schemas/settings" - }, - "severity": { - "$ref": "#/components/schemas/severity_property" - }, - "status": { - "$ref": "#/components/schemas/status" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "tag-1" - ] - }, - "title": { - "type": "string", - "example": "Case title 1" - }, - "totalAlerts": { - "type": "integer", - "example": 0 - }, - "totalComment": { - "type": "integer", - "example": 0 - }, - "updated_at": { - "type": "string", - "format": "date-time", - "nullable": true, - "example": null - }, - "updated_by": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": null - }, - "full_name": { - "type": "string", - "example": null - }, - "username": { - "type": "string", - "example": "elastic" - }, - "profile_uid": { - "type": "string", - "example": "u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0" - } - }, - "nullable": true, - "example": null - }, - "version": { - "type": "string", - "example": "WzUzMiwxXQ==" - } - } - }, - "examples": { - "pushCaseResponse": { - "$ref": "#/components/examples/push_case_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "/api/cases/{caseId}/user_actions": { - "get": { - "summary": "Returns all user activity for a case in the default space.", - "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're seeking.\n", - "deprecated": true, - "operationId": "getCaseActivityDefaultSpace", - "tags": [ - "cases", - "kibana" - ], - "parameters": [ - { - "$ref": "#/components/parameters/case_id" - } - ], - "responses": { - "200": { - "description": "Indicates a successful call.", - "content": { - "application/json; charset=utf-8": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/user_actions_response_properties" - } - }, - "examples": { - "getCaseActivityResponse": { - "$ref": "#/components/examples/get_case_activity_response" - } - } - } - } - } - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, - "servers": [ - { - "url": "https://localhost:5601" - } - ] - }, "/s/{spaceId}/api/cases": { "post": { "summary": "Creates a case.", "operationId": "createCase", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're creating.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -4498,8 +459,7 @@ "operationId": "deleteCase", "description": "You must have `read` or `all` privileges and the `delete` sub-feature privilege for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -4535,8 +495,7 @@ "operationId": "updateCase", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're updating.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -4979,8 +938,7 @@ "operationId": "getCases", "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -5462,8 +1420,7 @@ "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", "x-technical-preview": true, "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -5525,8 +1482,7 @@ "operationId": "getCaseConfiguration", "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -5737,8 +1693,7 @@ "operationId": "setCaseConfiguration", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration. Connectors are used to interface with external systems. You must create a connector before you can use it in your cases. Refer to the add connectors API. If you set a default connector, it is automatically selected when you create cases in Kibana. If you use the create case API, however, you must still specify all of the connector details.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6088,8 +2043,7 @@ "operationId": "updateCaseConfiguration", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case configuration. Connectors are used to interface with external systems. You must create a connector before you can use it in your cases. Refer to the add connectors API.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6428,8 +2382,7 @@ "operationId": "getCaseConnectors", "description": "In particular, only the connectors that are supported for use in cases are returned. You must have `read` privileges for the **Actions and Connectors** feature in the **Management** section of the Kibana feature privileges.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6509,8 +2462,7 @@ "operationId": "getCaseReporters", "description": "You must have read privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases. The API returns information about the users as they existed at the time of the case creation, including their name, full name, and email address. If any of those details change thereafter or if a user is deleted, the information returned by this API is unchanged.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6577,8 +2529,7 @@ "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", "deprecated": true, "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6634,8 +2585,7 @@ "operationId": "getCaseTags", "description": "You must have read privileges for the **Cases*** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're seeking.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6698,8 +2648,7 @@ "operationId": "getCase", "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're seeking.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -6997,8 +2946,7 @@ "x-technical-preview": true, "operationId": "getCaseAlerts", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7046,8 +2994,7 @@ "operationId": "addCaseComment", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're creating.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7351,8 +3298,7 @@ "operationId": "deleteCaseComments", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7381,8 +3327,7 @@ "operationId": "updateCaseComment", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're updating. NOTE: You cannot change the comment type or the owner of a comment.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7687,8 +3632,7 @@ "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases with the comments you're seeking.\n", "deprecated": true, "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7739,8 +3683,7 @@ "operationId": "deleteCaseComment", "description": "You must have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the cases you're deleting.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7772,8 +3715,7 @@ "operationId": "getCaseComment", "description": "You must have `read` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security*** section of the Kibana feature privileges, depending on the owner of the cases with the comments you're seeking.\n", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -7828,8 +3770,7 @@ "description": "You must have `all` privileges for the **Actions and Connectors** feature in the **Management** section of the Kibana feature privileges. You must also have `all` privileges for the **Cases** feature in the **Management**, **Observability**, or **Security** section of the Kibana feature privileges, depending on the owner of the case you're pushing.\n", "operationId": "pushCase", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -8128,8 +4069,7 @@ "deprecated": true, "operationId": "getCaseActivity", "tags": [ - "cases", - "kibana" + "cases" ], "parameters": [ { @@ -8193,6 +4133,16 @@ "name": "kbn-xsrf", "required": true }, + "space_id": { + "in": "path", + "name": "spaceId", + "description": "An identifier for the space. If `/s/` and the identifier are omitted from the path, the default space is used.", + "required": true, + "schema": { + "type": "string", + "example": "default" + } + }, "owner": { "in": "query", "name": "owner", @@ -8275,16 +4225,6 @@ "type": "string", "example": "abed3a70-71bd-11ea-a0b2-c51ea50a58e2" } - }, - "space_id": { - "in": "path", - "name": "spaceId", - "description": "An identifier for the space.", - "required": true, - "schema": { - "type": "string", - "example": "default" - } } }, "schemas": { diff --git a/x-pack/plugins/cases/docs/openapi/bundled.yaml b/x-pack/plugins/cases/docs/openapi/bundled.yaml index a328d0282a515..7f02703b161a6 100644 --- a/x-pack/plugins/cases/docs/openapi/bundled.yaml +++ b/x-pack/plugins/cases/docs/openapi/bundled.yaml @@ -17,3350 +17,6 @@ servers: - url: http://localhost:5601 description: local paths: - /api/cases: - post: - summary: Creates a case in the default space. - operationId: createCaseDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're creating. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - requestBody: - content: - application/json: - schema: - type: object - properties: - connector: - description: An object that contains the connector configuration. - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM and - ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type is - sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM Resilient - connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for ServiceNow - SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow ITSM - connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - required: - - fields - - id - - name - - type - description: - description: The description for the case. - type: string - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - tags: - description: >- - The words and phrases that help categorize cases. It can be - an empty array. - type: array - items: - type: string - title: - description: A title for the case. - type: string - required: - - connector - - description - - owner - - settings - - tags - - title - examples: - createCaseRequest: - $ref: '#/components/examples/create_case_request' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - createCaseResponse: - $ref: '#/components/examples/create_case_response' - servers: - - url: https://localhost:5601 - delete: - summary: Deletes one or more cases from the default space. - operationId: deleteCaseDefaultSpace - description: > - You must have `read` or `all` privileges and the `delete` sub-feature - privilege for the **Cases** feature in the **Management**, - **Observability**, or **Security** section of the Kibana feature - privileges, depending on the owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - name: ids - description: >- - The cases that you want to removed. To retrieve case IDs, use the - find cases API. All non-ASCII characters must be URL encoded. - in: query - required: true - schema: - type: string - example: d4e7abb0-b462-11ec-9a8d-698504725a43 - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - patch: - summary: Updates one or more cases in the default space. - operationId: updateCaseDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're updating. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - requestBody: - content: - application/json: - schema: - type: object - properties: - cases: - type: array - items: - type: object - properties: - connector: - description: An object that contains the connector configuration. - type: object - properties: - fields: - description: >- - An object containing the connector fields. To - create a case without a connector, specify null. - If you want to omit any individual field, specify - null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow - ITSM and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: >- - The type of incident for IBM Resilient - connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue - type is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and - ServiceNow SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow - ITSM connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution - can be delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case - without a connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - required: - - fields - - id - - name - - type - description: - description: The description for the case. - type: string - id: - description: The identifier for the case. - type: string - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - description: The words and phrases that help categorize cases. - type: array - items: - type: string - title: - description: A title for the case. - type: string - version: - description: The current version of the case. - type: string - required: - - id - - version - examples: - updateCaseRequest: - $ref: '#/components/examples/update_case_request' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - updateCaseResponse: - $ref: '#/components/examples/update_case_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/_find: - get: - summary: Retrieves a paginated subset of cases from the default space. - operationId: getCasesDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - parameters: - - name: defaultSearchOperator - in: query - description: The default operator to use for the simple_query_string. - schema: - type: string - default: OR - example: OR - - name: fields - in: query - description: The fields in the entity to return in the response. - schema: - type: array - items: - type: string - - name: from - in: query - description: > - [preview] Returns only cases that were created after a specific - date. The date must be specified as a KQL data range or date match - expression. This functionality is in technical preview and may be - changed or removed in a future release. Elastic will apply best - effort to fix any issues, but features in technical preview are not - subject to the support SLA of official GA features. - schema: - type: string - example: now-1d - x-technical-preview: true - - $ref: '#/components/parameters/owner' - - name: page - in: query - description: The page number to return. - schema: - type: integer - default: 1 - example: 1 - - name: perPage - in: query - description: The number of rules to return per page. - schema: - type: integer - default: 20 - example: 20 - - name: reporters - in: query - description: Filters the returned cases by the user name of the reporter. - schema: - oneOf: - - type: string - - type: array - items: - type: string - example: elastic - - name: search - in: query - description: >- - An Elasticsearch simple_query_string query that filters the objects - in the response. - schema: - type: string - - name: searchFields - in: query - description: The fields to perform the simple_query_string parsed query against. - schema: - oneOf: - - type: string - - type: array - items: - type: string - - $ref: '#/components/parameters/severity' - - name: sortField - in: query - description: Determines which field is used to sort the results. - schema: - type: string - enum: - - createdAt - - updatedAt - default: createdAt - example: updatedAt - - name: sortOrder - in: query - description: Determines the sort order. - schema: - type: string - enum: - - asc - - desc - default: desc - example: asc - - in: query - name: status - description: Filters the returned cases by state. - schema: - type: string - enum: - - closed - - in-progress - - open - example: open - - name: tags - in: query - description: Filters the returned cases by tags. - schema: - oneOf: - - type: string - - type: array - items: - type: string - example: tag-1 - - name: to - in: query - description: >- - Returns only cases that were created before a specific date. The - date must be specified as a KQL data range or date match expression. - schema: - type: string - example: now%2B1d - x-technical-preview: true - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - cases: - type: array - items: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To - create a case without a connector, specify null. - If you want to omit any individual field, - specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow - ITSM and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs - for ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: >- - The type of incident for IBM Resilient - connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue - type is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and - ServiceNow SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow - ITSM connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for - ServiceNow ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution - can be delayed for ServiceNow ITSM - connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a - case without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case - without a connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to - its closure (in seconds). If the case has not been - closed, the duration is set to null. If the case was - closed after less than half a second, the duration - is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - count_closed_cases: - type: integer - count_in_progress_cases: - type: integer - count_open_cases: - type: integer - page: - type: integer - per_page: - type: integer - total: - type: integer - examples: - findCaseResponse: - $ref: '#/components/examples/find_case_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/alerts/{alertId}: - get: - summary: Returns the cases associated with a specific alert in the default space. - operationId: getCasesByAlertDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - x-technical-preview: true - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/alert_id' - - $ref: '#/components/parameters/owner' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - id: - type: string - description: The case identifier. - title: - type: string - description: The case title. - example: - - id: 06116b80-e1c3-11ec-be9b-9b1838238ee6 - title: security_case - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/configure: - get: - summary: >- - Retrieves external connection details, such as the closure type and - default connector for cases in the default space. - operationId: getCaseConfigurationDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/owner' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - closure_type: - $ref: '#/components/schemas/closure_types' - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create - a case without a connector, specify null. If you - want to omit any individual field, specify null as - its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: >- - The type of incident for IBM Resilient - connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and - ServiceNow SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can - be delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without - a connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-06-01T17:07:17.767Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - error: - type: string - example: null - id: - type: string - example: 4a97a440-e1cd-11ec-be9b-9b1838238ee6 - mappings: - type: array - items: - type: object - properties: - action_type: - type: string - example: overwrite - source: - type: string - example: title - target: - type: string - example: summary - owner: - $ref: '#/components/schemas/owners' - updated_at: - type: string - format: date-time - nullable: true - example: '2022-06-01T19:58:48.169Z' - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - nullable: true - version: - type: string - example: WzIwNzMsMV0= - servers: - - url: https://localhost:5601 - post: - summary: >- - Sets external connection details, such as the closure type and default - connector for cases in the default space. - operationId: setCaseConfigurationDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - Connectors are used to interface with external systems. You must create - a connector before you can use it in your cases. Refer to the add - connectors API. If you set a default connector, it is automatically - selected when you create cases in Kibana. If you use the create case - API, however, you must still specify all of the connector details. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - requestBody: - content: - application/json: - schema: - type: object - properties: - closure_type: - $ref: '#/components/schemas/closure_types' - connector: - description: An object that contains the connector configuration. - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM and - ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type is - sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM Resilient - connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for ServiceNow - SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow ITSM - connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - required: - - fields - - id - - name - - type - owner: - $ref: '#/components/schemas/owners' - settings: - description: An object that contains the case settings. - type: object - properties: - syncAlerts: - description: Turns alert syncing on or off. - type: boolean - example: true - required: - - syncAlerts - required: - - closure_type - - connector - - owner - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - closure_type: - $ref: '#/components/schemas/closure_types' - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create - a case without a connector, specify null. If you - want to omit any individual field, specify null as - its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: >- - The type of incident for IBM Resilient - connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and - ServiceNow SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can - be delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without - a connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-06-01T17:07:17.767Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - error: - type: string - example: null - id: - type: string - example: 4a97a440-e1cd-11ec-be9b-9b1838238ee6 - mappings: - type: array - items: - type: object - properties: - action_type: - type: string - example: overwrite - source: - type: string - example: title - target: - type: string - example: summary - owner: - $ref: '#/components/schemas/owners' - updated_at: - type: string - format: date-time - nullable: true - example: '2022-06-01T19:58:48.169Z' - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - nullable: true - version: - type: string - example: WzIwNzMsMV0= - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/configure/{configurationId}: - patch: - summary: >- - Updates external connection details, such as the closure type and - default connector for cases in the default space. - operationId: updateCaseConfigurationDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - Connectors are used to interface with external systems. You must create - a connector before you can use it in your cases. Refer to the add - connectors API. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - $ref: '#/components/parameters/configuration_id' - requestBody: - content: - application/json: - schema: - type: object - properties: - closure_type: - $ref: '#/components/schemas/closure_types' - connector: - description: An object that contains the connector configuration. - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM and - ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type is - sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM Resilient - connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for ServiceNow - SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow ITSM - connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - required: - - fields - - id - - name - - type - version: - description: > - The version of the connector. To retrieve the version value, - use the get configuration API. - type: string - example: WzIwMiwxXQ== - required: - - version - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - closure_type: - $ref: '#/components/schemas/closure_types' - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create - a case without a connector, specify null. If you - want to omit any individual field, specify null as - its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: >- - The type of incident for IBM Resilient - connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and - ServiceNow SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can - be delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without - a connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-06-01T17:07:17.767Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - error: - type: string - example: null - id: - type: string - example: 4a97a440-e1cd-11ec-be9b-9b1838238ee6 - mappings: - type: array - items: - type: object - properties: - action_type: - type: string - example: overwrite - source: - type: string - example: title - target: - type: string - example: summary - owner: - $ref: '#/components/schemas/owners' - updated_at: - type: string - format: date-time - nullable: true - example: '2022-06-01T19:58:48.169Z' - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - nullable: true - version: - type: string - example: WzIwNzMsMV0= - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/configure/connectors/_find: - get: - summary: Retrieves information about connectors for cases in the default space. - operationId: getCaseConnectorsDefaultSpace - description: > - In particular, only the connectors that are supported for use in cases - are returned. You must have `read` privileges for the **Actions and - Connectors** feature in the **Management** section of the Kibana feature - privileges. - tags: - - cases - - kibana - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - actionTypeId: - $ref: '#/components/schemas/connector_types' - config: - type: object - properties: - apiUrl: - type: string - projectKey: - type: string - additionalProperties: true - id: - type: string - isDeprecated: - type: boolean - isMissingSecrets: - type: boolean - isPreconfigured: - type: boolean - name: - type: string - referencedByCount: - type: integer - examples: - findCaseResponse: - $ref: '#/components/examples/find_connector_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/reporters: - get: - summary: >- - Returns information about the users who opened cases in the default - space. - operationId: getCaseReportersDefaultSpace - description: > - You must have read privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases. The API returns - information about the users as they existed at the time of the case - creation, including their name, full name, and email address. If any of - those details change thereafter or if a user is deleted, the information - returned by this API is unchanged. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/owner' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - examples: - getReportersResponse: - $ref: '#/components/examples/get_reporters_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/status: - get: - summary: Returns the number of cases that are open, closed, and in progress. - operationId: getCaseStatusDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - deprecated: true - parameters: - - $ref: '#/components/parameters/owner' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - count_closed_cases: - type: integer - count_in_progress_cases: - type: integer - count_open_cases: - type: integer - examples: - getStatusResponse: - $ref: '#/components/examples/get_status_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/tags: - get: - summary: Aggregates and returns a list of case tags in the default space. - operationId: getCaseTagsDefaultSpace - description: > - You must have read privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - parameters: - - in: query - name: owner - description: >- - A filter to limit the retrieved case statistics to a specific set of - applications. If this parameter is omitted, the response contains - tags from all cases that the user has access to read. - schema: - oneOf: - - $ref: '#/components/schemas/owners' - - type: array - items: - $ref: '#/components/schemas/owners' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: string - examples: - getTagsResponse: - $ref: '#/components/examples/get_tags_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}: - get: - summary: Retrieves information about a case in the default space. - operationId: getCaseDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're seeking. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/case_id' - - in: query - name: includeComments - description: Determines whether case comments are returned. - deprecated: true - schema: - type: boolean - default: true - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - getCaseResponse: - $ref: '#/components/examples/get_case_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}/alerts: - get: - summary: Gets all alerts attached to a case in the default space. - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - operationId: getCaseAlertsDefaultSpace - tags: - - cases - - kibana - x-technical-preview: true - parameters: - - $ref: '#/components/parameters/case_id' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - $ref: '#/components/schemas/alert_response_properties' - examples: - createCaseCommentResponse: - $ref: '#/components/examples/get_case_alerts_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}/comments: - post: - summary: Adds a comment or alert to a case in the default space. - operationId: addCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're creating. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - $ref: '#/components/parameters/case_id' - requestBody: - content: - application/json: - schema: - oneOf: - - $ref: '#/components/schemas/add_alert_comment_request_properties' - - $ref: '#/components/schemas/add_user_comment_request_properties' - examples: - createCaseCommentRequest: - $ref: '#/components/examples/add_comment_request' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - createCaseCommentResponse: - $ref: '#/components/examples/add_comment_response' - servers: - - url: https://localhost:5601 - delete: - summary: Deletes all comments and alerts from a case in the default space. - operationId: deleteCaseCommentsDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - $ref: '#/components/parameters/case_id' - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - patch: - summary: Updates a comment or alert in a case in the default space. - operationId: updateCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're updating. - NOTE: You cannot change the comment type or the owner of a comment. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - $ref: '#/components/parameters/case_id' - requestBody: - content: - application/json: - schema: - oneOf: - - $ref: '#/components/schemas/update_alert_comment_request_properties' - - $ref: '#/components/schemas/update_user_comment_request_properties' - examples: - updateCaseCommentRequest: - $ref: '#/components/examples/update_comment_request' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - updateCaseCommentResponse: - $ref: '#/components/examples/update_comment_response' - servers: - - url: https://localhost:5601 - get: - summary: Retrieves all the comments from a case in the default space. - operationId: getAllCaseCommentsDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases with the - comments you're seeking. - tags: - - cases - - kibana - deprecated: true - parameters: - - $ref: '#/components/parameters/case_id' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - anyOf: - - $ref: '#/components/schemas/alert_comment_response_properties' - - $ref: '#/components/schemas/user_comment_response_properties' - examples: {} - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}/comments/{commentId}: - delete: - summary: Deletes a comment or alert from a case in the default space. - operationId: deleteCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/kbn_xsrf' - - $ref: '#/components/parameters/case_id' - - $ref: '#/components/parameters/comment_id' - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - get: - summary: Retrieves a comment from a case in the default space. - operationId: getCaseCommentDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases with the - comments you're seeking. - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/case_id' - - $ref: '#/components/parameters/comment_id' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - oneOf: - - $ref: '#/components/schemas/alert_comment_response_properties' - - $ref: '#/components/schemas/user_comment_response_properties' - examples: - getCaseCommentResponse: - $ref: '#/components/examples/get_comment_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}/connector/{connectorId}/_push: - post: - summary: Pushes a case to an external service. - description: > - You must have `all` privileges for the **Actions and Connectors** - feature in the **Management** section of the Kibana feature privileges. - You must also have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're pushing. - operationId: pushCaseDefaultSpace - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/case_id' - - $ref: '#/components/parameters/connector_id' - - $ref: '#/components/parameters/kbn_xsrf' - requestBody: - content: - application/json: {} - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - closed_at: - type: string - format: date-time - nullable: true - example: null - closed_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - comments: - type: array - items: - oneOf: - - $ref: >- - #/components/schemas/alert_comment_response_properties - - $ref: >- - #/components/schemas/user_comment_response_properties - example: [] - connector: - type: object - properties: - fields: - description: >- - An object containing the connector fields. To create a - case without a connector, specify null. If you want to - omit any individual field, specify null as its value. - nullable: true - type: object - properties: - caseId: - description: The case identifier for Swimlane connectors. - type: string - category: - description: >- - The category of the incident for ServiceNow ITSM - and ServiceNow SecOps connectors. - type: string - destIp: - description: >- - A comma-separated list of destination IPs for - ServiceNow SecOps connectors. - type: string - impact: - description: >- - The effect an incident had on business for - ServiceNow ITSM connectors. - type: string - issueType: - description: The type of issue for Jira connectors. - type: string - issueTypes: - description: The type of incident for IBM Resilient connectors. - type: array - items: - type: number - malwareHash: - description: >- - A comma-separated list of malware hashes for - ServiceNow SecOps connectors. - type: string - malwareUrl: - description: >- - A comma-separated list of malware URLs for - ServiceNow SecOps connectors. - type: string - parent: - description: >- - The key of the parent issue, when the issue type - is sub-task for Jira connectors. - type: string - priority: - description: >- - The priority of the issue for Jira and ServiceNow - SecOps connectors. - type: string - severity: - description: >- - The severity of the incident for ServiceNow ITSM - connectors. - type: string - severityCode: - description: >- - The severity code of the incident for IBM - Resilient connectors. - type: number - sourceIp: - description: >- - A comma-separated list of source IPs for - ServiceNow SecOps connectors. - type: string - subcategory: - description: >- - The subcategory of the incident for ServiceNow - ITSM connectors. - type: string - urgency: - description: >- - The extent to which the incident resolution can be - delayed for ServiceNow ITSM connectors. - type: string - example: null - id: - description: >- - The identifier for the connector. To create a case - without a connector, use `none`. - type: string - example: none - name: - description: >- - The name of the connector. To create a case without a - connector, use `none`. - type: string - example: none - type: - $ref: '#/components/schemas/connector_types' - created_at: - type: string - format: date-time - example: '2022-05-13T09:16:17.416Z' - created_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - description: - type: string - example: A case description. - duration: - type: integer - description: > - The elapsed time from the creation of the case to its - closure (in seconds). If the case has not been closed, the - duration is set to null. If the case was closed after less - than half a second, the duration is rounded down to zero. - example: 120 - external_service: - $ref: '#/components/schemas/external_service' - id: - type: string - example: 66b9aa00-94fa-11ea-9f74-e7e108796192 - owner: - $ref: '#/components/schemas/owners' - settings: - $ref: '#/components/schemas/settings' - severity: - $ref: '#/components/schemas/severity_property' - status: - $ref: '#/components/schemas/status' - tags: - type: array - items: - type: string - example: - - tag-1 - title: - type: string - example: Case title 1 - totalAlerts: - type: integer - example: 0 - totalComment: - type: integer - example: 0 - updated_at: - type: string - format: date-time - nullable: true - example: null - updated_by: - type: object - properties: - email: - type: string - example: null - full_name: - type: string - example: null - username: - type: string - example: elastic - profile_uid: - type: string - example: u_J41Oh6L9ki-Vo2tOogS8WRTENzhHurGtRc87NgEAlkc_0 - nullable: true - example: null - version: - type: string - example: WzUzMiwxXQ== - examples: - pushCaseResponse: - $ref: '#/components/examples/push_case_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 - /api/cases/{caseId}/user_actions: - get: - summary: Returns all user activity for a case in the default space. - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're seeking. - deprecated: true - operationId: getCaseActivityDefaultSpace - tags: - - cases - - kibana - parameters: - - $ref: '#/components/parameters/case_id' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - $ref: '#/components/schemas/user_actions_response_properties' - examples: - getCaseActivityResponse: - $ref: '#/components/examples/get_case_activity_response' - servers: - - url: https://localhost:5601 - servers: - - url: https://localhost:5601 /s/{spaceId}/api/cases: post: summary: Creates a case. @@ -3372,7 +28,6 @@ paths: creating. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/space_id' @@ -3748,7 +403,6 @@ paths: privileges, depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/space_id' @@ -3776,7 +430,6 @@ paths: updating. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/space_id' @@ -4162,7 +815,6 @@ paths: feature privileges, depending on the owner of the cases you're seeking. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' - name: defaultSearchOperator @@ -4544,7 +1196,6 @@ paths: x-technical-preview: true tags: - cases - - kibana parameters: - $ref: '#/components/parameters/alert_id' - $ref: '#/components/parameters/space_id' @@ -4584,7 +1235,6 @@ paths: feature privileges, depending on the owner of the case configuration. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' - $ref: '#/components/parameters/owner' @@ -4777,7 +1427,6 @@ paths: API, however, you must still specify all of the connector details. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/space_id' @@ -5098,7 +1747,6 @@ paths: connectors API. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/configuration_id' @@ -5408,7 +2056,6 @@ paths: privileges. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' responses: @@ -5464,7 +2111,6 @@ paths: returned by this API is unchanged. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' - $ref: '#/components/parameters/owner' @@ -5508,7 +2154,6 @@ paths: deprecated: true tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' - $ref: '#/components/parameters/owner' @@ -5543,7 +2188,6 @@ paths: feature privileges, depending on the owner of the cases you're seeking. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/space_id' - in: query @@ -5584,7 +2228,6 @@ paths: feature privileges, depending on the owner of the case you're seeking. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/space_id' @@ -5832,7 +2475,6 @@ paths: operationId: getCaseAlerts tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/space_id' @@ -5862,7 +2504,6 @@ paths: feature privileges, depending on the owner of the case you're creating. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/case_id' @@ -6110,7 +2751,6 @@ paths: feature privileges, depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/case_id' @@ -6130,7 +2770,6 @@ paths: NOTE: You cannot change the comment type or the owner of a comment. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/case_id' @@ -6380,7 +3019,6 @@ paths: deprecated: true tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/space_id' @@ -6410,7 +3048,6 @@ paths: feature privileges, depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/kbn_xsrf' - $ref: '#/components/parameters/case_id' @@ -6431,7 +3068,6 @@ paths: comments you're seeking. tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/comment_id' @@ -6464,7 +3100,6 @@ paths: operationId: pushCase tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/connector_id' @@ -6710,7 +3345,6 @@ paths: operationId: getCaseActivity tags: - cases - - kibana parameters: - $ref: '#/components/parameters/case_id' - $ref: '#/components/parameters/space_id' @@ -6746,6 +3380,16 @@ components: in: header name: kbn-xsrf required: true + space_id: + in: path + name: spaceId + description: >- + An identifier for the space. If `/s/` and the identifier are omitted + from the path, the default space is used. + required: true + schema: + type: string + example: default owner: in: query name: owner @@ -6817,14 +3461,6 @@ components: schema: type: string example: abed3a70-71bd-11ea-a0b2-c51ea50a58e2 - space_id: - in: path - name: spaceId - description: An identifier for the space. - required: true - schema: - type: string - example: default schemas: connector_types: type: string diff --git a/x-pack/plugins/cases/docs/openapi/components/parameters/space_id.yaml b/x-pack/plugins/cases/docs/openapi/components/parameters/space_id.yaml index 0ff325b08a082..0a9fba457e3e7 100644 --- a/x-pack/plugins/cases/docs/openapi/components/parameters/space_id.yaml +++ b/x-pack/plugins/cases/docs/openapi/components/parameters/space_id.yaml @@ -1,6 +1,6 @@ in: path name: spaceId -description: An identifier for the space. +description: An identifier for the space. If `/s/` and the identifier are omitted from the path, the default space is used. required: true schema: type: string diff --git a/x-pack/plugins/cases/docs/openapi/entrypoint.yaml b/x-pack/plugins/cases/docs/openapi/entrypoint.yaml index 3866c4fe4edcb..6995d1482e0a9 100644 --- a/x-pack/plugins/cases/docs/openapi/entrypoint.yaml +++ b/x-pack/plugins/cases/docs/openapi/entrypoint.yaml @@ -17,37 +17,6 @@ servers: - url: 'http://localhost:5601' description: local paths: - /api/cases: - $ref: paths/api@cases.yaml - /api/cases/_find: - $ref: paths/api@cases@_find.yaml - '/api/cases/alerts/{alertId}': - $ref: 'paths/api@cases@alerts@{alertid}.yaml' - '/api/cases/configure': - $ref: paths/api@cases@configure.yaml - '/api/cases/configure/{configurationId}': - $ref: paths/api@cases@configure@{configurationid}.yaml - '/api/cases/configure/connectors/_find': - $ref: paths/api@cases@configure@connectors@_find.yaml - '/api/cases/reporters': - $ref: 'paths/api@cases@reporters.yaml' - '/api/cases/status': - $ref: 'paths/api@cases@status.yaml' - '/api/cases/tags': - $ref: 'paths/api@cases@tags.yaml' - '/api/cases/{caseId}': - $ref: 'paths/api@cases@{caseid}.yaml' - '/api/cases/{caseId}/alerts': - $ref: 'paths/api@cases@{caseid}@alerts.yaml' - '/api/cases/{caseId}/comments': - $ref: 'paths/api@cases@{caseid}@comments.yaml' - '/api/cases/{caseId}/comments/{commentId}': - $ref: 'paths/api@cases@{caseid}@comments@{commentid}.yaml' - '/api/cases/{caseId}/connector/{connectorId}/_push': - $ref: 'paths/api@cases@{caseid}@connector@{connectorid}@_push.yaml' - '/api/cases/{caseId}/user_actions': - $ref: 'paths/api@cases@{caseid}@user_actions.yaml' - '/s/{spaceId}/api/cases': $ref: 'paths/s@{spaceid}@api@cases.yaml' '/s/{spaceId}/api/cases/_find': diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases.yaml deleted file mode 100644 index 96a9c473557c5..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases.yaml +++ /dev/null @@ -1,175 +0,0 @@ -post: - summary: Creates a case in the default space. - operationId: createCaseDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're creating. - tags: - - cases - - kibana - parameters: - - $ref: ../components/headers/kbn_xsrf.yaml - requestBody: - content: - application/json: - schema: - type: object - properties: - connector: - description: An object that contains the connector configuration. - type: object - properties: - $ref: '../components/schemas/connector_properties.yaml' - required: - - fields - - id - - name - - type - description: - description: The description for the case. - type: string - owner: - $ref: '../components/schemas/owners.yaml' - settings: - $ref: '../components/schemas/settings.yaml' - severity: - $ref: '../components/schemas/severity_property.yaml' - tags: - description: The words and phrases that help categorize cases. It can be an empty array. - type: array - items: - type: string - title: - description: A title for the case. - type: string - required: - - connector - - description - - owner - - settings - - tags - - title - examples: - createCaseRequest: - $ref: '../components/examples/create_case_request.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - createCaseResponse: - $ref: '../components/examples/create_case_response.yaml' - servers: - - url: https://localhost:5601 - -delete: - summary: Deletes one or more cases from the default space. - operationId: deleteCaseDefaultSpace - description: > - You must have `read` or `all` privileges and the `delete` sub-feature - privilege for the **Cases** feature in the **Management**, **Observability**, - or **Security** section of the Kibana feature privileges, depending on the - owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: ../components/headers/kbn_xsrf.yaml - - name: ids - description: The cases that you want to removed. To retrieve case IDs, use the find cases API. All non-ASCII characters must be URL encoded. - in: query - required: true - schema: - type: string - example: d4e7abb0-b462-11ec-9a8d-698504725a43 - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - -patch: - summary: Updates one or more cases in the default space. - operationId: updateCaseDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're updating. - tags: - - cases - - kibana - parameters: - - $ref: ../components/headers/kbn_xsrf.yaml - requestBody: - content: - application/json: - schema: - type: object - properties: - cases: - type: array - items: - type: object - properties: - connector: - description: An object that contains the connector configuration. - type: object - properties: - $ref: '../components/schemas/connector_properties.yaml' - required: - - fields - - id - - name - - type - description: - description: The description for the case. - type: string - id: - description: The identifier for the case. - type: string - settings: - $ref: '../components/schemas/settings.yaml' - severity: - $ref: '../components/schemas/severity_property.yaml' - status: - $ref: '../components/schemas/status.yaml' - tags: - description: The words and phrases that help categorize cases. - type: array - items: - type: string - title: - description: A title for the case. - type: string - version: - description: The current version of the case. - type: string - required: - - id - - version - examples: - updateCaseRequest: - $ref: '../components/examples/update_case_request.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - updateCaseResponse: - $ref: '../components/examples/update_case_response.yaml' - servers: - - url: https://localhost:5601 - -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@_find.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@_find.yaml deleted file mode 100644 index 266e00101aad5..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@_find.yaml +++ /dev/null @@ -1,158 +0,0 @@ -get: - summary: Retrieves a paginated subset of cases from the default space. - operationId: getCasesDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - parameters: - - name: defaultSearchOperator - in: query - description: The default operator to use for the simple_query_string. - schema: - type: string - default: OR - example: OR - - name: fields - in: query - description: The fields in the entity to return in the response. - schema: - type: array - items: - type: string - - name: from - in: query - description: > - [preview] Returns only cases that were created after a specific date. - The date must be specified as a KQL data range or date match expression. - This functionality is in technical preview and may be changed or removed - in a future release. Elastic will apply best effort to fix any issues, - but features in technical preview are not subject to the support SLA of - official GA features. - schema: - type: string - example: now-1d - x-technical-preview: true - - $ref: '../components/parameters/owner.yaml' - - name: page - in: query - description: The page number to return. - schema: - type: integer - default: 1 - example: 1 - - name: perPage - in: query - description: The number of rules to return per page. - schema: - type: integer - default: 20 - example: 20 - - name: reporters - in: query - description: Filters the returned cases by the user name of the reporter. - schema: - oneOf: - - type: string - - type: array - items: - type: string - example: elastic - - name: search - in: query - description: An Elasticsearch simple_query_string query that filters the objects in the response. - schema: - type: string - - name: searchFields - in: query - description: The fields to perform the simple_query_string parsed query against. - schema: - oneOf: - - type: string - - type: array - items: - type: string - - $ref: '../components/parameters/severity.yaml' - - name: sortField - in: query - description: Determines which field is used to sort the results. - schema: - type: string - enum: - - createdAt - - updatedAt - default: createdAt - example: updatedAt - - name: sortOrder - in: query - description: Determines the sort order. - schema: - type: string - enum: - - asc - - desc - default: desc - example: asc - - in: query - name: status - description: Filters the returned cases by state. - schema: - type: string - enum: - - closed - - in-progress - - open - example: open - - name: tags - in: query - description: Filters the returned cases by tags. - schema: - oneOf: - - type: string - - type: array - items: - type: string - example: tag-1 - - name: to - in: query - description: Returns only cases that were created before a specific date. The date must be specified as a KQL data range or date match expression. - schema: - type: string - example: now%2B1d - x-technical-preview: true - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - cases: - type: array - items: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - count_closed_cases: - type: integer - count_in_progress_cases: - type: integer - count_open_cases: - type: integer - page: - type: integer - per_page: - type: integer - total: - type: integer - examples: - findCaseResponse: - $ref: '../components/examples/find_case_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@alerts@{alertid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@alerts@{alertid}.yaml deleted file mode 100644 index e020ae577cd96..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@alerts@{alertid}.yaml +++ /dev/null @@ -1,37 +0,0 @@ -get: - summary: Returns the cases associated with a specific alert in the default space. - operationId: getCasesByAlertDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - x-technical-preview: true - tags: - - cases - - kibana - parameters: - - $ref: ../components/parameters/alert_id.yaml - - $ref: '../components/parameters/owner.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - id: - type: string - description: The case identifier. - title: - type: string - description: The case title. - example: - - id: 06116b80-e1c3-11ec-be9b-9b1838238ee6 - title: security_case - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure.yaml deleted file mode 100644 index 527f67b3cbf22..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure.yaml +++ /dev/null @@ -1,93 +0,0 @@ -get: - summary: Retrieves external connection details, such as the closure type and default connector for cases in the default space. - operationId: getCaseConfigurationDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - tags: - - cases - - kibana - parameters: - - $ref: '../components/parameters/owner.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - $ref: '../components/schemas/case_configure_response_properties.yaml' - servers: - - url: https://localhost:5601 - -post: - summary: Sets external connection details, such as the closure type and default connector for cases in the default space. - operationId: setCaseConfigurationDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - Connectors are used to interface with external systems. You must create a - connector before you can use it in your cases. Refer to the add connectors - API. If you set a default connector, it is automatically selected when you - create cases in Kibana. If you use the create case API, however, you must - still specify all of the connector details. - tags: - - cases - - kibana - parameters: - - $ref: ../components/headers/kbn_xsrf.yaml - requestBody: - content: - application/json: - schema: - type: object - properties: - closure_type: - $ref: '../components/schemas/closure_types.yaml' - connector: - description: An object that contains the connector configuration. - type: object - properties: - $ref: '../components/schemas/connector_properties.yaml' - required: - - fields - - id - - name - - type - owner: - $ref: '../components/schemas/owners.yaml' - settings: - description: An object that contains the case settings. - type: object - properties: - syncAlerts: - description: Turns alert syncing on or off. - type: boolean - example: true - required: - - syncAlerts - required: - - closure_type - - connector - - owner - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - $ref: '../components/schemas/case_configure_response_properties.yaml' - servers: - - url: https://localhost:5601 - -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@connectors@_find.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@connectors@_find.yaml deleted file mode 100644 index 8e6bddd6c681d..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@connectors@_find.yaml +++ /dev/null @@ -1,28 +0,0 @@ -get: - summary: Retrieves information about connectors for cases in the default space. - operationId: getCaseConnectorsDefaultSpace - description: > - In particular, only the connectors that are supported for use in cases are - returned. You must have `read` privileges for the **Actions and Connectors** - feature in the **Management** section of the Kibana feature privileges. - tags: - - cases - - kibana - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - $ref: '../components/schemas/connector_response_properties.yaml' - examples: - findCaseResponse: - $ref: '../components/examples/find_connector_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@{configurationid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@{configurationid}.yaml deleted file mode 100644 index 204541dced9c1..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@configure@{configurationid}.yaml +++ /dev/null @@ -1,57 +0,0 @@ -patch: - summary: Updates external connection details, such as the closure type and default connector for cases in the default space. - operationId: updateCaseConfigurationDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case configuration. - Connectors are used to interface with external systems. You must create a - connector before you can use it in your cases. Refer to the add connectors - API. - tags: - - cases - - kibana - parameters: - - $ref: ../components/headers/kbn_xsrf.yaml - - $ref: ../components/parameters/configuration_id.yaml - requestBody: - content: - application/json: - schema: - type: object - properties: - closure_type: - $ref: '../components/schemas/closure_types.yaml' - connector: - description: An object that contains the connector configuration. - type: object - properties: - $ref: '../components/schemas/connector_properties.yaml' - required: - - fields - - id - - name - - type - version: - description: > - The version of the connector. To retrieve the version value, use - the get configuration API. - type: string - example: WzIwMiwxXQ== - required: - - version - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - $ref: '../components/schemas/case_configure_response_properties.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@reporters.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@reporters.yaml deleted file mode 100644 index 2578f59c0ec6d..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@reporters.yaml +++ /dev/null @@ -1,34 +0,0 @@ -get: - summary: Returns information about the users who opened cases in the default space. - operationId: getCaseReportersDefaultSpace - description: > - You must have read privileges for the **Cases** feature in the **Management**, - **Observability**, or **Security** section of the Kibana feature privileges, - depending on the owner of the cases. - The API returns information about the users as they existed at the time of - the case creation, including their name, full name, and email address. If - any of those details change thereafter or if a user is deleted, the - information returned by this API is unchanged. - tags: - - cases - - kibana - parameters: - - $ref: '../components/parameters/owner.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: object - properties: - $ref: '../components/schemas/user_properties.yaml' - examples: - getReportersResponse: - $ref: '../components/examples/get_reporters_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@status.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@status.yaml deleted file mode 100644 index 580248e0d99c1..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@status.yaml +++ /dev/null @@ -1,34 +0,0 @@ -get: - summary: Returns the number of cases that are open, closed, and in progress. - operationId: getCaseStatusDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - deprecated: true - parameters: - - $ref: '../components/parameters/owner.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - count_closed_cases: - type: integer - count_in_progress_cases: - type: integer - count_open_cases: - type: integer - examples: - getStatusResponse: - $ref: '../components/examples/get_status_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@tags.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@tags.yaml deleted file mode 100644 index f74dabea5bd0c..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@tags.yaml +++ /dev/null @@ -1,36 +0,0 @@ -get: - summary: Aggregates and returns a list of case tags in the default space. - operationId: getCaseTagsDefaultSpace - description: > - You must have read privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - tags: - - cases - - kibana - parameters: - - in: query - name: owner - description: A filter to limit the retrieved case statistics to a specific set of applications. If this parameter is omitted, the response contains tags from all cases that the user has access to read. - schema: - oneOf: - - $ref: '../components/schemas/owners.yaml' - - type: array - items: - $ref: '../components/schemas/owners.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - type: string - examples: - getTagsResponse: - $ref: '../components/examples/get_tags_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}.yaml deleted file mode 100644 index 7290e5f5fdfba..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}.yaml +++ /dev/null @@ -1,35 +0,0 @@ -get: - summary: Retrieves information about a case in the default space. - operationId: getCaseDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're seeking. - tags: - - cases - - kibana - parameters: - - $ref: ../components/parameters/case_id.yaml - - in: query - name: includeComments - description: Determines whether case comments are returned. - deprecated: true - schema: - type: boolean - default: true - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - getCaseResponse: - $ref: '../components/examples/get_case_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@alerts.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@alerts.yaml deleted file mode 100644 index e6b3ffbd8faad..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@alerts.yaml +++ /dev/null @@ -1,29 +0,0 @@ -get: - summary: Gets all alerts attached to a case in the default space. - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're seeking. - operationId: getCaseAlertsDefaultSpace - tags: - - cases - - kibana - x-technical-preview: true - parameters: - - $ref: ../components/parameters/case_id.yaml - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - $ref: '../components/schemas/alert_response_properties.yaml' - examples: - createCaseCommentResponse: - $ref: '../components/examples/get_case_alerts_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments.yaml deleted file mode 100644 index 95e49981d729d..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments.yaml +++ /dev/null @@ -1,126 +0,0 @@ -post: - summary: Adds a comment or alert to a case in the default space. - operationId: addCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're creating. - tags: - - cases - - kibana - parameters: - - $ref: '../components/headers/kbn_xsrf.yaml' - - $ref: '../components/parameters/case_id.yaml' - requestBody: - content: - application/json: - schema: - oneOf: - - $ref: '../components/schemas/add_alert_comment_request_properties.yaml' - - $ref: '../components/schemas/add_user_comment_request_properties.yaml' - examples: - createCaseCommentRequest: - $ref: '../components/examples/add_comment_request.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - createCaseCommentResponse: - $ref: '../components/examples/add_comment_response.yaml' - servers: - - url: https://localhost:5601 - -delete: - summary: Deletes all comments and alerts from a case in the default space. - operationId: deleteCaseCommentsDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: '../components/headers/kbn_xsrf.yaml' - - $ref: '../components/parameters/case_id.yaml' - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - -patch: - summary: Updates a comment or alert in a case in the default space. - operationId: updateCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're updating. - NOTE: You cannot change the comment type or the owner of a comment. - tags: - - cases - - kibana - parameters: - - $ref: '../components/headers/kbn_xsrf.yaml' - - $ref: '../components/parameters/case_id.yaml' - requestBody: - content: - application/json: - schema: - oneOf: - - $ref: '../components/schemas/update_alert_comment_request_properties.yaml' - - $ref: '../components/schemas/update_user_comment_request_properties.yaml' - examples: - updateCaseCommentRequest: - $ref: '../components/examples/update_comment_request.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - updateCaseCommentResponse: - $ref: '../components/examples/update_comment_response.yaml' - servers: - - url: https://localhost:5601 - -get: - summary: Retrieves all the comments from a case in the default space. - operationId: getAllCaseCommentsDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the **Management**, - **Observability**, or **Security** section of the Kibana feature privileges, - depending on the owner of the cases with the comments you're seeking. - tags: - - cases - - kibana - deprecated: true - parameters: - - $ref: ../components/parameters/case_id.yaml - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - anyOf: - - $ref: '../components/schemas/alert_comment_response_properties.yaml' - - $ref: '../components/schemas/user_comment_response_properties.yaml' - examples: {} - servers: - - url: https://localhost:5601 - -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments@{commentid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments@{commentid}.yaml deleted file mode 100644 index f76bd93cd8510..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@comments@{commentid}.yaml +++ /dev/null @@ -1,50 +0,0 @@ -delete: - summary: Deletes a comment or alert from a case in the default space. - operationId: deleteCaseCommentDefaultSpace - description: > - You must have `all` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the cases you're deleting. - tags: - - cases - - kibana - parameters: - - $ref: '../components/headers/kbn_xsrf.yaml' - - $ref: '../components/parameters/case_id.yaml' - - $ref: '../components/parameters/comment_id.yaml' - responses: - '204': - description: Indicates a successful call. - servers: - - url: https://localhost:5601 - -get: - summary: Retrieves a comment from a case in the default space. - operationId: getCaseCommentDefaultSpace - description: > - You must have `read` privileges for the **Cases** feature in the **Management**, - **Observability**, or **Security** section of the Kibana feature privileges, - depending on the owner of the cases with the comments you're seeking. - tags: - - cases - - kibana - parameters: - - $ref: '../components/parameters/case_id.yaml' - - $ref: '../components/parameters/comment_id.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - oneOf: - - $ref: '../components/schemas/alert_comment_response_properties.yaml' - - $ref: '../components/schemas/user_comment_response_properties.yaml' - examples: - getCaseCommentResponse: - $ref: '../components/examples/get_comment_response.yaml' - servers: - - url: https://localhost:5601 - -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@connector@{connectorid}@_push.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@connector@{connectorid}@_push.yaml deleted file mode 100644 index 7fc3a73db00b5..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@connector@{connectorid}@_push.yaml +++ /dev/null @@ -1,35 +0,0 @@ -post: - summary: Pushes a case to an external service. - description: > - You must have `all` privileges for the **Actions and Connectors** feature in - the **Management** section of the Kibana feature privileges. You must also - have `all` privileges for the **Cases** feature in the **Management**, - **Observability**, or **Security** section of the Kibana feature privileges, - depending on the owner of the case you're pushing. - operationId: pushCaseDefaultSpace - tags: - - cases - - kibana - parameters: - - $ref: '../components/parameters/case_id.yaml' - - $ref: '../components/parameters/connector_id.yaml' - - $ref: '../components/headers/kbn_xsrf.yaml' - requestBody: - content: - application/json: {} - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: object - properties: - $ref: '../components/schemas/case_response_properties.yaml' - examples: - pushCaseResponse: - $ref: '../components/examples/push_case_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 \ No newline at end of file diff --git a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@user_actions.yaml b/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@user_actions.yaml deleted file mode 100644 index 66a3d389aee14..0000000000000 --- a/x-pack/plugins/cases/docs/openapi/paths/api@cases@{caseid}@user_actions.yaml +++ /dev/null @@ -1,29 +0,0 @@ -get: - summary: Returns all user activity for a case in the default space. - description: > - You must have `read` privileges for the **Cases** feature in the - **Management**, **Observability**, or **Security** section of the Kibana - feature privileges, depending on the owner of the case you're seeking. - deprecated: true - operationId: getCaseActivityDefaultSpace - tags: - - cases - - kibana - parameters: - - $ref: '../components/parameters/case_id.yaml' - responses: - '200': - description: Indicates a successful call. - content: - application/json; charset=utf-8: - schema: - type: array - items: - $ref: '../components/schemas/user_actions_response_properties.yaml' - examples: - getCaseActivityResponse: - $ref: '../components/examples/get_case_activity_response.yaml' - servers: - - url: https://localhost:5601 -servers: - - url: https://localhost:5601 diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases.yaml index 5e891285ac8ba..59abb58531821 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases.yaml @@ -7,7 +7,6 @@ post: feature privileges, depending on the owner of the case you're creating. tags: - cases - - kibana parameters: - $ref: ../components/headers/kbn_xsrf.yaml - $ref: '../components/parameters/space_id.yaml' @@ -79,7 +78,6 @@ delete: depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: ../components/headers/kbn_xsrf.yaml - $ref: '../components/parameters/space_id.yaml' @@ -105,7 +103,6 @@ patch: feature privileges, depending on the owner of the case you're updating. tags: - cases - - kibana parameters: - $ref: ../components/headers/kbn_xsrf.yaml - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@_find.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@_find.yaml index 48801a11dea66..a260321248357 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@_find.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@_find.yaml @@ -7,7 +7,6 @@ get: feature privileges, depending on the owner of the cases you're seeking. tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' - name: defaultSearchOperator diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@alerts@{alertid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@alerts@{alertid}.yaml index 20c365947e351..24615d772b3ef 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@alerts@{alertid}.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@alerts@{alertid}.yaml @@ -8,7 +8,6 @@ get: x-technical-preview: true tags: - cases - - kibana parameters: - $ref: ../components/parameters/alert_id.yaml - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure.yaml index 2df6edb39c1ce..97306b5490956 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure.yaml @@ -7,7 +7,6 @@ get: feature privileges, depending on the owner of the case configuration. tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' - $ref: '../components/parameters/owner.yaml' @@ -39,7 +38,6 @@ post: still specify all of the connector details. tags: - cases - - kibana parameters: - $ref: ../components/headers/kbn_xsrf.yaml - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@connectors@_find.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@connectors@_find.yaml index dfbbc498d836d..0755225bad71a 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@connectors@_find.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@connectors@_find.yaml @@ -7,7 +7,6 @@ get: feature in the **Management** section of the Kibana feature privileges. tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' responses: diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@{configurationid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@{configurationid}.yaml index 18336746e830b..f727cbb0b4274 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@{configurationid}.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@configure@{configurationid}.yaml @@ -9,7 +9,6 @@ patch: connector before you can use it in your cases. Refer to the add connectors API. tags: - cases - - kibana parameters: - $ref: ../components/headers/kbn_xsrf.yaml - $ref: ../components/parameters/configuration_id.yaml diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@reporters.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@reporters.yaml index e35c2ceaf5063..93b7ac3863c99 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@reporters.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@reporters.yaml @@ -11,7 +11,6 @@ get: information returned by this API is unchanged. tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' - $ref: '../components/parameters/owner.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@status.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@status.yaml index 5d8aa302fd76f..dad05ad967728 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@status.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@status.yaml @@ -8,7 +8,6 @@ get: deprecated: true tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' - $ref: '../components/parameters/owner.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@tags.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@tags.yaml index 58f1e7369d718..6787c075cb19f 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@tags.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@tags.yaml @@ -7,7 +7,6 @@ get: feature privileges, depending on the owner of the cases you're seeking. tags: - cases - - kibana parameters: - $ref: '../components/parameters/space_id.yaml' - in: query diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}.yaml index 30c33a27a37f6..9e8ca4660c44d 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}.yaml @@ -7,7 +7,6 @@ get: feature privileges, depending on the owner of the case you're seeking. tags: - cases - - kibana parameters: - $ref: ../components/parameters/case_id.yaml - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@alerts.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@alerts.yaml index 6236078853e71..66430fd219d25 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@alerts.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@alerts.yaml @@ -8,7 +8,6 @@ get: operationId: getCaseAlerts tags: - cases - - kibana parameters: - $ref: ../components/parameters/case_id.yaml - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments.yaml index 9d139bed703e4..c8a045267a492 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments.yaml @@ -7,7 +7,6 @@ post: feature privileges, depending on the owner of the case you're creating. tags: - cases - - kibana parameters: - $ref: '../components/headers/kbn_xsrf.yaml' - $ref: '../components/parameters/case_id.yaml' @@ -46,7 +45,6 @@ delete: feature privileges, depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: '../components/headers/kbn_xsrf.yaml' - $ref: '../components/parameters/case_id.yaml' @@ -67,7 +65,6 @@ patch: NOTE: You cannot change the comment type or the owner of a comment. tags: - cases - - kibana parameters: - $ref: '../components/headers/kbn_xsrf.yaml' - $ref: '../components/parameters/case_id.yaml' @@ -107,7 +104,6 @@ get: deprecated: true tags: - cases - - kibana parameters: - $ref: '../components/parameters/case_id.yaml' - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments@{commentid}.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments@{commentid}.yaml index 2ed9456aed4db..3aac8f33bc68b 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments@{commentid}.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@comments@{commentid}.yaml @@ -7,7 +7,6 @@ delete: feature privileges, depending on the owner of the cases you're deleting. tags: - cases - - kibana parameters: - $ref: '../components/headers/kbn_xsrf.yaml' - $ref: '../components/parameters/case_id.yaml' @@ -28,7 +27,6 @@ get: depending on the owner of the cases with the comments you're seeking. tags: - cases - - kibana parameters: - $ref: '../components/parameters/case_id.yaml' - $ref: '../components/parameters/comment_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@connector@{connectorid}@_push.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@connector@{connectorid}@_push.yaml index d2291b59ec088..32caad2bc4086 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@connector@{connectorid}@_push.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@connector@{connectorid}@_push.yaml @@ -9,7 +9,6 @@ post: operationId: pushCase tags: - cases - - kibana parameters: - $ref: '../components/parameters/case_id.yaml' - $ref: '../components/parameters/connector_id.yaml' diff --git a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@user_actions.yaml b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@user_actions.yaml index 723265cfbe495..71301cf67a731 100644 --- a/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@user_actions.yaml +++ b/x-pack/plugins/cases/docs/openapi/paths/s@{spaceid}@api@cases@{caseid}@user_actions.yaml @@ -8,7 +8,6 @@ get: operationId: getCaseActivity tags: - cases - - kibana parameters: - $ref: '../components/parameters/case_id.yaml' - $ref: '../components/parameters/space_id.yaml' diff --git a/x-pack/plugins/cases/public/common/translations.ts b/x-pack/plugins/cases/public/common/translations.ts index 1dbc271e9be49..9748339878222 100644 --- a/x-pack/plugins/cases/public/common/translations.ts +++ b/x-pack/plugins/cases/public/common/translations.ts @@ -18,7 +18,7 @@ export const CANCEL = i18n.translate('xpack.cases.caseView.cancel', { export const DELETE_CASE = (quantity: number = 1) => i18n.translate('xpack.cases.confirmDeleteCase.deleteCase', { values: { quantity }, - defaultMessage: `Delete {quantity, plural, =1 {case} other {cases}}`, + defaultMessage: `Delete {quantity, plural, =1 {case} other {{quantity} cases}}`, }); export const NAME = i18n.translate('xpack.cases.caseView.name', { @@ -296,3 +296,9 @@ export const READ_ACTIONS_PERMISSIONS_ERROR_MSG = i18n.translate( 'You do not have permission to view connectors. If you would like to view connectors, contact your Kibana administrator.', } ); + +export const DELETED_CASES = (totalCases: number) => + i18n.translate('xpack.cases.containers.deletedCases', { + values: { totalCases }, + defaultMessage: 'Deleted {totalCases, plural, =1 {case} other {{totalCases} cases}}', + }); diff --git a/x-pack/plugins/cases/public/common/use_cases_toast.test.tsx b/x-pack/plugins/cases/public/common/use_cases_toast.test.tsx index e8661387e1e64..cfa2d3a6e0052 100644 --- a/x-pack/plugins/cases/public/common/use_cases_toast.test.tsx +++ b/x-pack/plugins/cases/public/common/use_cases_toast.test.tsx @@ -23,6 +23,7 @@ const useKibanaMock = useKibana as jest.Mocked; describe('Use cases toast hook', () => { const successMock = jest.fn(); + const errorMock = jest.fn(); const getUrlForApp = jest.fn().mockReturnValue(`/app/cases/${mockCase.id}`); const navigateToUrl = jest.fn(); @@ -51,6 +52,7 @@ describe('Use cases toast hook', () => { useToastsMock.mockImplementation(() => { return { addSuccess: successMock, + addError: errorMock, }; }); @@ -63,159 +65,260 @@ describe('Use cases toast hook', () => { }; }); - describe('Toast hook', () => { - it('should create a success toast when invoked with a case', () => { - const { result } = renderHook( - () => { - return useCasesToast(); - }, - { wrapper: TestProviders } - ); - result.current.showSuccessAttach({ - theCase: mockCase, + describe('showSuccessAttach', () => { + describe('Toast hook', () => { + it('should create a success toast when invoked with a case', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ + theCase: mockCase, + }); + expect(successMock).toHaveBeenCalled(); }); - expect(successMock).toHaveBeenCalled(); }); - }); - describe('toast title', () => { - it('should create a success toast when invoked with a case and a custom title', () => { - const { result } = renderHook( - () => { - return useCasesToast(); - }, - { wrapper: TestProviders } - ); - result.current.showSuccessAttach({ theCase: mockCase, title: 'Custom title' }); - validateTitle('Custom title'); - }); + describe('toast title', () => { + it('should create a success toast when invoked with a case and a custom title', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ theCase: mockCase, title: 'Custom title' }); + validateTitle('Custom title'); + }); - it('should display the alert sync title when called with an alert attachment (1 alert)', () => { - const { result } = renderHook( - () => { - return useCasesToast(); - }, - { wrapper: TestProviders } - ); - result.current.showSuccessAttach({ - theCase: mockCase, - attachments: [alertComment as SupportedCaseAttachment], + it('should display the alert sync title when called with an alert attachment (1 alert)', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ + theCase: mockCase, + attachments: [alertComment as SupportedCaseAttachment], + }); + validateTitle('An alert was added to "Another horrible breach!!'); + }); + + it('should display the alert sync title when called with an alert attachment (multiple alerts)', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + const alert = { + ...alertComment, + alertId: ['1234', '54321'], + } as SupportedCaseAttachment; + + result.current.showSuccessAttach({ + theCase: mockCase, + attachments: [alert], + }); + validateTitle('Alerts were added to "Another horrible breach!!'); + }); + + it('should display a generic title when called with a non-alert attachament', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ + theCase: mockCase, + attachments: [basicComment as SupportedCaseAttachment], + }); + validateTitle('Another horrible breach!! has been updated'); }); - validateTitle('An alert was added to "Another horrible breach!!'); }); - it('should display the alert sync title when called with an alert attachment (multiple alerts)', () => { - const { result } = renderHook( - () => { - return useCasesToast(); - }, - { wrapper: TestProviders } - ); - const alert = { - ...alertComment, - alertId: ['1234', '54321'], - } as SupportedCaseAttachment; - - result.current.showSuccessAttach({ - theCase: mockCase, - attachments: [alert], + describe('Toast content', () => { + let appMockRender: AppMockRenderer; + const onViewCaseClick = jest.fn(); + beforeEach(() => { + appMockRender = createAppMockRenderer(); + onViewCaseClick.mockReset(); + }); + + it('should create a success toast when invoked with a case and a custom content', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ theCase: mockCase, content: 'Custom content' }); + validateContent('Custom content'); + }); + + it('renders an alert-specific content when called with an alert attachment and sync on', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ + theCase: mockCase, + attachments: [alertComment as SupportedCaseAttachment], + }); + validateContent('The alert statuses are synched with the case status.'); + }); + + it('renders empty content when called with an alert attachment and sync off', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + result.current.showSuccessAttach({ + theCase: { ...mockCase, settings: { ...mockCase.settings, syncAlerts: false } }, + attachments: [alertComment as SupportedCaseAttachment], + }); + validateContent('View case'); + }); + + it('renders a correct successful message content', () => { + const result = appMockRender.render( + + ); + expect(result.getByTestId('toaster-content-sync-text')).toHaveTextContent('my content'); + expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case'); + expect(onViewCaseClick).not.toHaveBeenCalled(); + }); + + it('renders a correct successful message without content', () => { + const result = appMockRender.render( + + ); + expect(result.queryByTestId('toaster-content-sync-text')).toBeFalsy(); + expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case'); + expect(onViewCaseClick).not.toHaveBeenCalled(); + }); + + it('Calls the onViewCaseClick when clicked', () => { + const result = appMockRender.render( + + ); + userEvent.click(result.getByTestId('toaster-content-case-view-link')); + expect(onViewCaseClick).toHaveBeenCalled(); }); - validateTitle('Alerts were added to "Another horrible breach!!'); }); - it('should display a generic title when called with a non-alert attachament', () => { - const { result } = renderHook( - () => { - return useCasesToast(); - }, - { wrapper: TestProviders } - ); - result.current.showSuccessAttach({ - theCase: mockCase, - attachments: [basicComment as SupportedCaseAttachment], + describe('Toast navigation', () => { + const tests = Object.entries(OWNER_INFO).map(([owner, ownerInfo]) => [ + owner, + ownerInfo.appId, + ]); + + it.each(tests)('should navigate correctly with owner %s and appId %s', (owner, appId) => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + + result.current.showSuccessAttach({ + theCase: { ...mockCase, owner }, + title: 'Custom title', + }); + + navigateToCase(); + + expect(getUrlForApp).toHaveBeenCalledWith(appId, { + deepLinkId: 'cases', + path: '/mock-id', + }); + + expect(navigateToUrl).toHaveBeenCalledWith('/app/cases/mock-id'); + }); + + it('navigates to the current app if the owner is invalid', () => { + const { result } = renderHook( + () => { + return useCasesToast(); + }, + { wrapper: TestProviders } + ); + + result.current.showSuccessAttach({ + theCase: { ...mockCase, owner: 'in-valid' }, + title: 'Custom title', + }); + + navigateToCase(); + + expect(getUrlForApp).toHaveBeenCalledWith('testAppId', { + deepLinkId: 'cases', + path: '/mock-id', + }); }); - validateTitle('Another horrible breach!! has been updated'); }); }); - describe('Toast content', () => { - let appMockRender: AppMockRenderer; - const onViewCaseClick = jest.fn(); - beforeEach(() => { - appMockRender = createAppMockRenderer(); - onViewCaseClick.mockReset(); - }); + describe('showErrorToast', () => { + it('should show an error toast', () => { + const error = new Error('showErrorToast: an error occurred'); - it('should create a success toast when invoked with a case and a custom content', () => { const { result } = renderHook( () => { return useCasesToast(); }, { wrapper: TestProviders } ); - result.current.showSuccessAttach({ theCase: mockCase, content: 'Custom content' }); - validateContent('Custom content'); + + result.current.showErrorToast(error); + + expect(errorMock).toHaveBeenCalledWith(error, { title: error.message }); }); - it('renders an alert-specific content when called with an alert attachment and sync on', () => { + it('should override the title', () => { + const error = new Error('showErrorToast: an error occurred'); + const { result } = renderHook( () => { return useCasesToast(); }, { wrapper: TestProviders } ); - result.current.showSuccessAttach({ - theCase: mockCase, - attachments: [alertComment as SupportedCaseAttachment], - }); - validateContent('The alert statuses are synched with the case status.'); + + result.current.showErrorToast(error, { title: 'my title' }); + + expect(errorMock).toHaveBeenCalledWith(error, { title: 'my title' }); }); - it('renders empty content when called with an alert attachment and sync off', () => { + it('should not show an error toast if the error is AbortError', () => { + const error = new Error('showErrorToast: an error occurred'); + error.name = 'AbortError'; + const { result } = renderHook( () => { return useCasesToast(); }, { wrapper: TestProviders } ); - result.current.showSuccessAttach({ - theCase: { ...mockCase, settings: { ...mockCase.settings, syncAlerts: false } }, - attachments: [alertComment as SupportedCaseAttachment], - }); - validateContent('View case'); - }); - it('renders a correct successful message content', () => { - const result = appMockRender.render( - - ); - expect(result.getByTestId('toaster-content-sync-text')).toHaveTextContent('my content'); - expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case'); - expect(onViewCaseClick).not.toHaveBeenCalled(); - }); - - it('renders a correct successful message without content', () => { - const result = appMockRender.render( - - ); - expect(result.queryByTestId('toaster-content-sync-text')).toBeFalsy(); - expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case'); - expect(onViewCaseClick).not.toHaveBeenCalled(); - }); + result.current.showErrorToast(error); - it('Calls the onViewCaseClick when clicked', () => { - const result = appMockRender.render( - - ); - userEvent.click(result.getByTestId('toaster-content-case-view-link')); - expect(onViewCaseClick).toHaveBeenCalled(); + expect(errorMock).not.toHaveBeenCalled(); }); - }); - describe('Toast navigation', () => { - const tests = Object.entries(OWNER_INFO).map(([owner, ownerInfo]) => [owner, ownerInfo.appId]); + it('should show the body message if it is a ServerError', () => { + const error = new Error('showErrorToast: an error occurred'); + // @ts-expect-error: need to create a ServerError + error.body = { message: 'message error' }; - it.each(tests)('should navigate correctly with owner %s and appId %s', (owner, appId) => { const { result } = renderHook( () => { return useCasesToast(); @@ -223,22 +326,16 @@ describe('Use cases toast hook', () => { { wrapper: TestProviders } ); - result.current.showSuccessAttach({ - theCase: { ...mockCase, owner }, - title: 'Custom title', - }); + result.current.showErrorToast(error); - navigateToCase(); - - expect(getUrlForApp).toHaveBeenCalledWith(appId, { - deepLinkId: 'cases', - path: '/mock-id', + expect(errorMock).toHaveBeenCalledWith(new Error('message error'), { + title: 'message error', }); - - expect(navigateToUrl).toHaveBeenCalledWith('/app/cases/mock-id'); }); + }); - it('navigates to the current app if the owner is invalid', () => { + describe('showSuccessToast', () => { + it('should show a success toast', () => { const { result } = renderHook( () => { return useCasesToast(); @@ -246,17 +343,9 @@ describe('Use cases toast hook', () => { { wrapper: TestProviders } ); - result.current.showSuccessAttach({ - theCase: { ...mockCase, owner: 'in-valid' }, - title: 'Custom title', - }); - - navigateToCase(); + result.current.showSuccessToast('my title'); - expect(getUrlForApp).toHaveBeenCalledWith('testAppId', { - deepLinkId: 'cases', - path: '/mock-id', - }); + expect(successMock).toHaveBeenCalledWith('my title'); }); }); }); diff --git a/x-pack/plugins/cases/public/common/use_cases_toast.tsx b/x-pack/plugins/cases/public/common/use_cases_toast.tsx index 7d445a4edffac..42a358897bc62 100644 --- a/x-pack/plugins/cases/public/common/use_cases_toast.tsx +++ b/x-pack/plugins/cases/public/common/use_cases_toast.tsx @@ -5,6 +5,7 @@ * 2.0. */ +import type { ErrorToastOptions } from '@kbn/core/public'; import { EuiButtonEmpty, EuiText } from '@elastic/eui'; import React from 'react'; import styled from 'styled-components'; @@ -12,7 +13,7 @@ import { toMountPoint } from '@kbn/kibana-react-plugin/public'; import { Case, CommentType } from '../../common'; import { useKibana, useToasts } from './lib/kibana'; import { generateCaseViewPath } from './navigation'; -import { CaseAttachmentsWithoutOwner } from '../types'; +import { CaseAttachmentsWithoutOwner, ServerError } from '../types'; import { CASE_ALERT_SUCCESS_SYNC_TEXT, CASE_ALERT_SUCCESS_TOAST, @@ -98,6 +99,25 @@ function getToastContent({ const isValidOwner = (owner: string): owner is keyof typeof OWNER_INFO => Object.keys(OWNER_INFO).includes(owner); +const isServerError = (error: Error | ServerError): error is ServerError => + Object.hasOwn(error, 'body'); + +const getError = (error: Error | ServerError): Error => { + if (isServerError(error)) { + return new Error(error.body?.message); + } + + return error; +}; + +const getErrorMessage = (error: Error | ServerError): string => { + if (isServerError(error)) { + return error.body?.message ?? ''; + } + + return error.message; +}; + export const useCasesToast = () => { const { appId } = useCasesContext(); const { getUrlForApp, navigateToUrl } = useKibana().services.application; @@ -141,6 +161,14 @@ export const useCasesToast = () => { ), }); }, + showErrorToast: (error: Error | ServerError, opts?: ErrorToastOptions) => { + if (error.name !== 'AbortError') { + toasts.addError(getError(error), { title: getErrorMessage(error), ...opts }); + } + }, + showSuccessToast: (title: string) => { + toasts.addSuccess(title); + }, }; }; diff --git a/x-pack/plugins/cases/public/components/all_cases/all_cases_list.test.tsx b/x-pack/plugins/cases/public/components/all_cases/all_cases_list.test.tsx index a504bf251ff20..1cc3a5f0263e5 100644 --- a/x-pack/plugins/cases/public/components/all_cases/all_cases_list.test.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/all_cases_list.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { mount } from 'enzyme'; import moment from 'moment-timezone'; -import { act, render, waitFor, screen } from '@testing-library/react'; +import { render, waitFor, screen, act } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import userEvent from '@testing-library/user-event'; import { waitForEuiPopoverOpen } from '@elastic/eui/lib/test/rtl'; @@ -20,15 +20,12 @@ import { noDeleteCasesPermissions, TestProviders, } from '../../common/mock'; -import { casesStatus, useGetCasesMockState, mockCase, connectorsMock } from '../../containers/mock'; +import { useGetCasesMockState, connectorsMock } from '../../containers/mock'; import { StatusAll } from '../../../common/ui/types'; import { CaseSeverity, CaseStatuses } from '../../../common/api'; import { SECURITY_SOLUTION_OWNER } from '../../../common/constants'; import { getEmptyTagValue } from '../empty_value'; -import { useDeleteCases } from '../../containers/use_delete_cases'; -import { useGetCasesStatus } from '../../containers/use_get_cases_status'; -import { useUpdateCases } from '../../containers/use_bulk_update_case'; import { useKibana } from '../../common/lib/kibana'; import { AllCasesList } from './all_cases_list'; import { CasesColumns, GetCasesColumn, useCasesColumns } from './columns'; @@ -37,7 +34,6 @@ import { registerConnectorsToMockActionRegistry } from '../../common/mock/regist import { createStartServicesMock } from '../../common/lib/kibana/kibana_react.mock'; import { waitForComponentToUpdate } from '../../common/test_utils'; import { useCreateAttachments } from '../../containers/use_create_attachments'; -import { useGetCasesMetrics } from '../../containers/use_get_cases_metrics'; import { useGetConnectors } from '../../containers/configure/use_connectors'; import { useGetTags } from '../../containers/use_get_tags'; import { useUpdateCase } from '../../containers/use_update_case'; @@ -46,13 +42,10 @@ import { useGetCurrentUserProfile } from '../../containers/user_profiles/use_get import { userProfiles, userProfilesMap } from '../../containers/user_profiles/api.mock'; import { useBulkGetUserProfiles } from '../../containers/user_profiles/use_bulk_get_user_profiles'; import { useLicense } from '../../common/use_license'; +import * as api from '../../containers/api'; jest.mock('../../containers/use_create_attachments'); -jest.mock('../../containers/use_bulk_update_case'); -jest.mock('../../containers/use_delete_cases'); jest.mock('../../containers/use_get_cases'); -jest.mock('../../containers/use_get_cases_status'); -jest.mock('../../containers/use_get_cases_metrics'); jest.mock('../../containers/use_get_action_license'); jest.mock('../../containers/use_get_tags'); jest.mock('../../containers/user_profiles/use_get_current_user_profile'); @@ -66,11 +59,7 @@ jest.mock('../app/use_available_owners', () => ({ jest.mock('../../containers/use_update_case'); jest.mock('../../common/use_license'); -const useDeleteCasesMock = useDeleteCases as jest.Mock; const useGetCasesMock = useGetCases as jest.Mock; -const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; -const useGetCasesMetricsMock = useGetCasesMetrics as jest.Mock; -const useUpdateCasesMock = useUpdateCases as jest.Mock; const useGetTagsMock = useGetTags as jest.Mock; const useGetCurrentUserProfileMock = useGetCurrentUserProfile as jest.Mock; const useBulkGetUserProfilesMock = useBulkGetUserProfiles as jest.Mock; @@ -92,13 +81,7 @@ const mockKibana = () => { }; describe('AllCasesListGeneric', () => { - const dispatchResetIsDeleted = jest.fn(); - const dispatchResetIsUpdated = jest.fn(); - const handleOnDeleteConfirm = jest.fn(); - const handleToggleModal = jest.fn(); const refetchCases = jest.fn(); - const updateBulkStatus = jest.fn(); - const fetchCasesStatus = jest.fn(); const onRowClick = jest.fn(); const updateCaseProperty = jest.fn(); @@ -113,36 +96,6 @@ describe('AllCasesListGeneric', () => { refetch: refetchCases, }; - const defaultDeleteCases = { - dispatchResetIsDeleted, - handleOnDeleteConfirm, - handleToggleModal, - isDeleted: false, - isDisplayConfirmDeleteModal: false, - isLoading: false, - }; - - const defaultCasesStatus = { - ...casesStatus, - fetchCasesStatus, - isError: false, - isLoading: false, - }; - - const defaultCasesMetrics = { - mttr: 5, - isLoading: false, - fetchCasesMetrics: jest.fn(), - }; - - const defaultUpdateCases = { - isUpdated: false, - isLoading: false, - isError: false, - dispatchResetIsUpdated, - updateBulkStatus, - }; - const defaultColumnArgs = { caseDetailsNavigation: { href: jest.fn(), @@ -167,11 +120,7 @@ describe('AllCasesListGeneric', () => { beforeEach(() => { jest.clearAllMocks(); appMockRenderer = createAppMockRenderer(); - useUpdateCasesMock.mockReturnValue(defaultUpdateCases); useGetCasesMock.mockReturnValue(defaultGetCases); - useDeleteCasesMock.mockReturnValue(defaultDeleteCases); - useGetCasesStatusMock.mockReturnValue(defaultCasesStatus); - useGetCasesMetricsMock.mockReturnValue(defaultCasesMetrics); useGetTagsMock.mockReturnValue({ data: ['coke', 'pepsi'], refetch: jest.fn() }); useGetCurrentUserProfileMock.mockReturnValue({ data: userProfiles[0], isLoading: false }); useBulkGetUserProfilesMock.mockReturnValue({ data: userProfilesMap }); @@ -368,43 +317,48 @@ describe('AllCasesListGeneric', () => { expect(wrapper.find('[data-test-subj="cases-count-stats"]')).toBeTruthy(); }); - it.skip('Bulk delete', async () => { - useDeleteCasesMock - .mockReturnValueOnce({ - ...defaultDeleteCases, - isDisplayConfirmDeleteModal: false, - }) - .mockReturnValue({ - ...defaultDeleteCases, - isDisplayConfirmDeleteModal: true, - }); + it('Bulk delete', async () => { + const deleteCasesSpy = jest.spyOn(api, 'deleteCases'); + const result = appMockRenderer.render(); - const wrapper = mount( - - - - ); + act(() => { + userEvent.click(result.getByTestId('checkboxSelectAll')); + }); - wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); - wrapper.find('[data-test-subj="cases-bulk-delete-button"]').first().simulate('click'); + act(() => { + userEvent.click(result.getByText('Bulk actions')); + }); - wrapper - .find( - '[data-test-subj="confirm-delete-case-modal"] [data-test-subj="confirmModalConfirmButton"]' - ) - .last() - .simulate('click'); + await waitForEuiPopoverOpen(); + + act(() => { + userEvent.click(result.getByTestId('cases-bulk-delete-button'), undefined, { + skipPointerEventsCheck: true, + }); + }); await waitFor(() => { - expect(handleToggleModal).toBeCalled(); + expect(result.getByTestId('confirm-delete-case-modal')).toBeInTheDocument(); + }); - expect(handleOnDeleteConfirm.mock.calls[0][0]).toStrictEqual([ - ...useGetCasesMockState.data.cases.map(({ id, title }) => ({ id, title })), - { - id: mockCase.id, - title: mockCase.title, - }, - ]); + act(() => { + userEvent.click(result.getByTestId('confirmModalConfirmButton')); + }); + + await waitFor(() => { + expect(deleteCasesSpy).toHaveBeenCalledWith( + [ + 'basic-case-id', + '1', + '2', + '3', + '4', + 'case-with-alerts-id', + 'case-with-alerts-syncoff-id', + 'case-with-registered-attachment', + ], + expect.anything() + ); }); }); @@ -431,6 +385,8 @@ describe('AllCasesListGeneric', () => { }); it('Bulk close status update', async () => { + const updateCasesSpy = jest.spyOn(api, 'updateCases'); + const result = appMockRenderer.render(); const theCase = useGetCasesMockState.data.cases[0]; userEvent.click(result.getByTestId('case-status-filter')); @@ -441,10 +397,16 @@ describe('AllCasesListGeneric', () => { await waitForEuiPopoverOpen(); userEvent.click(result.getByTestId('cases-bulk-close-button')); await waitFor(() => {}); - expect(updateBulkStatus).toBeCalledWith([theCase], CaseStatuses.closed); + + expect(updateCasesSpy).toBeCalledWith( + [{ id: theCase.id, version: theCase.version, status: CaseStatuses.closed }], + expect.anything() + ); }); it('Bulk open status update', async () => { + const updateCasesSpy = jest.spyOn(api, 'updateCases'); + const result = appMockRenderer.render(); const theCase = useGetCasesMockState.data.cases[0]; userEvent.click(result.getByTestId('case-status-filter')); @@ -455,10 +417,16 @@ describe('AllCasesListGeneric', () => { await waitForEuiPopoverOpen(); userEvent.click(result.getByTestId('cases-bulk-open-button')); await waitFor(() => {}); - expect(updateBulkStatus).toBeCalledWith([theCase], CaseStatuses.open); + + expect(updateCasesSpy).toBeCalledWith( + [{ id: theCase.id, version: theCase.version, status: CaseStatuses.open }], + expect.anything() + ); }); it('Bulk in-progress status update', async () => { + const updateCasesSpy = jest.spyOn(api, 'updateCases'); + const result = appMockRenderer.render(); const theCase = useGetCasesMockState.data.cases[0]; userEvent.click(result.getByTestId('case-status-filter')); @@ -469,43 +437,11 @@ describe('AllCasesListGeneric', () => { await waitForEuiPopoverOpen(); userEvent.click(result.getByTestId('cases-bulk-in-progress-button')); await waitFor(() => {}); - expect(updateBulkStatus).toBeCalledWith([theCase], CaseStatuses['in-progress']); - }); - it('isDeleted is true, refetch', async () => { - useDeleteCasesMock.mockReturnValue({ - ...defaultDeleteCases, - isDeleted: true, - }); - - mount( - - - + expect(updateCasesSpy).toBeCalledWith( + [{ id: theCase.id, version: theCase.version, status: CaseStatuses['in-progress'] }], + expect.anything() ); - await waitFor(() => { - expect(refetchCases).toBeCalled(); - // expect(fetchCasesStatus).toBeCalled(); - expect(dispatchResetIsDeleted).toBeCalled(); - }); - }); - - it('isUpdated is true, refetch', async () => { - useUpdateCasesMock.mockReturnValue({ - ...defaultUpdateCases, - isUpdated: true, - }); - - mount( - - - - ); - await waitFor(() => { - expect(refetchCases).toBeCalled(); - // expect(fetchCasesStatus).toBeCalled(); - expect(dispatchResetIsUpdated).toBeCalled(); - }); }); it('should not render table utility bar when isSelectorView=true', async () => { @@ -769,28 +705,10 @@ describe('AllCasesListGeneric', () => { expect(wrapper.find('[data-test-subj="status-badge-in-progress"]').exists()).toBeTruthy(); }); - it('should call doRefresh if provided', async () => { - const doRefresh = jest.fn(); - - const wrapper = mount( - - - - ); - - await act(async () => { - wrapper.find('[data-test-subj="all-cases-refresh"] button').first().simulate('click'); - }); - - expect(doRefresh).toHaveBeenCalled(); - }); - it('shows Solution column if there are no set owners', async () => { - const doRefresh = jest.fn(); - const wrapper = mount( - + ); @@ -801,11 +719,9 @@ describe('AllCasesListGeneric', () => { }); it('hides Solution column if there is a set owner', async () => { - const doRefresh = jest.fn(); - const wrapper = mount( - + ); diff --git a/x-pack/plugins/cases/public/components/all_cases/all_cases_list.tsx b/x-pack/plugins/cases/public/components/all_cases/all_cases_list.tsx index 0bc5e9b14b29a..c7b2d4895f94a 100644 --- a/x-pack/plugins/cases/public/components/all_cases/all_cases_list.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/all_cases_list.tsx @@ -10,7 +10,6 @@ import { EuiProgress, EuiBasicTable, EuiTableSelectionType } from '@elastic/eui' import { difference, head, isEmpty } from 'lodash/fp'; import styled, { css } from 'styled-components'; -import { useQueryClient } from '@tanstack/react-query'; import { Case, CaseStatusWithAllStatus, @@ -38,11 +37,8 @@ import { } from '../../containers/use_get_cases'; import { useBulkGetUserProfiles } from '../../containers/user_profiles/use_bulk_get_user_profiles'; import { useGetCurrentUserProfile } from '../../containers/user_profiles/use_get_current_user_profile'; -import { - USER_PROFILES_BULK_GET_CACHE_KEY, - USER_PROFILES_CACHE_KEY, -} from '../../containers/constants'; import { getAllPermissionsExceptFrom } from '../../utils/permissions'; +import { useIsLoadingCases } from './use_is_loading_cases'; const ProgressLoader = styled(EuiProgress)` ${({ $isShow }: { $isShow: boolean }) => @@ -64,14 +60,13 @@ export interface AllCasesListProps { hiddenStatuses?: CaseStatusWithAllStatus[]; isSelectorView?: boolean; onRowClick?: (theCase?: Case) => void; - doRefresh?: () => void; } export const AllCasesList = React.memo( - ({ hiddenStatuses = [], isSelectorView = false, onRowClick, doRefresh }) => { + ({ hiddenStatuses = [], isSelectorView = false, onRowClick }) => { const { owner, permissions } = useCasesContext(); const availableSolutions = useAvailableCasesOwners(getAllPermissionsExceptFrom('delete')); - const [refresh, setRefresh] = useState(0); + const isLoading = useIsLoadingCases(); const hasOwner = !!owner.length; @@ -80,19 +75,15 @@ export const AllCasesList = React.memo( ...(!isEmpty(hiddenStatuses) && firstAvailableStatus && { status: firstAvailableStatus }), owner: hasOwner ? owner : availableSolutions, }; + const [filterOptions, setFilterOptions] = useState({ ...DEFAULT_FILTER_OPTIONS, ...initialFilterOptions, }); const [queryParams, setQueryParams] = useState(DEFAULT_QUERY_PARAMS); const [selectedCases, setSelectedCases] = useState([]); - const queryClient = useQueryClient(); - const { - data = initialData, - isFetching: isLoadingCases, - refetch: refetchCases, - } = useGetCases({ + const { data = initialData, isFetching: isLoadingCases } = useGetCases({ filterOptions, queryParams, }); @@ -126,41 +117,13 @@ export const AllCasesList = React.memo( [queryParams.sortField, queryParams.sortOrder] ); - const filterRefetch = useRef<() => void>(); const tableRef = useRef(null); - const [isLoading, handleIsLoading] = useState(false); - - const setFilterRefetch = useCallback( - (refetchFilter: () => void) => { - filterRefetch.current = refetchFilter; - }, - [filterRefetch] - ); const deselectCases = useCallback(() => { setSelectedCases([]); tableRef.current?.setSelection([]); }, [setSelectedCases]); - const refreshCases = useCallback( - (dataRefresh = true) => { - deselectCases(); - if (dataRefresh) { - refetchCases(); - queryClient.refetchQueries([USER_PROFILES_CACHE_KEY, USER_PROFILES_BULK_GET_CACHE_KEY]); - - setRefresh((currRefresh: number) => currRefresh + 1); - } - if (doRefresh) { - doRefresh(); - } - if (filterRefetch.current != null) { - filterRefetch.current(); - } - }, - [deselectCases, doRefresh, queryClient, refetchCases] - ); - const tableOnChangeCallback = useCallback( ({ page, sort }: EuiBasicTableOnChange) => { let newQueryParams = queryParams; @@ -179,9 +142,9 @@ export const AllCasesList = React.memo( }; } setQueryParams(newQueryParams); - refreshCases(false); + deselectCases(); }, - [queryParams, refreshCases, setQueryParams] + [queryParams, deselectCases, setQueryParams] ); const onFilterChangedCallback = useCallback( @@ -229,9 +192,8 @@ export const AllCasesList = React.memo( } : {}), })); - refreshCases(false); }, - [deselectCases, refreshCases, hasOwner, availableSolutions, owner] + [deselectCases, hasOwner, availableSolutions, owner] ); /** @@ -244,8 +206,6 @@ export const AllCasesList = React.memo( filterStatus: filterOptions.status ?? StatusAll, userProfiles: userProfiles ?? new Map(), currentUserProfile, - handleIsLoading, - refreshCases, isSelectorView, connectors, onRowClick, @@ -286,7 +246,7 @@ export const AllCasesList = React.memo( className="essentialAnimation" $isShow={isLoading || isLoadingCases} /> - {!isSelectorView ? : null} + {!isSelectorView ? : null} ( owner: filterOptions.owner, severity: filterOptions.severity, }} - setFilterRefetch={setFilterRefetch} hiddenStatuses={hiddenStatuses} displayCreateCaseButton={isSelectorView} onCreateCasePressed={onRowClick} @@ -315,20 +274,19 @@ export const AllCasesList = React.memo( data={data} filterOptions={filterOptions} goToCreateCase={onRowClick} - handleIsLoading={handleIsLoading} isCasesLoading={isLoadingCases} isCommentUpdating={isLoadingCases} isDataEmpty={isDataEmpty} isSelectorView={isSelectorView} onChange={tableOnChangeCallback} pagination={pagination} - refreshCases={refreshCases} selectedCases={selectedCases} selection={euiBasicTableSelectionProps} showActions={showActions} sorting={sorting} tableRef={tableRef} tableRowProps={tableRowProps} + deselectCases={deselectCases} /> ); diff --git a/x-pack/plugins/cases/public/components/all_cases/cases_metrics.test.tsx b/x-pack/plugins/cases/public/components/all_cases/cases_metrics.test.tsx index 6141527d59f42..323f9deead3eb 100644 --- a/x-pack/plugins/cases/public/components/all_cases/cases_metrics.test.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/cases_metrics.test.tsx @@ -5,46 +5,29 @@ * 2.0. */ -import { within } from '@testing-library/dom'; +import { waitFor, within } from '@testing-library/react'; import React from 'react'; import { AppMockRenderer, createAppMockRenderer } from '../../common/mock'; -import { useGetCasesMetrics } from '../../containers/use_get_cases_metrics'; -import { useGetCasesStatus } from '../../containers/use_get_cases_status'; import { CasesMetrics } from './cases_metrics'; -jest.mock('../../containers/use_get_cases_metrics'); -jest.mock('../../containers/use_get_cases_status'); - -const useGetCasesMetricsMock = useGetCasesMetrics as jest.Mock; -const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; +jest.mock('../../api'); describe('Cases metrics', () => { - useGetCasesStatusMock.mockReturnValue({ - countOpenCases: 2, - countInProgressCases: 3, - countClosedCases: 4, - isLoading: false, - fetchCasesStatus: jest.fn(), - }); - useGetCasesMetricsMock.mockReturnValue({ - // 600 seconds = 10m - mttr: 600, - isLoading: false, - fetchCasesMetrics: jest.fn(), - }); - let appMockRenderer: AppMockRenderer; beforeEach(() => { appMockRenderer = createAppMockRenderer(); }); - it('renders the correct stats', () => { - const result = appMockRenderer.render(); - expect(result.getByTestId('cases-metrics-stats')).toBeTruthy(); - expect(within(result.getByTestId('openStatsHeader')).getByText(2)).toBeTruthy(); - expect(within(result.getByTestId('inProgressStatsHeader')).getByText(3)).toBeTruthy(); - expect(within(result.getByTestId('closedStatsHeader')).getByText(4)).toBeTruthy(); - expect(within(result.getByTestId('mttrStatsHeader')).getByText('10m')).toBeTruthy(); + it('renders the correct stats', async () => { + const result = appMockRenderer.render(); + + await waitFor(() => { + expect(result.getByTestId('cases-metrics-stats')).toBeTruthy(); + expect(within(result.getByTestId('openStatsHeader')).getByText(20)).toBeTruthy(); + expect(within(result.getByTestId('inProgressStatsHeader')).getByText(40)).toBeTruthy(); + expect(within(result.getByTestId('closedStatsHeader')).getByText(130)).toBeTruthy(); + expect(within(result.getByTestId('mttrStatsHeader')).getByText('12s')).toBeTruthy(); + }); }); }); diff --git a/x-pack/plugins/cases/public/components/all_cases/cases_metrics.tsx b/x-pack/plugins/cases/public/components/all_cases/cases_metrics.tsx index e75f0fd8a6708..ca6434aa11c26 100644 --- a/x-pack/plugins/cases/public/components/all_cases/cases_metrics.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/cases_metrics.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { FunctionComponent, useEffect, useMemo } from 'react'; +import React, { useMemo } from 'react'; import { EuiDescriptionList, EuiFlexGroup, @@ -22,9 +22,6 @@ import { StatusStats } from '../status/status_stats'; import { useGetCasesMetrics } from '../../containers/use_get_cases_metrics'; import { ATTC_DESCRIPTION, ATTC_STAT } from './translations'; -interface CountProps { - refresh?: number; -} const MetricsFlexGroup = styled.div` ${({ theme }) => css` .euiFlexGroup { @@ -40,29 +37,23 @@ const MetricsFlexGroup = styled.div` `} `; -export const CasesMetrics: FunctionComponent = ({ refresh }) => { +export const CasesMetrics: React.FC = () => { const { - countOpenCases, - countInProgressCases, - countClosedCases, + data: { countOpenCases, countInProgressCases, countClosedCases } = { + countOpenCases: 0, + countInProgressCases: 0, + countClosedCases: 0, + }, isLoading: isCasesStatusLoading, - fetchCasesStatus, } = useGetCasesStatus(); - const { mttr, isLoading: isCasesMetricsLoading, fetchCasesMetrics } = useGetCasesMetrics(); + const { data: { mttr } = { mttr: 0 }, isLoading: isCasesMetricsLoading } = useGetCasesMetrics(); const mttrValue = useMemo( () => (mttr != null ? prettyMilliseconds(mttr * 1000, { compact: true, verbose: false }) : '-'), [mttr] ); - useEffect(() => { - if (refresh != null) { - fetchCasesStatus(); - fetchCasesMetrics(); - } - }, [fetchCasesMetrics, fetchCasesStatus, refresh]); - return ( diff --git a/x-pack/plugins/cases/public/components/all_cases/columns.tsx b/x-pack/plugins/cases/public/components/all_cases/columns.tsx index 00e9fb077589a..948abdbbcd2f3 100644 --- a/x-pack/plugins/cases/public/components/all_cases/columns.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/columns.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useMemo, useState } from 'react'; import { EuiBadgeGroup, EuiBadge, @@ -24,7 +24,7 @@ import { RIGHT_ALIGNMENT } from '@elastic/eui/lib/services'; import styled from 'styled-components'; import { UserProfileWithAvatar } from '@kbn/user-profile-components'; -import { Case, DeleteCase, UpdateByKey } from '../../../common/ui/types'; +import { Case, UpdateByKey } from '../../../common/ui/types'; import { CaseStatuses, ActionConnector, CaseSeverity } from '../../../common/api'; import { OWNER_INFO } from '../../../common/constants'; import { getEmptyTagValue } from '../empty_value'; @@ -49,6 +49,7 @@ import { getUsernameDataTestSubj } from '../user_profiles/data_test_subject'; import { CurrentUserProfile } from '../types'; import { SmallUserAvatar } from '../user_profiles/small_user_avatar'; import { useCasesFeatures } from '../../common/use_cases_features'; +import { useRefreshCases } from './use_on_refresh_cases'; export type CasesColumns = | EuiTableActionsColumnType @@ -103,8 +104,6 @@ export interface GetCasesColumn { filterStatus: string; userProfiles: Map; currentUserProfile: CurrentUserProfile; - handleIsLoading: (a: boolean) => void; - refreshCases?: (a?: boolean) => void; isSelectorView: boolean; connectors?: ActionConnector[]; onRowClick?: (theCase: Case) => void; @@ -115,41 +114,40 @@ export const useCasesColumns = ({ filterStatus, userProfiles, currentUserProfile, - handleIsLoading, - refreshCases, isSelectorView, connectors = [], onRowClick, showSolutionColumn, }: GetCasesColumn): CasesColumns[] => { - // Delete case - const { - dispatchResetIsDeleted, - handleOnDeleteConfirm, - handleToggleModal, - isDeleted, - isDisplayConfirmDeleteModal, - isLoading: isDeleting, - } = useDeleteCases(); - + const [isModalVisible, setIsModalVisible] = useState(false); + const { mutate: deleteCases } = useDeleteCases(); + const refreshCases = useRefreshCases(); const { isAlertsEnabled, caseAssignmentAuthorized } = useCasesFeatures(); const { permissions } = useCasesContext(); - - const [deleteThisCase, setDeleteThisCase] = useState({ - id: '', - title: '', - }); - + const [caseToBeDeleted, setCaseToBeDeleted] = useState(); const { updateCaseProperty, isLoading: isLoadingUpdateCase } = useUpdateCase(); - const toggleDeleteModal = useCallback( - (deleteCase: Case) => { - handleToggleModal(); - setDeleteThisCase({ id: deleteCase.id, title: deleteCase.title }); + const closeModal = useCallback(() => setIsModalVisible(false), []); + const openModal = useCallback(() => setIsModalVisible(true), []); + + const onDeleteAction = useCallback( + (theCase: Case) => { + openModal(); + setCaseToBeDeleted(theCase.id); }, - [handleToggleModal] + [openModal] ); + const onConfirmDeletion = useCallback(() => { + closeModal(); + if (caseToBeDeleted) { + deleteCases({ + caseIds: [caseToBeDeleted], + successToasterTitle: i18n.DELETED_CASES(1), + }); + } + }, [caseToBeDeleted, closeModal, deleteCases]); + const handleDispatchUpdate = useCallback( ({ updateKey, updateValue, caseData }: UpdateByKey) => { updateCaseProperty({ @@ -157,7 +155,7 @@ export const useCasesColumns = ({ updateValue, caseData, onSuccess: () => { - if (refreshCases != null) refreshCases(); + refreshCases(); }, }); }, @@ -167,9 +165,9 @@ export const useCasesColumns = ({ const actions = useMemo( () => getActions({ - deleteCaseOnClick: toggleDeleteModal, + deleteCaseOnClick: onDeleteAction, }), - [toggleDeleteModal] + [onDeleteAction] ); const assignCaseAction = useCallback( @@ -181,17 +179,6 @@ export const useCasesColumns = ({ [onRowClick] ); - useEffect(() => { - handleIsLoading(isDeleting || isLoadingUpdateCase); - }, [handleIsLoading, isDeleting, isLoadingUpdateCase]); - - useEffect(() => { - if (isDeleted) { - if (refreshCases != null) refreshCases(); - dispatchResetIsDeleted(); - } - }, [isDeleted, dispatchResetIsDeleted, refreshCases]); - return [ { name: i18n.NAME, @@ -421,12 +408,13 @@ export const useCasesColumns = ({ name: ( <> {i18n.ACTIONS} - + {isModalVisible ? ( + + ) : null} ), actions, diff --git a/x-pack/plugins/cases/public/components/all_cases/index.test.tsx b/x-pack/plugins/cases/public/components/all_cases/index.test.tsx index 6fd1556f7d4e1..55777dd5bd34c 100644 --- a/x-pack/plugins/cases/public/components/all_cases/index.test.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/index.test.tsx @@ -15,8 +15,7 @@ import { noCreateCasesPermissions, } from '../../common/mock'; import { useGetActionLicense } from '../../containers/use_get_action_license'; -import { casesStatus, connectorsMock, useGetCasesMockState } from '../../containers/mock'; -import { useGetCasesStatus } from '../../containers/use_get_cases_status'; +import { connectorsMock, useGetCasesMockState } from '../../containers/mock'; import { useGetConnectors } from '../../containers/configure/use_connectors'; import { useGetTags } from '../../containers/use_get_tags'; import { useGetCases } from '../../containers/use_get_cases'; @@ -33,13 +32,12 @@ jest.mock('../../containers/use_get_action_license', () => { jest.mock('../../containers/configure/use_connectors'); jest.mock('../../containers/api'); jest.mock('../../containers/use_get_cases'); -jest.mock('../../containers/use_get_cases_status'); jest.mock('../../containers/user_profiles/use_get_current_user_profile'); jest.mock('../../containers/user_profiles/use_bulk_get_user_profiles'); +jest.mock('../../api'); const useGetConnectorsMock = useGetConnectors as jest.Mock; const useGetCasesMock = useGetCases as jest.Mock; -const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; const useGetActionLicenseMock = useGetActionLicense as jest.Mock; const useGetCurrentUserProfileMock = useGetCurrentUserProfile as jest.Mock; const useBulkGetUserProfilesMock = useBulkGetUserProfiles as jest.Mock; @@ -49,7 +47,6 @@ describe('AllCases', () => { const setFilters = jest.fn(); const setQueryParams = jest.fn(); const setSelectedCases = jest.fn(); - const fetchCasesStatus = jest.fn(); const defaultGetCases = { ...useGetCasesMockState, @@ -59,13 +56,6 @@ describe('AllCases', () => { setSelectedCases, }; - const defaultCasesStatus = { - ...casesStatus, - fetchCasesStatus, - isError: false, - isLoading: false, - }; - const defaultActionLicense = { data: null, isLoading: false, @@ -75,7 +65,6 @@ describe('AllCases', () => { beforeAll(() => { (useGetTags as jest.Mock).mockReturnValue({ data: ['coke', 'pepsi'], refetch: jest.fn() }); useGetConnectorsMock.mockImplementation(() => ({ data: connectorsMock, isLoading: false })); - useGetCasesStatusMock.mockReturnValue(defaultCasesStatus); useGetActionLicenseMock.mockReturnValue(defaultActionLicense); useGetCasesMock.mockReturnValue(defaultGetCases); @@ -142,8 +131,6 @@ describe('AllCases', () => { }); it('should render the loading spinner when loading stats', async () => { - useGetCasesStatusMock.mockReturnValue({ ...defaultCasesStatus, isLoading: true }); - const result = appMockRender.render(); await waitFor(() => { diff --git a/x-pack/plugins/cases/public/components/all_cases/table.tsx b/x-pack/plugins/cases/public/components/all_cases/table.tsx index afe653a50e4db..208c26e47648c 100644 --- a/x-pack/plugins/cases/public/components/all_cases/table.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/table.tsx @@ -29,20 +29,19 @@ interface CasesTableProps { data: Cases; filterOptions: FilterOptions; goToCreateCase?: () => void; - handleIsLoading: (a: boolean) => void; isCasesLoading: boolean; isCommentUpdating: boolean; isDataEmpty: boolean; isSelectorView?: boolean; onChange: EuiBasicTableProps['onChange']; pagination: Pagination; - refreshCases: (a?: boolean) => void; selectedCases: Case[]; selection: EuiTableSelectionType; showActions: boolean; sorting: EuiBasicTableProps['sorting']; tableRef: MutableRefObject; tableRowProps: EuiBasicTableProps['rowProps']; + deselectCases: () => void; } const Div = styled.div` @@ -54,20 +53,19 @@ export const CasesTable: FunctionComponent = ({ data, filterOptions, goToCreateCase, - handleIsLoading, isCasesLoading, isCommentUpdating, isDataEmpty, isSelectorView, onChange, pagination, - refreshCases, selectedCases, selection, showActions, sorting, tableRef, tableRowProps, + deselectCases, }) => { const { permissions } = useCasesContext(); const { getCreateCaseUrl, navigateToCreateCase } = useCreateCaseNavigation(); @@ -93,9 +91,8 @@ export const CasesTable: FunctionComponent = ({ data={data} enableBulkActions={showActions} filterOptions={filterOptions} - handleIsLoading={handleIsLoading} selectedCases={selectedCases} - refreshCases={refreshCases} + deselectCases={deselectCases} /> { expect(onFilterChanged).toBeCalledWith({ status: CaseStatuses.closed }); }); - it('should call on load setFilterRefetch', () => { - mount( - - - - ); - expect(setFilterRefetch).toHaveBeenCalled(); - }); - it('should remove tag from selected tags when tag no longer exists', () => { const ourProps = { ...props, diff --git a/x-pack/plugins/cases/public/components/all_cases/table_filters.tsx b/x-pack/plugins/cases/public/components/all_cases/table_filters.tsx index 5ab587ad31759..75fc22a9fee27 100644 --- a/x-pack/plugins/cases/public/components/all_cases/table_filters.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/table_filters.tsx @@ -19,7 +19,6 @@ import { StatusFilter } from './status_filter'; import * as i18n from './translations'; import { SeverityFilter } from './severity_filter'; import { useGetTags } from '../../containers/use_get_tags'; -import { CASE_LIST_CACHE_KEY } from '../../containers/constants'; import { DEFAULT_FILTER_OPTIONS } from '../../containers/use_get_cases'; import { AssigneesFilterPopover } from './assignees_filter'; import { CurrentUserProfile } from '../types'; @@ -31,7 +30,6 @@ interface CasesTableFiltersProps { countOpenCases: number | null; onFilterChanged: (filterOptions: Partial) => void; initial: FilterOptions; - setFilterRefetch: (val: () => void) => void; hiddenStatuses?: CaseStatusWithAllStatus[]; availableSolutions: string[]; displayCreateCaseButton?: boolean; @@ -59,7 +57,6 @@ const CasesTableFiltersComponent = ({ countInProgressCases, onFilterChanged, initial = DEFAULT_FILTER_OPTIONS, - setFilterRefetch, hiddenStatuses, availableSolutions, displayCreateCaseButton, @@ -71,19 +68,9 @@ const CasesTableFiltersComponent = ({ const [selectedTags, setSelectedTags] = useState(initial.tags); const [selectedOwner, setSelectedOwner] = useState([]); const [selectedAssignees, setSelectedAssignees] = useState([]); - const { data: tags = [], refetch: fetchTags } = useGetTags(CASE_LIST_CACHE_KEY); + const { data: tags = [] } = useGetTags(); const { caseAssignmentAuthorized } = useCasesFeatures(); - const refetch = useCallback(() => { - fetchTags(); - }, [fetchTags]); - - useEffect(() => { - if (setFilterRefetch != null) { - setFilterRefetch(refetch); - } - }, [refetch, setFilterRefetch]); - const handleSelectedAssignees = useCallback( (newAssignees: UserProfileWithAvatar[]) => { if (!isEqual(newAssignees, selectedAssignees)) { diff --git a/x-pack/plugins/cases/public/components/all_cases/translations.ts b/x-pack/plugins/cases/public/components/all_cases/translations.ts index 0c4fe02993ea3..96a683aee5077 100644 --- a/x-pack/plugins/cases/public/components/all_cases/translations.ts +++ b/x-pack/plugins/cases/public/components/all_cases/translations.ts @@ -71,10 +71,6 @@ export const CLOSED = i18n.translate('xpack.cases.caseTable.closed', { defaultMessage: 'Closed', }); -export const DELETE = i18n.translate('xpack.cases.caseTable.delete', { - defaultMessage: 'Delete', -}); - export const SELECT = i18n.translate('xpack.cases.caseTable.select', { defaultMessage: 'Select', }); @@ -134,3 +130,40 @@ export const TOTAL_ASSIGNEES_FILTERED = (total: number) => defaultMessage: '{total, plural, one {# assignee} other {# assignees}} filtered', values: { total }, }); + +export const CLOSED_CASES = ({ + totalCases, + caseTitle, +}: { + totalCases: number; + caseTitle?: string; +}) => + i18n.translate('xpack.cases.containers.closedCases', { + values: { caseTitle, totalCases }, + defaultMessage: 'Closed {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}}', + }); + +export const REOPENED_CASES = ({ + totalCases, + caseTitle, +}: { + totalCases: number; + caseTitle?: string; +}) => + i18n.translate('xpack.cases.containers.reopenedCases', { + values: { caseTitle, totalCases }, + defaultMessage: 'Opened {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}}', + }); + +export const MARK_IN_PROGRESS_CASES = ({ + totalCases, + caseTitle, +}: { + totalCases: number; + caseTitle?: string; +}) => + i18n.translate('xpack.cases.containers.markInProgressCases', { + values: { caseTitle, totalCases }, + defaultMessage: + 'Marked {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}} as in progress', + }); diff --git a/x-pack/plugins/cases/public/components/all_cases/use_is_loading_cases.tsx b/x-pack/plugins/cases/public/components/all_cases/use_is_loading_cases.tsx new file mode 100644 index 0000000000000..70f46464ed2f8 --- /dev/null +++ b/x-pack/plugins/cases/public/components/all_cases/use_is_loading_cases.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useIsMutating } from '@tanstack/react-query'; +import { casesMutationsKeys } from '../../containers/constants'; + +/** + * Returns true or false if any of the queries and mutations + * are fetching in the all cases page + */ + +export const useIsLoadingCases = (): boolean => { + const isDeletingCases = useIsMutating(casesMutationsKeys.deleteCases); + const isUpdatingCases = useIsMutating(casesMutationsKeys.updateCases); + return Boolean(isDeletingCases) || Boolean(isUpdatingCases); +}; diff --git a/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.test.tsx b/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.test.tsx new file mode 100644 index 0000000000000..cd077004b5cf9 --- /dev/null +++ b/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.test.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { act, renderHook } from '@testing-library/react-hooks'; +import { AppMockRenderer, createAppMockRenderer } from '../../common/mock'; +import { casesQueriesKeys } from '../../containers/constants'; +import { useRefreshCases } from './use_on_refresh_cases'; + +describe('useRefreshCases', () => { + let appMockRender: AppMockRenderer; + + beforeEach(() => { + appMockRender = createAppMockRenderer(); + jest.clearAllMocks(); + }); + + it('should refresh data on refresh', async () => { + const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries'); + + const { result } = renderHook(() => useRefreshCases(), { + wrapper: appMockRender.AppWrapper, + }); + + act(() => { + result.current(); + }); + + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles()); + }); +}); diff --git a/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.tsx b/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.tsx new file mode 100644 index 0000000000000..b50bed282cce1 --- /dev/null +++ b/x-pack/plugins/cases/public/components/all_cases/use_on_refresh_cases.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { casesQueriesKeys } from '../../containers/constants'; + +/** + * Using react-query queryClient to invalidate all the + * cases table page cache namespace. + * + * This effectively clears the cache for all the cases table pages and + * forces the page to fetch all the data again. Including + * all cases, user profiles, statuses, metrics, tags, etc. + */ + +export const useRefreshCases = () => { + const queryClient = useQueryClient(); + return useCallback(() => { + queryClient.invalidateQueries(casesQueriesKeys.casesList()); + queryClient.invalidateQueries(casesQueriesKeys.tags()); + queryClient.invalidateQueries(casesQueriesKeys.userProfiles()); + }, [queryClient]); +}; diff --git a/x-pack/plugins/cases/public/components/all_cases/utility_bar.tsx b/x-pack/plugins/cases/public/components/all_cases/utility_bar.tsx index a6247cedd3fac..fdfcdc17d472c 100644 --- a/x-pack/plugins/cases/public/components/all_cases/utility_bar.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/utility_bar.tsx @@ -5,8 +5,9 @@ * 2.0. */ -import React, { FunctionComponent, useCallback, useEffect, useState } from 'react'; +import React, { FunctionComponent, useCallback, useState } from 'react'; import { EuiContextMenuPanel } from '@elastic/eui'; +import { CaseStatuses } from '../../../common'; import { UtilityBar, UtilityBarAction, @@ -15,88 +16,70 @@ import { UtilityBarText, } from '../utility_bar'; import * as i18n from './translations'; -import { Cases, Case, DeleteCase, FilterOptions } from '../../../common/ui/types'; +import { Cases, Case, FilterOptions } from '../../../common/ui/types'; import { getBulkItems } from '../bulk_actions'; import { useDeleteCases } from '../../containers/use_delete_cases'; import { ConfirmDeleteCaseModal } from '../confirm_delete_case'; import { useUpdateCases } from '../../containers/use_bulk_update_case'; +import { useRefreshCases } from './use_on_refresh_cases'; -interface OwnProps { +interface Props { data: Cases; enableBulkActions: boolean; filterOptions: FilterOptions; - handleIsLoading: (a: boolean) => void; - refreshCases?: (a?: boolean) => void; selectedCases: Case[]; + deselectCases: () => void; } -type Props = OwnProps; +export const getStatusToasterMessage = (status: CaseStatuses, cases: Case[]): string => { + const totalCases = cases.length; + const caseTitle = totalCases === 1 ? cases[0].title : ''; + + if (status === CaseStatuses.open) { + return i18n.REOPENED_CASES({ totalCases, caseTitle }); + } else if (status === CaseStatuses['in-progress']) { + return i18n.MARK_IN_PROGRESS_CASES({ totalCases, caseTitle }); + } else if (status === CaseStatuses.closed) { + return i18n.CLOSED_CASES({ totalCases, caseTitle }); + } + + return ''; +}; export const CasesTableUtilityBar: FunctionComponent = ({ data, enableBulkActions = false, filterOptions, - handleIsLoading, - refreshCases, selectedCases, + deselectCases, }) => { - const [deleteCases, setDeleteCases] = useState([]); - - // Delete case - const { - dispatchResetIsDeleted, - handleOnDeleteConfirm, - handleToggleModal, - isLoading: isDeleting, - isDeleted, - isDisplayConfirmDeleteModal, - } = useDeleteCases(); + const [isModalVisible, setIsModalVisible] = useState(false); + const onCloseModal = useCallback(() => setIsModalVisible(false), []); + const refreshCases = useRefreshCases(); - // Update case - const { - dispatchResetIsUpdated, - isLoading: isUpdating, - isUpdated, - updateBulkStatus, - } = useUpdateCases(); + const { mutate: deleteCases } = useDeleteCases(); + const { mutate: updateCases } = useUpdateCases(); - useEffect(() => { - handleIsLoading(isDeleting); - }, [handleIsLoading, isDeleting]); + const toggleBulkDeleteModal = useCallback((cases: Case[]) => { + setIsModalVisible(true); + }, []); - useEffect(() => { - handleIsLoading(isUpdating); - }, [handleIsLoading, isUpdating]); - useEffect(() => { - if (isDeleted) { - if (refreshCases != null) refreshCases(); - dispatchResetIsDeleted(); - } - if (isUpdated) { - if (refreshCases != null) refreshCases(); - dispatchResetIsUpdated(); - } - }, [isDeleted, isUpdated, refreshCases, dispatchResetIsDeleted, dispatchResetIsUpdated]); - - const toggleBulkDeleteModal = useCallback( - (cases: Case[]) => { - handleToggleModal(); - - const convertToDeleteCases: DeleteCase[] = cases.map(({ id, title }) => ({ - id, - title, + const handleUpdateCaseStatus = useCallback( + (status: CaseStatuses) => { + const casesToUpdate = selectedCases.map((theCase) => ({ + status, + id: theCase.id, + version: theCase.version, })); - setDeleteCases(convertToDeleteCases); - }, - [setDeleteCases, handleToggleModal] - ); - const handleUpdateCaseStatus = useCallback( - (status: string) => { - updateBulkStatus(selectedCases, status); + updateCases({ + cases: casesToUpdate, + successToasterTitle: getStatusToasterMessage(status, selectedCases), + }); }, - [selectedCases, updateBulkStatus] + [selectedCases, updateCases] ); + const getBulkItemsPopoverContent = useCallback( (closePopover: () => void) => ( = ({ [selectedCases, filterOptions.status, toggleBulkDeleteModal, handleUpdateCaseStatus] ); + const onConfirmDeletion = useCallback(() => { + setIsModalVisible(false); + deleteCases({ + caseIds: selectedCases.map(({ id }) => id), + successToasterTitle: i18n.DELETED_CASES(selectedCases.length), + }); + }, [deleteCases, selectedCases]); + + const onRefresh = useCallback(() => { + deselectCases(); + refreshCases(); + }, [deselectCases, refreshCases]); + return ( @@ -141,20 +137,20 @@ export const CasesTableUtilityBar: FunctionComponent = ({ {i18n.REFRESH} - + {isModalVisible ? ( + + ) : null} ); }; diff --git a/x-pack/plugins/cases/public/components/bulk_actions/index.tsx b/x-pack/plugins/cases/public/components/bulk_actions/index.tsx index 8cf3a14ffd3ce..fcf2002f8882c 100644 --- a/x-pack/plugins/cases/public/components/bulk_actions/index.tsx +++ b/x-pack/plugins/cases/public/components/bulk_actions/index.tsx @@ -19,7 +19,7 @@ interface GetBulkItems { closePopover: () => void; deleteCasesAction: (cases: Case[]) => void; selectedCases: Case[]; - updateCaseStatus: (status: string) => void; + updateCaseStatus: (status: CaseStatuses) => void; } export const getBulkItems = ({ diff --git a/x-pack/plugins/cases/public/components/case_action_bar/actions.test.tsx b/x-pack/plugins/cases/public/components/case_action_bar/actions.test.tsx index 8735b94d71b2c..cf15d546415be 100644 --- a/x-pack/plugins/cases/public/components/case_action_bar/actions.test.tsx +++ b/x-pack/plugins/cases/public/components/case_action_bar/actions.test.tsx @@ -8,13 +8,14 @@ import React from 'react'; import { mount } from 'enzyme'; -import { useDeleteCases } from '../../containers/use_delete_cases'; import { noDeleteCasesPermissions, TestProviders } from '../../common/mock'; import { basicCase, basicPush } from '../../containers/mock'; import { Actions } from './actions'; import * as i18n from '../case_view/translations'; -jest.mock('../../containers/use_delete_cases'); -const useDeleteCasesMock = useDeleteCases as jest.Mock; +import * as api from '../../containers/api'; +import { waitFor } from '@testing-library/dom'; + +jest.mock('../../containers/api'); jest.mock('react-router-dom', () => { const original = jest.requireActual('react-router-dom'); @@ -26,6 +27,7 @@ jest.mock('react-router-dom', () => { }), }; }); + const defaultProps = { allCasesNavigation: { href: 'all-cases-href', @@ -34,23 +36,10 @@ const defaultProps = { caseData: basicCase, currentExternalIncident: null, }; -describe('CaseView actions', () => { - const handleOnDeleteConfirm = jest.fn(); - const handleToggleModal = jest.fn(); - const dispatchResetIsDeleted = jest.fn(); - const defaultDeleteState = { - dispatchResetIsDeleted, - handleToggleModal, - handleOnDeleteConfirm, - isLoading: false, - isError: false, - isDeleted: false, - isDisplayConfirmDeleteModal: false, - }; +describe('CaseView actions', () => { beforeEach(() => { jest.resetAllMocks(); - useDeleteCasesMock.mockImplementation(() => defaultDeleteState); }); it('clicking trash toggles modal', () => { @@ -61,10 +50,9 @@ describe('CaseView actions', () => { ); expect(wrapper.find('[data-test-subj="confirm-delete-case-modal"]').exists()).toBeFalsy(); - wrapper.find('button[data-test-subj="property-actions-ellipses"]').first().simulate('click'); wrapper.find('button[data-test-subj="property-actions-trash"]').simulate('click'); - expect(handleToggleModal).toHaveBeenCalled(); + expect(wrapper.find('[data-test-subj="confirm-delete-case-modal"]').exists()).toBeTruthy(); }); it('does not show trash icon when user does not have deletion privileges', () => { @@ -78,22 +66,26 @@ describe('CaseView actions', () => { expect(wrapper.find('button[data-test-subj="property-actions-ellipses"]').exists()).toBeFalsy(); }); - it('toggle delete modal and confirm', () => { - useDeleteCasesMock.mockImplementation(() => ({ - ...defaultDeleteState, - isDisplayConfirmDeleteModal: true, - })); + it('toggle delete modal and confirm', async () => { + const deleteCasesSpy = jest + .spyOn(api, 'deleteCases') + .mockRejectedValue(new Error('useDeleteCases: Test error')); + const wrapper = mount( ); + wrapper.find('button[data-test-subj="property-actions-ellipses"]').first().simulate('click'); + wrapper.find('button[data-test-subj="property-actions-trash"]').simulate('click'); + expect(wrapper.find('[data-test-subj="confirm-delete-case-modal"]').exists()).toBeTruthy(); wrapper.find('button[data-test-subj="confirmModalConfirmButton"]').simulate('click'); - expect(handleOnDeleteConfirm.mock.calls[0][0]).toEqual([ - { id: basicCase.id, title: basicCase.title }, - ]); + + await waitFor(() => { + expect(deleteCasesSpy).toHaveBeenCalledWith(['basic-case-id'], expect.anything()); + }); }); it('displays active incident link', () => { diff --git a/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx b/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx index 975cf89fc1031..2481822f76b8d 100644 --- a/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx +++ b/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx @@ -6,7 +6,7 @@ */ import { isEmpty } from 'lodash/fp'; -import React, { useMemo } from 'react'; +import React, { useCallback, useMemo, useState } from 'react'; import { EuiFlexItem } from '@elastic/eui'; import * as i18n from '../case_view/translations'; import { useDeleteCases } from '../../containers/use_delete_cases'; @@ -23,11 +23,18 @@ interface CaseViewActions { } const ActionsComponent: React.FC = ({ caseData, currentExternalIncident }) => { - // Delete case - const { handleToggleModal, handleOnDeleteConfirm, isDeleted, isDisplayConfirmDeleteModal } = - useDeleteCases(); + const { mutate: deleteCases } = useDeleteCases(); const { navigateToAllCases } = useAllCasesNavigation(); const { permissions } = useCasesContext(); + const [isModalVisible, setIsModalVisible] = useState(false); + + const openModal = useCallback(() => { + setIsModalVisible(true); + }, []); + + const closeModal = useCallback(() => { + setIsModalVisible(false); + }, []); const propertyActions = useMemo( () => [ @@ -36,7 +43,7 @@ const ActionsComponent: React.FC = ({ caseData, currentExternal { iconType: 'trash', label: i18n.DELETE_CASE(), - onClick: handleToggleModal, + onClick: openModal, }, ] : []), @@ -50,13 +57,16 @@ const ActionsComponent: React.FC = ({ caseData, currentExternal ] : []), ], - [handleToggleModal, currentExternalIncident, permissions.delete] + [permissions.delete, openModal, currentExternalIncident] ); - if (isDeleted) { - navigateToAllCases(); - return null; - } + const onConfirmDeletion = useCallback(() => { + setIsModalVisible(false); + deleteCases( + { caseIds: [caseData.id], successToasterTitle: i18n.DELETED_CASES(1) }, + { onSuccess: navigateToAllCases } + ); + }, [caseData.id, deleteCases, navigateToAllCases]); if (propertyActions.length === 0) { return null; @@ -65,12 +75,13 @@ const ActionsComponent: React.FC = ({ caseData, currentExternal return ( - + {isModalVisible ? ( + + ) : null} ); }; diff --git a/x-pack/plugins/cases/public/components/case_view/index.test.tsx b/x-pack/plugins/cases/public/components/case_view/index.test.tsx index 20cf2c8d0d9b4..6a5fd8fad8113 100644 --- a/x-pack/plugins/cases/public/components/case_view/index.test.tsx +++ b/x-pack/plugins/cases/public/components/case_view/index.test.tsx @@ -30,7 +30,7 @@ import { AppMockRenderer, createAppMockRenderer } from '../../common/mock'; import CaseView from '.'; import { waitFor } from '@testing-library/dom'; import { useGetTags } from '../../containers/use_get_tags'; -import { CASE_VIEW_CACHE_KEY } from '../../containers/constants'; +import { casesQueriesKeys } from '../../containers/constants'; import { alertsHit, caseViewProps, @@ -173,7 +173,8 @@ describe('CaseView', () => { const queryClientSpy = jest.spyOn(appMockRenderer.queryClient, 'invalidateQueries'); const result = appMockRenderer.render(); userEvent.click(result.getByTestId('case-refresh')); - expect(queryClientSpy).toHaveBeenCalledWith(['case']); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.caseView()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags()); }); describe('when a `refreshRef` prop is provided', () => { @@ -205,7 +206,8 @@ describe('CaseView', () => { it('should refresh actions and comments', async () => { refreshRef!.current!.refreshCase(); await waitFor(() => { - expect(queryClientSpy).toHaveBeenCalledWith([CASE_VIEW_CACHE_KEY]); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.caseView()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags()); }); }); }); diff --git a/x-pack/plugins/cases/public/components/case_view/use_on_refresh_case_view_page.tsx b/x-pack/plugins/cases/public/components/case_view/use_on_refresh_case_view_page.tsx index 396f180a074a0..d12ddc258e761 100644 --- a/x-pack/plugins/cases/public/components/case_view/use_on_refresh_case_view_page.tsx +++ b/x-pack/plugins/cases/public/components/case_view/use_on_refresh_case_view_page.tsx @@ -7,7 +7,7 @@ import { useCallback } from 'react'; import { useQueryClient } from '@tanstack/react-query'; -import { CASE_TAGS_CACHE_KEY, CASE_VIEW_CACHE_KEY } from '../../containers/constants'; +import { casesQueriesKeys } from '../../containers/constants'; /** * Using react-query queryClient to invalidate all the @@ -17,10 +17,11 @@ import { CASE_TAGS_CACHE_KEY, CASE_VIEW_CACHE_KEY } from '../../containers/const * forces the page to fetch all the data again. Including * metrics, actions, comments, etc. */ + export const useRefreshCaseViewPage = () => { const queryClient = useQueryClient(); return useCallback(() => { - queryClient.invalidateQueries([CASE_VIEW_CACHE_KEY]); - queryClient.invalidateQueries([CASE_TAGS_CACHE_KEY]); + queryClient.invalidateQueries(casesQueriesKeys.caseView()); + queryClient.invalidateQueries(casesQueriesKeys.tags()); }, [queryClient]); }; diff --git a/x-pack/plugins/cases/public/components/confirm_delete_case/index.tsx b/x-pack/plugins/cases/public/components/confirm_delete_case/index.tsx index ce8287310fb17..e1c4e0c1fa02d 100644 --- a/x-pack/plugins/cases/public/components/confirm_delete_case/index.tsx +++ b/x-pack/plugins/cases/public/components/confirm_delete_case/index.tsx @@ -10,35 +10,28 @@ import { EuiConfirmModal } from '@elastic/eui'; import * as i18n from './translations'; interface ConfirmDeleteCaseModalProps { - caseTitle: string; - isModalVisible: boolean; - caseQuantity?: number; + totalCasesToBeDeleted: number; onCancel: () => void; onConfirm: () => void; } const ConfirmDeleteCaseModalComp: React.FC = ({ - caseTitle, - isModalVisible, - caseQuantity = 1, + totalCasesToBeDeleted, onCancel, onConfirm, }) => { - if (!isModalVisible) { - return null; - } return ( - {i18n.CONFIRM_QUESTION(caseQuantity)} + {i18n.CONFIRM_QUESTION(totalCasesToBeDeleted)} ); }; diff --git a/x-pack/plugins/cases/public/components/confirm_delete_case/translations.ts b/x-pack/plugins/cases/public/components/confirm_delete_case/translations.ts index f8e4ab2a83a73..e6f5072f08f89 100644 --- a/x-pack/plugins/cases/public/components/confirm_delete_case/translations.ts +++ b/x-pack/plugins/cases/public/components/confirm_delete_case/translations.ts @@ -14,12 +14,6 @@ export const DELETE_TITLE = (caseTitle: string) => defaultMessage: 'Delete "{caseTitle}"', }); -export const DELETE_SELECTED_CASES = (quantity: number, title: string) => - i18n.translate('xpack.cases.confirmDeleteCase.selectedCases', { - values: { quantity, title }, - defaultMessage: 'Delete "{quantity, plural, =1 {{title}} other {Selected {quantity} cases}}"', - }); - export const CONFIRM_QUESTION = (quantity: number) => i18n.translate('xpack.cases.confirmDeleteCase.confirmQuestion', { values: { quantity }, diff --git a/x-pack/plugins/cases/public/components/user_profiles/no_matches.test.tsx b/x-pack/plugins/cases/public/components/user_profiles/no_matches.test.tsx index 3471aad3fec3c..e2d23dfd988e1 100644 --- a/x-pack/plugins/cases/public/components/user_profiles/no_matches.test.tsx +++ b/x-pack/plugins/cases/public/components/user_profiles/no_matches.test.tsx @@ -13,6 +13,6 @@ describe('NoMatches', () => { it('renders the no matches messages', () => { render(); - expect(screen.getByText('No matching users with required access.')); + expect(screen.getByText("User doesn't exist or is unavailable")); }); }); diff --git a/x-pack/plugins/cases/public/components/user_profiles/no_matches.tsx b/x-pack/plugins/cases/public/components/user_profiles/no_matches.tsx index 638d705fade86..ccd27b123f235 100644 --- a/x-pack/plugins/cases/public/components/user_profiles/no_matches.tsx +++ b/x-pack/plugins/cases/public/components/user_profiles/no_matches.tsx @@ -5,7 +5,15 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiSpacer, EuiText, EuiTextAlign } from '@elastic/eui'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiIcon, + EuiLink, + EuiSpacer, + EuiText, + EuiTextAlign, +} from '@elastic/eui'; import React from 'react'; import * as i18n from './translations'; @@ -25,11 +33,18 @@ const NoMatchesComponent: React.FC = () => { - {i18n.NO_MATCHING_USERS} + {i18n.USER_DOES_NOT_EXIST}
- {i18n.TRY_MODIFYING_SEARCH} + {i18n.MODIFY_SEARCH} +
+ + {i18n.LEARN_PRIVILEGES_GRANT_ACCESS} +
diff --git a/x-pack/plugins/cases/public/components/user_profiles/translations.ts b/x-pack/plugins/cases/public/components/user_profiles/translations.ts index db76408759bec..2624ec834cd2e 100644 --- a/x-pack/plugins/cases/public/components/user_profiles/translations.ts +++ b/x-pack/plugins/cases/public/components/user_profiles/translations.ts @@ -44,12 +44,19 @@ export const ASSIGNEES = i18n.translate('xpack.cases.userProfile.assigneesTitle' defaultMessage: 'Assignees', }); -export const NO_MATCHING_USERS = i18n.translate('xpack.cases.userProfiles.noMatchingUsers', { - defaultMessage: 'No matching users with required access.', +export const USER_DOES_NOT_EXIST = i18n.translate('xpack.cases.userProfiles.userDoesNotExist', { + defaultMessage: "User doesn't exist or is unavailable", }); -export const TRY_MODIFYING_SEARCH = i18n.translate('xpack.cases.userProfiles.tryModifyingSearch', { - defaultMessage: 'Try modifying your search.', +export const LEARN_PRIVILEGES_GRANT_ACCESS = i18n.translate( + 'xpack.cases.userProfiles.learnPrivileges', + { + defaultMessage: 'Learn what privileges grant access to cases.', + } +); + +export const MODIFY_SEARCH = i18n.translate('xpack.cases.userProfiles.modifySearch', { + defaultMessage: "Modify your search or check the user's privileges.", }); export const INVALID_ASSIGNEES = i18n.translate('xpack.cases.create.invalidAssignees', { diff --git a/x-pack/plugins/cases/public/containers/__mocks__/api.ts b/x-pack/plugins/cases/public/containers/__mocks__/api.ts index 2b43135123080..d01f927d3c324 100644 --- a/x-pack/plugins/cases/public/containers/__mocks__/api.ts +++ b/x-pack/plugins/cases/public/containers/__mocks__/api.ts @@ -8,7 +8,6 @@ import { ActionLicense, Cases, - BulkUpdateStatus, Case, CasesStatus, CaseUserActions, @@ -28,7 +27,7 @@ import { pushedCase, tags, } from '../mock'; -import { ResolvedCase, SeverityAll } from '../../../common/ui/types'; +import { CaseUpdateRequest, ResolvedCase, SeverityAll } from '../../../common/ui/types'; import { CasePatchRequest, CasePostRequest, @@ -99,8 +98,8 @@ export const patchCase = async ( signal: AbortSignal ): Promise => Promise.resolve([basicCase]); -export const patchCasesStatus = async ( - cases: BulkUpdateStatus[], +export const updateCases = async ( + cases: CaseUpdateRequest[], signal: AbortSignal ): Promise => Promise.resolve(allCases.cases); diff --git a/x-pack/plugins/cases/public/containers/api.test.tsx b/x-pack/plugins/cases/public/containers/api.test.tsx index e51224dc593dc..d5618ff8a7e9b 100644 --- a/x-pack/plugins/cases/public/containers/api.test.tsx +++ b/x-pack/plugins/cases/public/containers/api.test.tsx @@ -25,7 +25,7 @@ import { getCaseUserActions, getTags, patchCase, - patchCasesStatus, + updateCases, patchComment, postCase, createAttachments, @@ -449,7 +449,7 @@ describe('Cases API', () => { }); }); - describe('patchCasesStatus', () => { + describe('updateCases', () => { beforeEach(() => { fetchMock.mockClear(); fetchMock.mockResolvedValue(casesSnake); @@ -464,7 +464,7 @@ describe('Cases API', () => { ]; test('should be called with correct check url, method, signal', async () => { - await patchCasesStatus(data, abortCtrl.signal); + await updateCases(data, abortCtrl.signal); expect(fetchMock).toHaveBeenCalledWith(`${CASES_URL}`, { method: 'PATCH', body: JSON.stringify({ cases: data }), @@ -473,7 +473,7 @@ describe('Cases API', () => { }); test('should return correct response should not covert to camel case registered attachments', async () => { - const resp = await patchCasesStatus(data, abortCtrl.signal); + const resp = await updateCases(data, abortCtrl.signal); expect(resp).toEqual(cases); }); }); diff --git a/x-pack/plugins/cases/public/containers/api.ts b/x-pack/plugins/cases/public/containers/api.ts index 697635030eb49..ff8d05ef653d9 100644 --- a/x-pack/plugins/cases/public/containers/api.ts +++ b/x-pack/plugins/cases/public/containers/api.ts @@ -10,6 +10,7 @@ import { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common/const import { isEmpty } from 'lodash'; import { Cases, + CaseUpdateRequest, FetchCasesProps, ResolvedCase, SeverityAll, @@ -58,7 +59,6 @@ import { import { ActionLicense, - BulkUpdateStatus, Case, SingleCaseMetrics, SingleCaseMetricsFeature, @@ -238,8 +238,8 @@ export const patchCase = async ( return convertCasesToCamelCase(decodeCasesResponse(response)); }; -export const patchCasesStatus = async ( - cases: BulkUpdateStatus[], +export const updateCases = async ( + cases: CaseUpdateRequest[], signal: AbortSignal ): Promise => { const response = await KibanaServices.get().http.fetch(CASES_URL, { diff --git a/x-pack/plugins/cases/public/containers/configure/use_action_types.tsx b/x-pack/plugins/cases/public/containers/configure/use_action_types.tsx index 76a48e5d09ca3..8503ccd6eddf8 100644 --- a/x-pack/plugins/cases/public/containers/configure/use_action_types.tsx +++ b/x-pack/plugins/cases/public/containers/configure/use_action_types.tsx @@ -9,13 +9,13 @@ import { useQuery } from '@tanstack/react-query'; import * as i18n from '../translations'; import { fetchActionTypes } from './api'; import { useToasts } from '../../common/lib/kibana'; -import { CASE_CONFIGURATION_CACHE_KEY } from '../constants'; +import { casesQueriesKeys } from '../constants'; import { ServerError } from '../../types'; export const useGetActionTypes = () => { const toasts = useToasts(); return useQuery( - [CASE_CONFIGURATION_CACHE_KEY, 'actionTypes'], + casesQueriesKeys.connectorTypes(), () => { const abortController = new AbortController(); return fetchActionTypes({ signal: abortController.signal }); diff --git a/x-pack/plugins/cases/public/containers/configure/use_connectors.tsx b/x-pack/plugins/cases/public/containers/configure/use_connectors.tsx index 95124af988fb6..5e96dd86ae985 100644 --- a/x-pack/plugins/cases/public/containers/configure/use_connectors.tsx +++ b/x-pack/plugins/cases/public/containers/configure/use_connectors.tsx @@ -9,14 +9,14 @@ import { useQuery } from '@tanstack/react-query'; import { fetchConnectors } from './api'; import { useApplicationCapabilities, useToasts } from '../../common/lib/kibana'; import * as i18n from './translations'; -import { CASE_CONNECTORS_CACHE_KEY } from '../constants'; +import { casesQueriesKeys } from '../constants'; import { ServerError } from '../../types'; export function useGetConnectors() { const toasts = useToasts(); const { actions } = useApplicationCapabilities(); return useQuery( - [CASE_CONNECTORS_CACHE_KEY], + casesQueriesKeys.connectorsList(), async () => { if (!actions.read) { return []; diff --git a/x-pack/plugins/cases/public/containers/constants.ts b/x-pack/plugins/cases/public/containers/constants.ts index a87d773303447..a6acbbd68d412 100644 --- a/x-pack/plugins/cases/public/containers/constants.ts +++ b/x-pack/plugins/cases/public/containers/constants.ts @@ -5,23 +5,36 @@ * 2.0. */ +import { SingleCaseMetricsFeature } from './types'; + export const DEFAULT_TABLE_ACTIVE_PAGE = 1; export const DEFAULT_TABLE_LIMIT = 5; -export const CASE_VIEW_CACHE_KEY = 'case'; -export const CASE_VIEW_ACTIONS_CACHE_KEY = 'user-actions'; -export const CASE_VIEW_METRICS_CACHE_KEY = 'metrics'; -export const CASE_CONFIGURATION_CACHE_KEY = 'case-configuration'; -export const CASE_LIST_CACHE_KEY = 'case-list'; -export const CASE_CONNECTORS_CACHE_KEY = 'case-connectors'; -export const CASE_LICENSE_CACHE_KEY = 'case-license-action'; -export const CASE_TAGS_CACHE_KEY = 'case-tags'; - -/** - * User profiles - */ +export const casesQueriesKeys = { + all: ['cases'] as const, + users: ['users'] as const, + connectors: ['connectors'] as const, + connectorsList: () => [...casesQueriesKeys.connectors, 'list'] as const, + casesList: () => [...casesQueriesKeys.all, 'list'] as const, + casesMetrics: () => [...casesQueriesKeys.casesList(), 'metrics'] as const, + casesStatuses: () => [...casesQueriesKeys.casesList(), 'statuses'] as const, + cases: (params: unknown) => [...casesQueriesKeys.casesList(), 'all-cases', params] as const, + caseView: () => [...casesQueriesKeys.all, 'case'] as const, + case: (id: string) => [...casesQueriesKeys.caseView(), id] as const, + caseMetrics: (id: string, features: SingleCaseMetricsFeature[]) => + [...casesQueriesKeys.case(id), 'metrics', features] as const, + userActions: (id: string, connectorId: string) => + [...casesQueriesKeys.case(id), 'user-actions', connectorId] as const, + userProfiles: () => [...casesQueriesKeys.users, 'user-profiles'] as const, + userProfilesList: (ids: string[]) => [...casesQueriesKeys.userProfiles(), ids] as const, + currentUser: () => [...casesQueriesKeys.users, 'current-user'] as const, + suggestUsers: (params: unknown) => [...casesQueriesKeys.users, 'suggest', params] as const, + connectorTypes: () => [...casesQueriesKeys.connectors, 'types'] as const, + license: () => [...casesQueriesKeys.connectors, 'license'] as const, + tags: () => [...casesQueriesKeys.all, 'tags'] as const, +}; -export const USER_PROFILES_CACHE_KEY = 'user-profiles'; -export const USER_PROFILES_SUGGEST_CACHE_KEY = 'suggest'; -export const USER_PROFILES_BULK_GET_CACHE_KEY = 'bulk-get'; -export const USER_PROFILES_GET_CURRENT_CACHE_KEY = 'get-current'; +export const casesMutationsKeys = { + deleteCases: ['delete-cases'] as const, + updateCases: ['update-cases'] as const, +}; diff --git a/x-pack/plugins/cases/public/containers/translations.ts b/x-pack/plugins/cases/public/containers/translations.ts index 72aeb66772c52..5bf4acf385fce 100644 --- a/x-pack/plugins/cases/public/containers/translations.ts +++ b/x-pack/plugins/cases/public/containers/translations.ts @@ -23,48 +23,9 @@ export const UPDATED_CASE = (caseTitle: string) => defaultMessage: 'Updated "{caseTitle}"', }); -export const DELETED_CASES = (totalCases: number, caseTitle?: string) => - i18n.translate('xpack.cases.containers.deletedCases', { - values: { caseTitle, totalCases }, - defaultMessage: 'Deleted {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}}', - }); - -export const CLOSED_CASES = ({ - totalCases, - caseTitle, -}: { - totalCases: number; - caseTitle?: string; -}) => - i18n.translate('xpack.cases.containers.closedCases', { - values: { caseTitle, totalCases }, - defaultMessage: 'Closed {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}}', - }); - -export const REOPENED_CASES = ({ - totalCases, - caseTitle, -}: { - totalCases: number; - caseTitle?: string; -}) => - i18n.translate('xpack.cases.containers.reopenedCases', { - values: { caseTitle, totalCases }, - defaultMessage: 'Opened {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}}', - }); - -export const MARK_IN_PROGRESS_CASES = ({ - totalCases, - caseTitle, -}: { - totalCases: number; - caseTitle?: string; -}) => - i18n.translate('xpack.cases.containers.markInProgressCases', { - values: { caseTitle, totalCases }, - defaultMessage: - 'Marked {totalCases, plural, =1 {"{caseTitle}"} other {{totalCases} cases}} as in progress', - }); +export const UPDATED_CASES = i18n.translate('xpack.cases.containers.updatedCases', { + defaultMessage: 'Updated cases', +}); export const SUCCESS_SEND_TO_EXTERNAL_SERVICE = (serviceName: string) => i18n.translate('xpack.cases.containers.pushToExternalService', { diff --git a/x-pack/plugins/cases/public/containers/use_bulk_update_case.test.tsx b/x-pack/plugins/cases/public/containers/use_bulk_update_case.test.tsx index d00b361828a6e..d46f79569622f 100644 --- a/x-pack/plugins/cases/public/containers/use_bulk_update_case.test.tsx +++ b/x-pack/plugins/cases/public/containers/use_bulk_update_case.test.tsx @@ -6,126 +6,89 @@ */ import { renderHook, act } from '@testing-library/react-hooks'; -import { CaseStatuses } from '../../common/api'; -import { useUpdateCases, UseUpdateCases } from './use_bulk_update_case'; -import { basicCase } from './mock'; +import { useUpdateCases } from './use_bulk_update_case'; +import { allCases } from './mock'; +import { useToasts } from '../common/lib/kibana'; import * as api from './api'; +import { createAppMockRenderer, AppMockRenderer } from '../common/mock'; +import { casesQueriesKeys } from './constants'; jest.mock('./api'); jest.mock('../common/lib/kibana'); describe('useUpdateCases', () => { const abortCtrl = new AbortController(); + const addSuccess = jest.fn(); + const addError = jest.fn(); + + (useToasts as jest.Mock).mockReturnValue({ addSuccess, addError }); + + let appMockRender: AppMockRenderer; + beforeEach(() => { + appMockRender = createAppMockRenderer(); jest.clearAllMocks(); - jest.restoreAllMocks(); }); - it('init', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - await waitForNextUpdate(); - expect(result.current).toEqual({ - isLoading: false, - isError: false, - isUpdated: false, - updateBulkStatus: result.current.updateBulkStatus, - dispatchResetIsUpdated: result.current.dispatchResetIsUpdated, - }); + it('calls the api when invoked with the correct parameters', async () => { + const spy = jest.spyOn(api, 'updateCases'); + const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), { + wrapper: appMockRender.AppWrapper, }); - }); - it('calls patchCase with correct arguments', async () => { - const spyOnPatchCases = jest.spyOn(api, 'patchCasesStatus'); - - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - await waitForNextUpdate(); - - result.current.updateBulkStatus([basicCase], CaseStatuses.closed); - await waitForNextUpdate(); - expect(spyOnPatchCases).toBeCalledWith( - [ - { - status: CaseStatuses.closed, - id: basicCase.id, - version: basicCase.version, - }, - ], - abortCtrl.signal - ); + act(() => { + result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' }); }); - }); - it('patch cases', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - await waitForNextUpdate(); - result.current.updateBulkStatus([basicCase], CaseStatuses.closed); - await waitForNextUpdate(); - expect(result.current).toEqual({ - isUpdated: true, - isLoading: false, - isError: false, - updateBulkStatus: result.current.updateBulkStatus, - dispatchResetIsUpdated: result.current.dispatchResetIsUpdated, - }); - }); + await waitForNextUpdate(); + + expect(spy).toHaveBeenCalledWith(allCases.cases, abortCtrl.signal); }); - it('set isLoading to true when posting case', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - await waitForNextUpdate(); - result.current.updateBulkStatus([basicCase], CaseStatuses.closed); + it('invalidates the queries correctly', async () => { + const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries'); + const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), { + wrapper: appMockRender.AppWrapper, + }); - expect(result.current.isLoading).toBe(true); + act(() => { + result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles()); }); - it('dispatchResetIsUpdated resets is updated', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - - await waitForNextUpdate(); - result.current.updateBulkStatus([basicCase], CaseStatuses.closed); - await waitForNextUpdate(); - expect(result.current.isUpdated).toBeTruthy(); - result.current.dispatchResetIsUpdated(); - expect(result.current.isUpdated).toBeFalsy(); + it('shows a success toaster', async () => { + const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), { + wrapper: appMockRender.AppWrapper, + }); + + act(() => { + result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(addSuccess).toHaveBeenCalledWith('Success title'); }); - it('unhappy path', async () => { - const spyOnPatchCases = jest.spyOn(api, 'patchCasesStatus'); - spyOnPatchCases.mockImplementation(() => { - throw new Error('Something went wrong'); + it('shows a toast error when the api return an error', async () => { + jest.spyOn(api, 'updateCases').mockRejectedValue(new Error('useUpdateCases: Test error')); + + const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), { + wrapper: appMockRender.AppWrapper, }); - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useUpdateCases() - ); - await waitForNextUpdate(); - result.current.updateBulkStatus([basicCase], CaseStatuses.closed); - - expect(result.current).toEqual({ - isUpdated: false, - isLoading: false, - isError: true, - updateBulkStatus: result.current.updateBulkStatus, - dispatchResetIsUpdated: result.current.dispatchResetIsUpdated, - }); + act(() => { + result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(addError).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/cases/public/containers/use_bulk_update_case.tsx b/x-pack/plugins/cases/public/containers/use_bulk_update_case.tsx index 715b0c611c3b8..e0866bf0166a6 100644 --- a/x-pack/plugins/cases/public/containers/use_bulk_update_case.tsx +++ b/x-pack/plugins/cases/public/containers/use_bulk_update_case.tsx @@ -5,149 +5,42 @@ * 2.0. */ -import { useCallback, useReducer, useRef, useEffect } from 'react'; -import { CaseStatuses } from '../../common/api'; +import { useQueryClient, useMutation } from '@tanstack/react-query'; import * as i18n from './translations'; -import { patchCasesStatus } from './api'; -import { BulkUpdateStatus, Case } from './types'; -import { useToasts } from '../common/lib/kibana'; - -interface UpdateState { - isUpdated: boolean; - isLoading: boolean; - isError: boolean; -} -type Action = - | { type: 'FETCH_INIT' } - | { type: 'FETCH_SUCCESS'; payload: boolean } - | { type: 'FETCH_FAILURE' } - | { type: 'RESET_IS_UPDATED' }; - -const dataFetchReducer = (state: UpdateState, action: Action): UpdateState => { - switch (action.type) { - case 'FETCH_INIT': - return { - ...state, - isLoading: true, - isError: false, - }; - case 'FETCH_SUCCESS': - return { - ...state, - isLoading: false, - isError: false, - isUpdated: action.payload, - }; - case 'FETCH_FAILURE': - return { - ...state, - isLoading: false, - isError: true, - }; - case 'RESET_IS_UPDATED': - return { - ...state, - isUpdated: false, - }; - default: - return state; - } -}; -export interface UseUpdateCases extends UpdateState { - updateBulkStatus: (cases: Case[], status: string) => void; - dispatchResetIsUpdated: () => void; +import { updateCases } from './api'; +import { CaseUpdateRequest } from './types'; +import { useCasesToast } from '../common/use_cases_toast'; +import { ServerError } from '../types'; +import { casesQueriesKeys, casesMutationsKeys } from './constants'; + +interface MutationArgs { + cases: CaseUpdateRequest[]; + successToasterTitle: string; } -const getStatusToasterMessage = ( - status: CaseStatuses, - messageArgs: { - totalCases: number; - caseTitle?: string; - } -): string => { - if (status === CaseStatuses.open) { - return i18n.REOPENED_CASES(messageArgs); - } else if (status === CaseStatuses['in-progress']) { - return i18n.MARK_IN_PROGRESS_CASES(messageArgs); - } else if (status === CaseStatuses.closed) { - return i18n.CLOSED_CASES(messageArgs); - } - - return ''; -}; - -export const useUpdateCases = (): UseUpdateCases => { - const [state, dispatch] = useReducer(dataFetchReducer, { - isLoading: false, - isError: false, - isUpdated: false, - }); - const toasts = useToasts(); - const isCancelledRef = useRef(false); - const abortCtrlRef = useRef(new AbortController()); - - const dispatchUpdateCases = useCallback(async (cases: BulkUpdateStatus[], action: string) => { - try { - isCancelledRef.current = false; - abortCtrlRef.current.abort(); - abortCtrlRef.current = new AbortController(); - - dispatch({ type: 'FETCH_INIT' }); - const patchResponse = await patchCasesStatus(cases, abortCtrlRef.current.signal); - - if (!isCancelledRef.current) { - const resultCount = Object.keys(patchResponse).length; - const firstTitle = patchResponse[0].title; - - dispatch({ type: 'FETCH_SUCCESS', payload: true }); - const messageArgs = { - totalCases: resultCount, - caseTitle: resultCount === 1 ? firstTitle : '', - }; +export const useUpdateCases = () => { + const queryClient = useQueryClient(); + const { showErrorToast, showSuccessToast } = useCasesToast(); - const message = - action === 'status' ? getStatusToasterMessage(patchResponse[0].status, messageArgs) : ''; - - toasts.addSuccess(message); - } - } catch (error) { - if (!isCancelledRef.current) { - if (error.name !== 'AbortError') { - toasts.addError( - error.body && error.body.message ? new Error(error.body.message) : error, - { title: i18n.ERROR_TITLE } - ); - } - dispatch({ type: 'FETCH_FAILURE' }); - } - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - const dispatchResetIsUpdated = useCallback(() => { - dispatch({ type: 'RESET_IS_UPDATED' }); - }, []); - - const updateBulkStatus = useCallback( - (cases: Case[], status: string) => { - const updateCasesStatus: BulkUpdateStatus[] = cases.map((theCase) => ({ - status, - id: theCase.id, - version: theCase.version, - })); - dispatchUpdateCases(updateCasesStatus, 'status'); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [] - ); - - useEffect( - () => () => { - isCancelledRef.current = true; - abortCtrlRef.current.abort(); + return useMutation( + ({ cases }: MutationArgs) => { + const abortCtrlRef = new AbortController(); + return updateCases(cases, abortCtrlRef.signal); }, - [] + { + mutationKey: casesMutationsKeys.updateCases, + onSuccess: (_, { successToasterTitle }) => { + queryClient.invalidateQueries(casesQueriesKeys.casesList()); + queryClient.invalidateQueries(casesQueriesKeys.tags()); + queryClient.invalidateQueries(casesQueriesKeys.userProfiles()); + + showSuccessToast(successToasterTitle); + }, + onError: (error: ServerError) => { + showErrorToast(error, { title: i18n.ERROR_DELETING }); + }, + } ); - - return { ...state, updateBulkStatus, dispatchResetIsUpdated }; }; + +export type UseUpdateCases = ReturnType; diff --git a/x-pack/plugins/cases/public/containers/use_delete_cases.test.tsx b/x-pack/plugins/cases/public/containers/use_delete_cases.test.tsx index 88f6db42144f6..623a01746e3cb 100644 --- a/x-pack/plugins/cases/public/containers/use_delete_cases.test.tsx +++ b/x-pack/plugins/cases/public/containers/use_delete_cases.test.tsx @@ -7,125 +7,88 @@ import { renderHook, act } from '@testing-library/react-hooks'; -import { useDeleteCases, UseDeleteCase } from './use_delete_cases'; +import { useDeleteCases } from './use_delete_cases'; import * as api from './api'; +import { useToasts } from '../common/lib/kibana'; +import { AppMockRenderer, createAppMockRenderer } from '../common/mock'; +import { casesQueriesKeys } from './constants'; jest.mock('./api'); jest.mock('../common/lib/kibana'); describe('useDeleteCases', () => { const abortCtrl = new AbortController(); - const deleteObj = [ - { id: '1', title: 'case 1' }, - { id: '2', title: 'case 2' }, - { id: '3', title: 'case 3' }, - ]; - const deleteArr = ['1', '2', '3']; - it('init', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); - expect(result.current).toEqual({ - isDisplayConfirmDeleteModal: false, - isLoading: false, - isError: false, - isDeleted: false, - dispatchResetIsDeleted: result.current.dispatchResetIsDeleted, - handleOnDeleteConfirm: result.current.handleOnDeleteConfirm, - handleToggleModal: result.current.handleToggleModal, - }); - }); - }); + const addSuccess = jest.fn(); + const addError = jest.fn(); - it('calls deleteCases with correct arguments', async () => { - const spyOnDeleteCases = jest.spyOn(api, 'deleteCases'); + (useToasts as jest.Mock).mockReturnValue({ addSuccess, addError }); - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); + let appMockRender: AppMockRenderer; - result.current.handleOnDeleteConfirm(deleteObj); - await waitForNextUpdate(); - expect(spyOnDeleteCases).toBeCalledWith(deleteArr, abortCtrl.signal); - }); + beforeEach(() => { + appMockRender = createAppMockRenderer(); + jest.clearAllMocks(); }); - it('deletes cases', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); - result.current.handleToggleModal(); - result.current.handleOnDeleteConfirm(deleteObj); - await waitForNextUpdate(); - expect(result.current).toEqual({ - isDisplayConfirmDeleteModal: false, - isLoading: false, - isError: false, - isDeleted: true, - dispatchResetIsDeleted: result.current.dispatchResetIsDeleted, - handleOnDeleteConfirm: result.current.handleOnDeleteConfirm, - handleToggleModal: result.current.handleToggleModal, - }); + it('calls the api when invoked with the correct parameters', async () => { + const spy = jest.spyOn(api, 'deleteCases'); + const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), { + wrapper: appMockRender.AppWrapper, + }); + + act(() => { + result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(spy).toHaveBeenCalledWith(['1', '2'], abortCtrl.signal); }); - it('resets is deleting', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); - result.current.handleToggleModal(); - result.current.handleOnDeleteConfirm(deleteObj); - await waitForNextUpdate(); - expect(result.current.isDeleted).toBeTruthy(); - result.current.handleToggleModal(); - result.current.dispatchResetIsDeleted(); - expect(result.current.isDeleted).toBeFalsy(); + it('invalidates the queries correctly', async () => { + const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries'); + const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), { + wrapper: appMockRender.AppWrapper, + }); + + act(() => { + result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags()); + expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles()); }); - it('set isLoading to true when deleting cases', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); - result.current.handleToggleModal(); - result.current.handleOnDeleteConfirm(deleteObj); - expect(result.current.isLoading).toBe(true); + it('shows a success toaster', async () => { + const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), { + wrapper: appMockRender.AppWrapper, }); + + act(() => { + result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' }); + }); + + await waitForNextUpdate(); + + expect(addSuccess).toHaveBeenCalledWith('Success title'); }); - it('unhappy path', async () => { - const spyOnDeleteCases = jest.spyOn(api, 'deleteCases'); - spyOnDeleteCases.mockImplementation(() => { - throw new Error('Something went wrong'); + it('shows a toast error when the api return an error', async () => { + jest.spyOn(api, 'deleteCases').mockRejectedValue(new Error('useDeleteCases: Test error')); + + const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), { + wrapper: appMockRender.AppWrapper, }); - await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useDeleteCases() - ); - await waitForNextUpdate(); - result.current.handleToggleModal(); - result.current.handleOnDeleteConfirm(deleteObj); - - expect(result.current).toEqual({ - isDisplayConfirmDeleteModal: false, - isLoading: false, - isError: true, - isDeleted: false, - dispatchResetIsDeleted: result.current.dispatchResetIsDeleted, - handleOnDeleteConfirm: result.current.handleOnDeleteConfirm, - handleToggleModal: result.current.handleToggleModal, - }); + act(() => { + result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' }); }); + + await waitForNextUpdate(); + + expect(addError).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/cases/public/containers/use_delete_cases.tsx b/x-pack/plugins/cases/public/containers/use_delete_cases.tsx index 7ccec4436ec0b..da2258f8f5d82 100644 --- a/x-pack/plugins/cases/public/containers/use_delete_cases.tsx +++ b/x-pack/plugins/cases/public/containers/use_delete_cases.tsx @@ -5,139 +5,41 @@ * 2.0. */ -import { useCallback, useReducer, useRef, useEffect } from 'react'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; import * as i18n from './translations'; import { deleteCases } from './api'; -import { DeleteCase } from './types'; -import { useToasts } from '../common/lib/kibana'; +import { ServerError } from '../types'; +import { casesQueriesKeys, casesMutationsKeys } from './constants'; +import { useCasesToast } from '../common/use_cases_toast'; -interface DeleteState { - isDisplayConfirmDeleteModal: boolean; - isDeleted: boolean; - isLoading: boolean; - isError: boolean; +interface MutationArgs { + caseIds: string[]; + successToasterTitle: string; } -type Action = - | { type: 'DISPLAY_MODAL'; payload: boolean } - | { type: 'FETCH_INIT' } - | { type: 'FETCH_SUCCESS'; payload: boolean } - | { type: 'FETCH_FAILURE' } - | { type: 'RESET_IS_DELETED' }; -const dataFetchReducer = (state: DeleteState, action: Action): DeleteState => { - switch (action.type) { - case 'DISPLAY_MODAL': - return { - ...state, - isDisplayConfirmDeleteModal: action.payload, - }; - case 'FETCH_INIT': - return { - ...state, - isLoading: true, - isError: false, - }; - case 'FETCH_SUCCESS': - return { - ...state, - isLoading: false, - isError: false, - isDeleted: action.payload, - }; - case 'FETCH_FAILURE': - return { - ...state, - isLoading: false, - isError: true, - }; - case 'RESET_IS_DELETED': - return { - ...state, - isDeleted: false, - }; - default: - return state; - } -}; - -export interface UseDeleteCase extends DeleteState { - dispatchResetIsDeleted: () => void; - handleOnDeleteConfirm: (cases: DeleteCase[]) => void; - handleToggleModal: () => void; -} - -export const useDeleteCases = (): UseDeleteCase => { - const [state, dispatch] = useReducer(dataFetchReducer, { - isDisplayConfirmDeleteModal: false, - isLoading: false, - isError: false, - isDeleted: false, - }); - const toasts = useToasts(); - const isCancelledRef = useRef(false); - const abortCtrlRef = useRef(new AbortController()); - - const dispatchDeleteCases = useCallback(async (cases: DeleteCase[]) => { - try { - isCancelledRef.current = false; - abortCtrlRef.current.abort(); - abortCtrlRef.current = new AbortController(); - dispatch({ type: 'FETCH_INIT' }); - - const caseIds = cases.map((theCase) => theCase.id); - if (cases.length > 0) { - await deleteCases(caseIds, abortCtrlRef.current.signal); - } - - if (!isCancelledRef.current) { - dispatch({ type: 'FETCH_SUCCESS', payload: true }); - toasts.addSuccess( - i18n.DELETED_CASES(cases.length, cases.length === 1 ? cases[0].title : '') - ); - } - } catch (error) { - if (!isCancelledRef.current) { - if (error.name !== 'AbortError') { - toasts.addError( - error.body && error.body.message ? new Error(error.body.message) : error, - { title: i18n.ERROR_DELETING } - ); - } - dispatch({ type: 'FETCH_FAILURE' }); - } - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); +export const useDeleteCases = () => { + const queryClient = useQueryClient(); + const { showErrorToast, showSuccessToast } = useCasesToast(); - const dispatchToggleDeleteModal = useCallback(() => { - dispatch({ type: 'DISPLAY_MODAL', payload: !state.isDisplayConfirmDeleteModal }); - }, [state.isDisplayConfirmDeleteModal]); - - const dispatchResetIsDeleted = useCallback(() => { - dispatch({ type: 'RESET_IS_DELETED' }); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [state.isDisplayConfirmDeleteModal]); - - const handleOnDeleteConfirm = useCallback( - (cases: DeleteCase[]) => { - dispatchDeleteCases(cases); - dispatchToggleDeleteModal(); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [state.isDisplayConfirmDeleteModal] - ); - const handleToggleModal = useCallback(() => { - dispatchToggleDeleteModal(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [state.isDisplayConfirmDeleteModal]); - - useEffect( - () => () => { - isCancelledRef.current = true; - abortCtrlRef.current.abort(); + return useMutation( + ({ caseIds }: MutationArgs) => { + const abortCtrlRef = new AbortController(); + return deleteCases(caseIds, abortCtrlRef.signal); }, - [] + { + mutationKey: casesMutationsKeys.deleteCases, + onSuccess: (_, { successToasterTitle }) => { + queryClient.invalidateQueries(casesQueriesKeys.casesList()); + queryClient.invalidateQueries(casesQueriesKeys.tags()); + queryClient.invalidateQueries(casesQueriesKeys.userProfiles()); + + showSuccessToast(successToasterTitle); + }, + onError: (error: ServerError) => { + showErrorToast(error, { title: i18n.ERROR_DELETING }); + }, + } ); - - return { ...state, dispatchResetIsDeleted, handleOnDeleteConfirm, handleToggleModal }; }; + +export type UseDeleteCases = ReturnType; diff --git a/x-pack/plugins/cases/public/containers/use_get_action_license.tsx b/x-pack/plugins/cases/public/containers/use_get_action_license.tsx index 8e9aa28de440a..7f05012cbbe6a 100644 --- a/x-pack/plugins/cases/public/containers/use_get_action_license.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_action_license.tsx @@ -10,7 +10,7 @@ import { useToasts } from '../common/lib/kibana'; import { getActionLicense } from './api'; import * as i18n from './translations'; import { ConnectorTypes } from '../../common/api'; -import { CASE_LICENSE_CACHE_KEY } from './constants'; +import { casesQueriesKeys } from './constants'; import { ServerError } from '../types'; const MINIMUM_LICENSE_REQUIRED_CONNECTOR = ConnectorTypes.jira; @@ -18,7 +18,7 @@ const MINIMUM_LICENSE_REQUIRED_CONNECTOR = ConnectorTypes.jira; export const useGetActionLicense = () => { const toasts = useToasts(); return useQuery( - [CASE_LICENSE_CACHE_KEY], + casesQueriesKeys.license(), async () => { const abortCtrl = new AbortController(); const response = await getActionLicense(abortCtrl.signal); diff --git a/x-pack/plugins/cases/public/containers/use_get_case.tsx b/x-pack/plugins/cases/public/containers/use_get_case.tsx index ded91240239a1..bf588cc1e71d0 100644 --- a/x-pack/plugins/cases/public/containers/use_get_case.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_case.tsx @@ -11,12 +11,12 @@ import * as i18n from './translations'; import { useToasts } from '../common/lib/kibana'; import { resolveCase } from './api'; import { ServerError } from '../types'; -import { CASE_VIEW_CACHE_KEY } from './constants'; +import { casesQueriesKeys } from './constants'; export const useGetCase = (caseId: string) => { const toasts = useToasts(); return useQuery( - [CASE_VIEW_CACHE_KEY, caseId], + casesQueriesKeys.case(caseId), () => { const abortCtrlRef = new AbortController(); return resolveCase(caseId, true, abortCtrlRef.signal); diff --git a/x-pack/plugins/cases/public/containers/use_get_case_metrics.tsx b/x-pack/plugins/cases/public/containers/use_get_case_metrics.tsx index 1e294c4a5ba6e..32d63fcc3b42e 100644 --- a/x-pack/plugins/cases/public/containers/use_get_case_metrics.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_case_metrics.tsx @@ -11,13 +11,13 @@ import { useToasts } from '../common/lib/kibana'; import { getSingleCaseMetrics } from './api'; import { ServerError } from '../types'; import { ERROR_TITLE } from './translations'; -import { CASE_VIEW_CACHE_KEY, CASE_VIEW_METRICS_CACHE_KEY } from './constants'; +import { casesQueriesKeys } from './constants'; export const useGetCaseMetrics = (caseId: string, features: SingleCaseMetricsFeature[]) => { const toasts = useToasts(); const abortCtrlRef = new AbortController(); return useQuery( - [CASE_VIEW_CACHE_KEY, CASE_VIEW_METRICS_CACHE_KEY, caseId, features], + casesQueriesKeys.caseMetrics(caseId, features), async () => { const response: SingleCaseMetrics = await getSingleCaseMetrics( caseId, diff --git a/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx b/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx index fde45207b673e..c92d56b41ea76 100644 --- a/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx @@ -20,7 +20,7 @@ import { import { ServerError } from '../types'; import { useToasts } from '../common/lib/kibana'; import { ERROR_TITLE } from './translations'; -import { CASE_VIEW_ACTIONS_CACHE_KEY, CASE_VIEW_CACHE_KEY } from './constants'; +import { casesQueriesKeys } from './constants'; export interface CaseService extends CaseExternalService { firstPushIndex: number; @@ -238,7 +238,7 @@ export const useGetCaseUserActions = (caseId: string, caseConnectorId: string) = const toasts = useToasts(); const abortCtrlRef = new AbortController(); return useQuery( - [CASE_VIEW_CACHE_KEY, CASE_VIEW_ACTIONS_CACHE_KEY, caseId, caseConnectorId], + casesQueriesKeys.userActions(caseId, caseConnectorId), async () => { const response = await getCaseUserActions(caseId, abortCtrlRef.signal); const participants = !isEmpty(response) diff --git a/x-pack/plugins/cases/public/containers/use_get_cases.tsx b/x-pack/plugins/cases/public/containers/use_get_cases.tsx index 7b046cac3f13f..d630534957e53 100644 --- a/x-pack/plugins/cases/public/containers/use_get_cases.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_cases.tsx @@ -6,7 +6,7 @@ */ import { useQuery, UseQueryResult } from '@tanstack/react-query'; -import { CASE_LIST_CACHE_KEY, DEFAULT_TABLE_ACTIVE_PAGE, DEFAULT_TABLE_LIMIT } from './constants'; +import { casesQueriesKeys, DEFAULT_TABLE_ACTIVE_PAGE, DEFAULT_TABLE_LIMIT } from './constants'; import { Cases, FilterOptions, QueryParams, SortFieldCase, StatusAll, SeverityAll } from './types'; import { useToasts } from '../common/lib/kibana'; import * as i18n from './translations'; @@ -51,7 +51,7 @@ export const useGetCases = ( ): UseQueryResult => { const toasts = useToasts(); return useQuery( - [CASE_LIST_CACHE_KEY, 'cases', params], + casesQueriesKeys.cases(params), () => { const abortCtrl = new AbortController(); return getCases({ diff --git a/x-pack/plugins/cases/public/containers/use_get_cases_metrics.test.tsx b/x-pack/plugins/cases/public/containers/use_get_cases_metrics.test.tsx index a8747a2bd43a5..0b0cdc59a487e 100644 --- a/x-pack/plugins/cases/public/containers/use_get_cases_metrics.test.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_cases_metrics.test.tsx @@ -5,124 +5,56 @@ * 2.0. */ -import React from 'react'; -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react-hooks'; import * as api from '../api'; -import { TestProviders } from '../common/mock'; -import { useGetCasesMetrics, UseGetCasesMetrics } from './use_get_cases_metrics'; +import { AppMockRenderer, createAppMockRenderer } from '../common/mock'; +import { useGetCasesMetrics } from './use_get_cases_metrics'; import { SECURITY_SOLUTION_OWNER } from '../../common/constants'; +import { useToasts } from '../common/lib/kibana'; jest.mock('../api'); jest.mock('../common/lib/kibana'); describe('useGetCasesMetrics', () => { - beforeEach(() => { - jest.clearAllMocks(); - jest.restoreAllMocks(); - }); + const abortCtrl = new AbortController(); + const addSuccess = jest.fn(); + const addError = jest.fn(); - it('init', async () => { - const { result } = renderHook(() => useGetCasesMetrics(), { - wrapper: ({ children }) => {children}, - }); + (useToasts as jest.Mock).mockReturnValue({ addSuccess, addError }); - await act(async () => { - expect(result.current).toEqual({ - mttr: 0, - isLoading: true, - isError: false, - fetchCasesMetrics: result.current.fetchCasesMetrics, - }); - }); + let appMockRender: AppMockRenderer; + + beforeEach(() => { + appMockRender = createAppMockRenderer(); + jest.clearAllMocks(); }); - it('calls getCasesMetrics api', async () => { + it('calls the api when invoked with the correct parameters', async () => { const spy = jest.spyOn(api, 'getCasesMetrics'); - await act(async () => { - const { waitForNextUpdate } = renderHook( - () => useGetCasesMetrics(), - { - wrapper: ({ children }) => {children}, - } - ); - - await waitForNextUpdate(); - expect(spy).toBeCalledWith({ - http: expect.anything(), - signal: expect.anything(), - query: { - features: ['mttr'], - owner: [SECURITY_SOLUTION_OWNER], - }, - }); + const { waitForNextUpdate } = renderHook(() => useGetCasesMetrics(), { + wrapper: appMockRender.AppWrapper, }); - }); - it('fetch cases metrics', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook( - () => useGetCasesMetrics(), - { - wrapper: ({ children }) => {children}, - } - ); + await waitForNextUpdate(); - await waitForNextUpdate(); - expect(result.current).toEqual({ - mttr: 12, - isLoading: false, - isError: false, - fetchCasesMetrics: result.current.fetchCasesMetrics, - }); + expect(spy).toHaveBeenCalledWith({ + http: expect.anything(), + signal: abortCtrl.signal, + query: { owner: [SECURITY_SOLUTION_OWNER], features: ['mttr'] }, }); }); - it('fetches metrics when fetchCasesMetrics is invoked', async () => { - const spy = jest.spyOn(api, 'getCasesMetrics'); - await act(async () => { - const { result, waitForNextUpdate } = renderHook( - () => useGetCasesMetrics(), - { - wrapper: ({ children }) => {children}, - } - ); - - await waitForNextUpdate(); - expect(spy).toBeCalledWith({ - http: expect.anything(), - signal: expect.anything(), - query: { - features: ['mttr'], - owner: [SECURITY_SOLUTION_OWNER], - }, - }); - result.current.fetchCasesMetrics(); - await waitForNextUpdate(); - expect(spy).toHaveBeenCalledTimes(2); - }); - }); + it('shows a toast error when the api return an error', async () => { + jest + .spyOn(api, 'getCasesMetrics') + .mockRejectedValue(new Error('useGetCasesMetrics: Test error')); - it('unhappy path', async () => { - const spy = jest.spyOn(api, 'getCasesMetrics'); - spy.mockImplementation(() => { - throw new Error('Oh on. this is impossible'); + const { waitForNextUpdate } = renderHook(() => useGetCasesMetrics(), { + wrapper: appMockRender.AppWrapper, }); - await act(async () => { - const { result, waitForNextUpdate } = renderHook( - () => useGetCasesMetrics(), - { - wrapper: ({ children }) => {children}, - } - ); - await waitForNextUpdate(); + await waitForNextUpdate(); - expect(result.current).toEqual({ - mttr: 0, - isLoading: false, - isError: true, - fetchCasesMetrics: result.current.fetchCasesMetrics, - }); - }); + expect(addError).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/cases/public/containers/use_get_cases_metrics.tsx b/x-pack/plugins/cases/public/containers/use_get_cases_metrics.tsx index a5cb116acc559..b43266e55340d 100644 --- a/x-pack/plugins/cases/public/containers/use_get_cases_metrics.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_cases_metrics.tsx @@ -5,88 +5,37 @@ * 2.0. */ -import { useCallback, useEffect, useState, useRef } from 'react'; - +import { useQuery } from '@tanstack/react-query'; import { useCasesContext } from '../components/cases_context/use_cases_context'; import * as i18n from './translations'; -import { useHttp, useToasts } from '../common/lib/kibana'; +import { useHttp } from '../common/lib/kibana'; import { getCasesMetrics } from '../api'; import { CasesMetrics } from './types'; +import { useCasesToast } from '../common/use_cases_toast'; +import { ServerError } from '../types'; +import { casesQueriesKeys } from './constants'; -interface CasesMetricsState extends CasesMetrics { - isLoading: boolean; - isError: boolean; -} - -const initialData: CasesMetricsState = { - mttr: 0, - isLoading: true, - isError: false, -}; - -export interface UseGetCasesMetrics extends CasesMetricsState { - fetchCasesMetrics: () => void; -} - -export const useGetCasesMetrics = (): UseGetCasesMetrics => { +export const useGetCasesMetrics = () => { const http = useHttp(); const { owner } = useCasesContext(); - const [casesMetricsState, setCasesMetricsState] = useState(initialData); - const toasts = useToasts(); - const isCancelledRef = useRef(false); - const abortCtrlRef = useRef(new AbortController()); - - const fetchCasesMetrics = useCallback(async () => { - try { - isCancelledRef.current = false; - abortCtrlRef.current.abort(); - abortCtrlRef.current = new AbortController(); - setCasesMetricsState({ - ...initialData, - isLoading: true, - }); + const { showErrorToast } = useCasesToast(); - const response = await getCasesMetrics({ + return useQuery( + casesQueriesKeys.casesMetrics(), + () => { + const abortCtrlRef = new AbortController(); + return getCasesMetrics({ http, - signal: abortCtrlRef.current.signal, + signal: abortCtrlRef.signal, query: { owner, features: ['mttr'] }, }); - - if (!isCancelledRef.current) { - setCasesMetricsState({ - ...response, - isLoading: false, - isError: false, - }); - } - } catch (error) { - if (!isCancelledRef.current) { - if (error.name !== 'AbortError') { - toasts.addError( - error.body && error.body.message ? new Error(error.body.message) : error, - { title: i18n.ERROR_TITLE } - ); - } - setCasesMetricsState({ - mttr: 0, - isLoading: false, - isError: true, - }); - } + }, + { + onError: (error: ServerError) => { + showErrorToast(error, { title: i18n.ERROR_TITLE }); + }, } - }, [http, owner, toasts]); - - useEffect(() => { - fetchCasesMetrics(); - - return () => { - isCancelledRef.current = true; - abortCtrlRef.current.abort(); - }; - }, [fetchCasesMetrics]); - - return { - ...casesMetricsState, - fetchCasesMetrics, - }; + ); }; + +export type UseGetCasesMetrics = ReturnType; diff --git a/x-pack/plugins/cases/public/containers/use_get_cases_status.test.tsx b/x-pack/plugins/cases/public/containers/use_get_cases_status.test.tsx index 3978e944db949..4f2572093a285 100644 --- a/x-pack/plugins/cases/public/containers/use_get_cases_status.test.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_cases_status.test.tsx @@ -5,104 +5,56 @@ * 2.0. */ -import React from 'react'; -import { renderHook, act } from '@testing-library/react-hooks'; -import { useGetCasesStatus, UseGetCasesStatus } from './use_get_cases_status'; -import { casesStatus } from './mock'; +import { renderHook } from '@testing-library/react-hooks'; +import { useGetCasesStatus } from './use_get_cases_status'; import * as api from '../api'; -import { TestProviders } from '../common/mock'; +import { AppMockRenderer, createAppMockRenderer } from '../common/mock'; import { SECURITY_SOLUTION_OWNER } from '../../common/constants'; +import { useToasts } from '../common/lib/kibana'; jest.mock('../api'); jest.mock('../common/lib/kibana'); -describe('useGetCasesStatus', () => { +describe('useGetCasesMetrics', () => { const abortCtrl = new AbortController(); + const addSuccess = jest.fn(); + const addError = jest.fn(); + + (useToasts as jest.Mock).mockReturnValue({ addSuccess, addError }); + + let appMockRender: AppMockRenderer; + beforeEach(() => { + appMockRender = createAppMockRenderer(); jest.clearAllMocks(); - jest.restoreAllMocks(); }); - it('init', async () => { - const { result } = renderHook(() => useGetCasesStatus(), { - wrapper: ({ children }) => {children}, - }); - - await act(async () => { - expect(result.current).toEqual({ - countClosedCases: 0, - countOpenCases: 0, - countInProgressCases: 0, - isLoading: true, - isError: false, - fetchCasesStatus: result.current.fetchCasesStatus, - }); + it('calls the api when invoked with the correct parameters', async () => { + const spy = jest.spyOn(api, 'getCasesStatus'); + const { waitForNextUpdate } = renderHook(() => useGetCasesStatus(), { + wrapper: appMockRender.AppWrapper, }); - }); - it('calls getCasesStatus api', async () => { - const spyOnGetCasesStatus = jest.spyOn(api, 'getCasesStatus'); - await act(async () => { - const { waitForNextUpdate } = renderHook( - () => useGetCasesStatus(), - { - wrapper: ({ children }) => {children}, - } - ); + await waitForNextUpdate(); - await waitForNextUpdate(); - expect(spyOnGetCasesStatus).toBeCalledWith({ - http: expect.anything(), - signal: abortCtrl.signal, - query: { owner: [SECURITY_SOLUTION_OWNER] }, - }); + expect(spy).toHaveBeenCalledWith({ + http: expect.anything(), + signal: abortCtrl.signal, + query: { owner: [SECURITY_SOLUTION_OWNER] }, }); }); - it('fetch statuses', async () => { - await act(async () => { - const { result, waitForNextUpdate } = renderHook( - () => useGetCasesStatus(), - { - wrapper: ({ children }) => {children}, - } - ); + it('shows a toast error when the api return an error', async () => { + jest + .spyOn(api, 'getCasesStatus') + .mockRejectedValue(new Error('useGetCasesMetrics: Test error')); - await waitForNextUpdate(); - expect(result.current).toEqual({ - countClosedCases: casesStatus.countClosedCases, - countOpenCases: casesStatus.countOpenCases, - countInProgressCases: casesStatus.countInProgressCases, - isLoading: false, - isError: false, - fetchCasesStatus: result.current.fetchCasesStatus, - }); + const { waitForNextUpdate } = renderHook(() => useGetCasesStatus(), { + wrapper: appMockRender.AppWrapper, }); - }); - it('unhappy path', async () => { - const spyOnGetCasesStatus = jest.spyOn(api, 'getCasesStatus'); - spyOnGetCasesStatus.mockImplementation(() => { - throw new Error('Something went wrong'); - }); + await waitForNextUpdate(); - await act(async () => { - const { result, waitForNextUpdate } = renderHook( - () => useGetCasesStatus(), - { - wrapper: ({ children }) => {children}, - } - ); - await waitForNextUpdate(); - - expect(result.current).toEqual({ - countClosedCases: 0, - countOpenCases: 0, - countInProgressCases: 0, - isLoading: false, - isError: true, - fetchCasesStatus: result.current.fetchCasesStatus, - }); - }); + expect(addError).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/cases/public/containers/use_get_cases_status.tsx b/x-pack/plugins/cases/public/containers/use_get_cases_status.tsx index 6530236a2fee6..c2ba6659edcbd 100644 --- a/x-pack/plugins/cases/public/containers/use_get_cases_status.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_cases_status.tsx @@ -5,94 +5,37 @@ * 2.0. */ -import { useCallback, useEffect, useState, useRef } from 'react'; - +import { useQuery } from '@tanstack/react-query'; import { useCasesContext } from '../components/cases_context/use_cases_context'; import * as i18n from './translations'; import { CasesStatus } from './types'; -import { useHttp, useToasts } from '../common/lib/kibana'; +import { useHttp } from '../common/lib/kibana'; import { getCasesStatus } from '../api'; +import { useCasesToast } from '../common/use_cases_toast'; +import { ServerError } from '../types'; +import { casesQueriesKeys } from './constants'; -interface CasesStatusState extends CasesStatus { - isLoading: boolean; - isError: boolean; -} - -const initialData: CasesStatusState = { - countClosedCases: 0, - countInProgressCases: 0, - countOpenCases: 0, - isLoading: true, - isError: false, -}; - -export interface UseGetCasesStatus extends CasesStatusState { - fetchCasesStatus: () => void; -} - -export const useGetCasesStatus = (): UseGetCasesStatus => { +export const useGetCasesStatus = () => { const http = useHttp(); const { owner } = useCasesContext(); - const [casesStatusState, setCasesStatusState] = useState(initialData); - const toasts = useToasts(); - const isCancelledRef = useRef(false); - const abortCtrlRef = useRef(new AbortController()); - - const fetchCasesStatus = useCallback(async () => { - try { - isCancelledRef.current = false; - abortCtrlRef.current.abort(); - abortCtrlRef.current = new AbortController(); - setCasesStatusState({ - ...initialData, - isLoading: true, - }); + const { showErrorToast } = useCasesToast(); - const response = await getCasesStatus({ + return useQuery( + casesQueriesKeys.casesStatuses(), + () => { + const abortCtrlRef = new AbortController(); + return getCasesStatus({ http, - signal: abortCtrlRef.current.signal, + signal: abortCtrlRef.signal, query: { owner }, }); - - if (!isCancelledRef.current) { - setCasesStatusState({ - ...response, - isLoading: false, - isError: false, - }); - } - } catch (error) { - if (!isCancelledRef.current) { - if (error.name !== 'AbortError') { - toasts.addError( - error.body && error.body.message ? new Error(error.body.message) : error, - { title: i18n.ERROR_TITLE } - ); - } - setCasesStatusState({ - countClosedCases: 0, - countInProgressCases: 0, - countOpenCases: 0, - isLoading: false, - isError: true, - }); - } + }, + { + onError: (error: ServerError) => { + showErrorToast(error, { title: i18n.ERROR_TITLE }); + }, } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - useEffect(() => { - fetchCasesStatus(); - - return () => { - isCancelledRef.current = true; - abortCtrlRef.current.abort(); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return { - ...casesStatusState, - fetchCasesStatus, - }; + ); }; + +export type UseGetCasesStatus = ReturnType; diff --git a/x-pack/plugins/cases/public/containers/use_get_tags.tsx b/x-pack/plugins/cases/public/containers/use_get_tags.tsx index 1696a9d1413a5..da56521536cbe 100644 --- a/x-pack/plugins/cases/public/containers/use_get_tags.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_tags.tsx @@ -10,15 +10,14 @@ import { useToasts } from '../common/lib/kibana'; import { useCasesContext } from '../components/cases_context/use_cases_context'; import { ServerError } from '../types'; import { getTags } from './api'; -import { CASE_TAGS_CACHE_KEY } from './constants'; +import { casesQueriesKeys } from './constants'; import * as i18n from './translations'; -export const useGetTags = (cacheKey?: string) => { +export const useGetTags = () => { const toasts = useToasts(); const { owner } = useCasesContext(); - const key = [...(cacheKey ? [cacheKey] : []), CASE_TAGS_CACHE_KEY]; return useQuery( - key, + casesQueriesKeys.tags(), () => { const abortCtrl = new AbortController(); return getTags(abortCtrl.signal, owner); diff --git a/x-pack/plugins/cases/public/containers/user_profiles/use_bulk_get_user_profiles.ts b/x-pack/plugins/cases/public/containers/user_profiles/use_bulk_get_user_profiles.ts index de180b5970f3b..b2928295dbb37 100644 --- a/x-pack/plugins/cases/public/containers/user_profiles/use_bulk_get_user_profiles.ts +++ b/x-pack/plugins/cases/public/containers/user_profiles/use_bulk_get_user_profiles.ts @@ -10,7 +10,7 @@ import { UserProfileWithAvatar } from '@kbn/user-profile-components'; import * as i18n from '../translations'; import { useKibana, useToasts } from '../../common/lib/kibana'; import { ServerError } from '../../types'; -import { USER_PROFILES_CACHE_KEY, USER_PROFILES_BULK_GET_CACHE_KEY } from '../constants'; +import { casesQueriesKeys } from '../constants'; import { bulkGetUserProfiles } from './api'; const profilesToMap = (profiles: UserProfileWithAvatar[]): Map => @@ -25,7 +25,7 @@ export const useBulkGetUserProfiles = ({ uids }: { uids: string[] }) => { const toasts = useToasts(); return useQuery>( - [USER_PROFILES_CACHE_KEY, USER_PROFILES_BULK_GET_CACHE_KEY, uids], + casesQueriesKeys.userProfilesList(uids), () => { return bulkGetUserProfiles({ security, uids }); }, diff --git a/x-pack/plugins/cases/public/containers/user_profiles/use_get_current_user_profile.ts b/x-pack/plugins/cases/public/containers/user_profiles/use_get_current_user_profile.ts index 37c29fa0b2d01..d6e3483672554 100644 --- a/x-pack/plugins/cases/public/containers/user_profiles/use_get_current_user_profile.ts +++ b/x-pack/plugins/cases/public/containers/user_profiles/use_get_current_user_profile.ts @@ -10,7 +10,7 @@ import { UserProfile } from '@kbn/security-plugin/common'; import * as i18n from '../translations'; import { useKibana, useToasts } from '../../common/lib/kibana'; import { ServerError } from '../../types'; -import { USER_PROFILES_CACHE_KEY, USER_PROFILES_GET_CURRENT_CACHE_KEY } from '../constants'; +import { casesQueriesKeys } from '../constants'; import { getCurrentUserProfile } from './api'; export const useGetCurrentUserProfile = () => { @@ -19,7 +19,7 @@ export const useGetCurrentUserProfile = () => { const toasts = useToasts(); return useQuery( - [USER_PROFILES_CACHE_KEY, USER_PROFILES_GET_CURRENT_CACHE_KEY], + casesQueriesKeys.currentUser(), () => { return getCurrentUserProfile({ security }); }, diff --git a/x-pack/plugins/cases/public/containers/user_profiles/use_suggest_user_profiles.ts b/x-pack/plugins/cases/public/containers/user_profiles/use_suggest_user_profiles.ts index 26e03d0163c8e..74c492850acd4 100644 --- a/x-pack/plugins/cases/public/containers/user_profiles/use_suggest_user_profiles.ts +++ b/x-pack/plugins/cases/public/containers/user_profiles/use_suggest_user_profiles.ts @@ -14,7 +14,7 @@ import { DEFAULT_USER_SIZE, SEARCH_DEBOUNCE_MS } from '../../../common/constants import * as i18n from '../translations'; import { useKibana, useToasts } from '../../common/lib/kibana'; import { ServerError } from '../../types'; -import { USER_PROFILES_CACHE_KEY, USER_PROFILES_SUGGEST_CACHE_KEY } from '../constants'; +import { casesQueriesKeys } from '../constants'; import { suggestUserProfiles, SuggestUserProfilesArgs } from './api'; type Props = Omit & { onDebounce?: () => void }; @@ -49,11 +49,7 @@ export const useSuggestUserProfiles = ({ const toasts = useToasts(); return useQuery( - [ - USER_PROFILES_CACHE_KEY, - USER_PROFILES_SUGGEST_CACHE_KEY, - { name: debouncedName, owners, size }, - ], + casesQueriesKeys.suggestUsers({ name: debouncedName, owners, size }), () => { const abortCtrlRef = new AbortController(); return suggestUserProfiles({ diff --git a/x-pack/plugins/enterprise_search/common/types/pipelines.ts b/x-pack/plugins/enterprise_search/common/types/pipelines.ts index 60fd87ca523b9..269f7149cc7b3 100644 --- a/x-pack/plugins/enterprise_search/common/types/pipelines.ts +++ b/x-pack/plugins/enterprise_search/common/types/pipelines.ts @@ -6,7 +6,16 @@ */ export interface InferencePipeline { - isDeployed: boolean; + modelState: TrainedModelState; + modelStateReason?: string; pipelineName: string; types: string[]; } + +export enum TrainedModelState { + NotDeployed = '', + Starting = 'starting', + Stopping = 'stopping', + Started = 'started', + Failed = 'failed', +} diff --git a/x-pack/plugins/enterprise_search/public/applications/analytics/index.tsx b/x-pack/plugins/enterprise_search/public/applications/analytics/index.tsx index eaed153a01b7f..f1228682fe888 100644 --- a/x-pack/plugins/enterprise_search/public/applications/analytics/index.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/analytics/index.tsx @@ -29,8 +29,7 @@ export const Analytics: React.FC = (props) => { const incompatibleVersions = isVersionMismatch(enterpriseSearchVersion, kibanaVersion); const { uiSettings } = useValues(KibanaLogic); - const analyticsSectionEnabled = - uiSettings?.get(enableBehavioralAnalyticsSection) ?? false; + const analyticsSectionEnabled = uiSettings?.get(enableBehavioralAnalyticsSection, false); if (!analyticsSectionEnabled) { return ; diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.test.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.test.tsx index 1c79cff0244e3..27dc055564bd8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.test.tsx @@ -11,14 +11,16 @@ import React from 'react'; import { shallow } from 'enzyme'; -import { EuiBadge, EuiHealth, EuiPanel, EuiTitle } from '@elastic/eui'; +import { EuiBadge, EuiPanel, EuiTitle } from '@elastic/eui'; + +import { InferencePipeline, TrainedModelState } from '../../../../../../common/types/pipelines'; import { InferencePipelineCard } from './inference_pipeline_card'; +import { TrainedModelHealth } from './ml_model_health'; -export const DEFAULT_VALUES = { - isDeployed: true, +export const DEFAULT_VALUES: InferencePipeline = { + modelState: TrainedModelState.Started, pipelineName: 'Sample Processor', - trainedModelName: 'example_trained_model', types: ['pytorch'], }; @@ -34,8 +36,6 @@ describe('InferencePipelineCard', () => { expect(wrapper.find(EuiPanel)).toHaveLength(1); expect(wrapper.find(EuiTitle)).toHaveLength(1); expect(wrapper.find(EuiBadge)).toHaveLength(1); - - const health = wrapper.find(EuiHealth); - expect(health.prop('children')).toEqual('Deployed'); + expect(wrapper.find(TrainedModelHealth)).toHaveLength(1); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.tsx index b73121f947d73..e8017ff15a198 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/inference_pipeline_card.tsx @@ -12,31 +12,30 @@ import { useActions, useValues } from 'kea'; import { EuiBadge, EuiButtonEmpty, + EuiButtonIcon, EuiConfirmModal, EuiFlexGroup, EuiFlexItem, - EuiHealth, EuiPanel, EuiPopover, EuiPopoverTitle, EuiText, EuiTitle, + EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { InferencePipeline } from '../../../../../../common/types/pipelines'; +import { InferencePipeline, TrainedModelState } from '../../../../../../common/types/pipelines'; import { CANCEL_BUTTON_LABEL, DELETE_BUTTON_LABEL } from '../../../../shared/constants'; import { HttpLogic } from '../../../../shared/http'; +import { ML_MANAGE_TRAINED_MODELS_PATH } from '../../../routes'; import { IndexNameLogic } from '../index_name_logic'; +import { TrainedModelHealth } from './ml_model_health'; import { PipelinesLogic } from './pipelines_logic'; -export const InferencePipelineCard: React.FC = ({ - pipelineName, - isDeployed, - types, -}) => { +export const InferencePipelineCard: React.FC = (pipeline) => { const { http } = useValues(HttpLogic); const { indexName } = useValues(IndexNameLogic); const [isPopOverOpen, setIsPopOverOpen] = useState(false); @@ -46,10 +45,7 @@ export const InferencePipelineCard: React.FC = ({ setShowConfirmDelete(true); setIsPopOverOpen(false); }; - - const deployedText = i18n.translate('xpack.enterpriseSearch.inferencePipelineCard.isDeployed', { - defaultMessage: 'Deployed', - }); + const { pipelineName, types } = pipeline; const actionButton = ( = ({ - - {isDeployed && ( - - {deployedText} + + + + + {pipeline.modelState === TrainedModelState.NotDeployed && ( + + + + )} {types.map((type) => ( diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ingest_pipelines_card.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ingest_pipelines_card.tsx index ca6140b7b9625..7bf1ef06e1e75 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ingest_pipelines_card.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ingest_pipelines_card.tsx @@ -26,6 +26,7 @@ import { KibanaLogic } from '../../../../shared/kibana'; import { LicensingLogic } from '../../../../shared/licensing'; import { CreateCustomPipelineApiLogic } from '../../../api/index/create_custom_pipeline_api_logic'; import { FetchCustomPipelineApiLogic } from '../../../api/index/fetch_custom_pipeline_api_logic'; +import { isApiIndex } from '../../../utils/indices'; import { CurlRequest } from '../components/curl_request/curl_request'; import { IndexViewLogic } from '../index_view_logic'; @@ -36,7 +37,7 @@ import { PipelinesLogic } from './pipelines_logic'; export const IngestPipelinesCard: React.FC = () => { const { indexName } = useValues(IndexViewLogic); - const { canSetPipeline, pipelineState, showModal } = useValues(PipelinesLogic); + const { canSetPipeline, index, pipelineState, showModal } = useValues(PipelinesLogic); const { closeModal, openModal, setPipelineState, savePipeline } = useActions(PipelinesLogic); const { makeRequest: fetchCustomPipeline } = useActions(FetchCustomPipelineApiLogic); const { makeRequest: createCustomPipeline } = useActions(CreateCustomPipelineApiLogic); @@ -97,22 +98,24 @@ export const IngestPipelinesCard: React.FC = () => { - - - - - - + + {isApiIndex(index) && ( + + + + + + )} {i18n.translate( diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/configure_pipeline.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/configure_pipeline.tsx index 0d8c5b7c71f1f..199d62f914f03 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/configure_pipeline.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/configure_pipeline.tsx @@ -182,7 +182,13 @@ export const ConfigurePipeline: React.FC = () => { formErrors.destinationField === undefined && i18n.translate( 'xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.configure.destinationField.helpText', - { defaultMessage: 'Your field name will be prefixed with "ml.inference."' } + { + defaultMessage: + 'Your field name will be prefixed with "ml.inference.", if not set it will be defaulted to "ml.inference.{pipelineName}"', + values: { + pipelineName, + }, + } ) } error={formErrors.destinationField} diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.test.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.test.tsx new file mode 100644 index 0000000000000..0eb88abb317e5 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { setMockValues } from '../../../../__mocks__/kea_logic'; + +import React from 'react'; + +import { shallow } from 'enzyme'; + +import { EuiHealth } from '@elastic/eui'; + +import { InferencePipeline, TrainedModelState } from '../../../../../../common/types/pipelines'; + +import { TrainedModelHealth } from './ml_model_health'; + +describe('TrainedModelHealth', () => { + beforeEach(() => { + jest.clearAllMocks(); + setMockValues({}); + }); + + const commonModelData: InferencePipeline = { + modelState: TrainedModelState.NotDeployed, + pipelineName: 'Sample Processor', + types: ['pytorch'], + }; + it('renders model started', () => { + const pipeline: InferencePipeline = { + ...commonModelData, + modelState: TrainedModelState.Started, + }; + const wrapper = shallow(); + const health = wrapper.find(EuiHealth); + expect(health.prop('children')).toEqual('Started'); + expect(health.prop('color')).toEqual('success'); + }); + it('renders model not deployed', () => { + const pipeline: InferencePipeline = { + ...commonModelData, + }; + const wrapper = shallow(); + const health = wrapper.find(EuiHealth); + expect(health.prop('children')).toEqual('Not deployed'); + expect(health.prop('color')).toEqual('danger'); + }); + it('renders model stopping', () => { + const pipeline: InferencePipeline = { + ...commonModelData, + modelState: TrainedModelState.Stopping, + }; + const wrapper = shallow(); + const health = wrapper.find(EuiHealth); + expect(health.prop('children')).toEqual('Stopping'); + expect(health.prop('color')).toEqual('warning'); + }); + it('renders model starting', () => { + const pipeline: InferencePipeline = { + ...commonModelData, + modelState: TrainedModelState.Starting, + }; + const wrapper = shallow(); + const health = wrapper.find(EuiHealth); + expect(health.prop('children')).toEqual('Starting'); + expect(health.prop('color')).toEqual('warning'); + }); + it('renders model failed', () => { + const pipeline: InferencePipeline = { + ...commonModelData, + modelState: TrainedModelState.Failed, + modelStateReason: 'Model start boom.', + }; + const wrapper = shallow(); + const health = wrapper.find(EuiHealth); + expect(health.prop('children')).toEqual('Deployment failed'); + expect(health.prop('color')).toEqual('danger'); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.tsx new file mode 100644 index 0000000000000..0d47c7018d4fe --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_model_health.tsx @@ -0,0 +1,144 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; + +import { EuiHealth, EuiToolTip } from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n-react'; + +import { InferencePipeline, TrainedModelState } from '../../../../../../common/types/pipelines'; + +const modelStartedText = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.started', + { + defaultMessage: 'Started', + } +); +const modelStartedTooltip = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.started.tooltip', + { + defaultMessage: 'This trained model is running and fully available', + } +); +const modelStartingText = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.starting', + { + defaultMessage: 'Starting', + } +); +const modelStartingTooltip = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.starting.tooltip', + { + defaultMessage: + 'This trained model is in the process of starting up and will be available shortly', + } +); +const modelStoppingText = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.stopping', + { + defaultMessage: 'Stopping', + } +); +const modelStoppingTooltip = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.stopping.tooltip', + { + defaultMessage: + 'This trained model is in the process of shutting down and is currently unavailable', + } +); +const modelDeploymentFailedText = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.deploymentFailed', + { + defaultMessage: 'Deployment failed', + } +); +const modelNotDeployedText = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.notDeployed', + { + defaultMessage: 'Not deployed', + } +); +const modelNotDeployedTooltip = i18n.translate( + 'xpack.enterpriseSearch.inferencePipelineCard.modelState.notDeployed.tooltip', + { + defaultMessage: + 'This trained model is not currently deployed. Visit the trained models page to make changes', + } +); + +export const TrainedModelHealth: React.FC = ({ + modelState, + modelStateReason, +}) => { + let modelHealth: { + healthColor: string; + healthText: React.ReactNode; + tooltipText: React.ReactNode; + }; + switch (modelState) { + case TrainedModelState.Started: + modelHealth = { + healthColor: 'success', + healthText: modelStartedText, + tooltipText: modelStartedTooltip, + }; + break; + case TrainedModelState.Stopping: + modelHealth = { + healthColor: 'warning', + healthText: modelStoppingText, + tooltipText: modelStoppingTooltip, + }; + break; + case TrainedModelState.Starting: + modelHealth = { + healthColor: 'warning', + healthText: modelStartingText, + tooltipText: modelStartingTooltip, + }; + break; + case TrainedModelState.Failed: + modelHealth = { + healthColor: 'danger', + healthText: modelDeploymentFailedText, + tooltipText: ( + + ), + }; + break; + case TrainedModelState.NotDeployed: + modelHealth = { + healthColor: 'danger', + healthText: modelNotDeployedText, + tooltipText: modelNotDeployedTooltip, + }; + break; + } + return ( + + {modelHealth.healthText} + + ); +}; diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/routes.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/routes.ts index 60260dcaa5377..a980402119062 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/routes.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/routes.ts @@ -21,3 +21,5 @@ export const SEARCH_INDEX_PATH = `${SEARCH_INDICES_PATH}/:indexName`; export const SEARCH_INDEX_TAB_PATH = `${SEARCH_INDEX_PATH}/:tabId`; export const SEARCH_INDEX_CRAWLER_DOMAIN_DETAIL_PATH = `${SEARCH_INDEX_PATH}/crawler/domains/:domainId`; export const SEARCH_INDEX_SELECT_CONNECTOR_PATH = `${SEARCH_INDEX_PATH}/select_connector`; + +export const ML_MANAGE_TRAINED_MODELS_PATH = '/app/ml/trained_models'; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.test.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.test.tsx index 743efc3274a44..67fb93ae643f6 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.test.tsx @@ -86,7 +86,10 @@ describe('useEnterpriseSearchContentNav', () => { name: 'Search', }, ]); - expect(mockKibanaValues.uiSettings.get).toHaveBeenCalledWith(enableBehavioralAnalyticsSection); + expect(mockKibanaValues.uiSettings.get).toHaveBeenCalledWith( + enableBehavioralAnalyticsSection, + false + ); }); it('excludes legacy products when the user has no access to them', () => { diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.tsx index f5a2d17d7dd94..967095d9674ba 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/layout/nav.tsx @@ -27,8 +27,7 @@ import { generateNavLink } from './nav_link_helpers'; export const useEnterpriseSearchNav = () => { const { productAccess, uiSettings } = useValues(KibanaLogic); - const analyticsSectionEnabled = - uiSettings?.get(enableBehavioralAnalyticsSection) ?? false; + const analyticsSectionEnabled = uiSettings?.get(enableBehavioralAnalyticsSection, false); const navItems: Array> = [ { diff --git a/x-pack/plugins/enterprise_search/public/plugin.ts b/x-pack/plugins/enterprise_search/public/plugin.ts index ac7581814242e..f193016e73f0d 100644 --- a/x-pack/plugins/enterprise_search/public/plugin.ts +++ b/x-pack/plugins/enterprise_search/public/plugin.ts @@ -72,7 +72,8 @@ export class EnterpriseSearchPlugin implements Plugin { const { cloud } = plugins; const bahavioralAnalyticsEnabled = core.uiSettings?.get( - enableBehavioralAnalyticsSection + enableBehavioralAnalyticsSection, + false ); core.application.register({ diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.test.ts b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.test.ts index 9a34bb42ec876..79d4600bb31e4 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.test.ts @@ -9,7 +9,7 @@ import { MlTrainedModelConfig } from '@elastic/elasticsearch/lib/api/typesWithBo import { ElasticsearchClient } from '@kbn/core/server'; import { BUILT_IN_MODEL_TAG } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; -import { InferencePipeline } from '../../../common/types/pipelines'; +import { InferencePipeline, TrainedModelState } from '../../../common/types/pipelines'; import { fetchAndAddTrainedModelData, @@ -169,35 +169,74 @@ const mockGetTrainedModelsData = { model_type: 'pytorch', tags: [], }, + { + inference_config: { text_classification: {} }, + model_id: 'trained-model-id-3', + model_type: 'pytorch', + tags: [], + }, + { + inference_config: { fill_mask: {} }, + model_id: 'trained-model-id-4', + model_type: 'pytorch', + tags: [], + }, ], }; const mockGetTrainedModelStats = { - count: 1, + count: 4, trained_model_stats: [ { model_id: 'trained-model-id-1', }, { deployment_stats: { + allocation_status: { + allocation_count: 1, + }, state: 'started', }, model_id: 'trained-model-id-2', }, + { + deployment_stats: { + allocation_status: { + allocation_count: 1, + }, + state: 'failed', + reason: 'something is wrong, boom', + }, + model_id: 'trained-model-id-3', + }, + { + deployment_stats: { + allocation_status: { + allocation_count: 1, + }, + state: 'starting', + }, + model_id: 'trained-model-id-4', + }, ], }; -const trainedModelDataObject = { +const trainedModelDataObject: Record = { 'trained-model-id-1': { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-1', types: ['lang_ident', 'ner'], }, 'trained-model-id-2': { - isDeployed: true, + modelState: TrainedModelState.Started, pipelineName: 'ml-inference-pipeline-2', types: ['pytorch', 'ner'], }, + 'ml-inference-pipeline-3': { + modelState: TrainedModelState.NotDeployed, + pipelineName: 'ml-inference-pipeline-3', + types: ['lang_ident', 'ner'], + }, }; describe('fetchMlInferencePipelineProcessorNames lib function', () => { @@ -254,15 +293,15 @@ describe('fetchPipelineProcessorInferenceData lib function', () => { it('should return the inference processor data for the pipelines', async () => { mockClient.ingest.getPipeline.mockImplementation(() => Promise.resolve(mockGetPipeline2)); - const expected = [ + const expected: InferencePipelineData[] = [ { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-1', trainedModelName: 'trained-model-id-1', types: [], }, { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-2', trainedModelName: 'trained-model-id-2', types: [], @@ -338,20 +377,20 @@ describe('getMlModelConfigsForModelIds lib function', () => { Promise.resolve(mockGetTrainedModelStats) ); - const input = { + const input: Record = { 'trained-model-id-1': { - isDeployed: true, + modelState: TrainedModelState.Started, pipelineName: '', trainedModelName: 'trained-model-id-1', types: ['pytorch', 'ner'], }, 'trained-model-id-2': { - isDeployed: true, + modelState: TrainedModelState.Started, pipelineName: '', trainedModelName: 'trained-model-id-2', types: ['pytorch', 'ner'], }, - } as Record; + }; const expected = { 'trained-model-id-2': input['trained-model-id-2'], @@ -392,32 +431,57 @@ describe('fetchAndAddTrainedModelData lib function', () => { const pipelines: InferencePipelineData[] = [ { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-1', trainedModelName: 'trained-model-id-1', types: [], }, { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-2', trainedModelName: 'trained-model-id-2', types: [], }, + { + modelState: TrainedModelState.NotDeployed, + pipelineName: 'ml-inference-pipeline-3', + trainedModelName: 'trained-model-id-3', + types: [], + }, + { + modelState: TrainedModelState.NotDeployed, + pipelineName: 'ml-inference-pipeline-4', + trainedModelName: 'trained-model-id-4', + types: [], + }, ]; const expected: InferencePipelineData[] = [ { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: 'ml-inference-pipeline-1', trainedModelName: 'trained-model-id-1', types: ['lang_ident', 'ner'], }, { - isDeployed: true, + modelState: TrainedModelState.Started, pipelineName: 'ml-inference-pipeline-2', trainedModelName: 'trained-model-id-2', types: ['pytorch', 'ner'], }, + { + modelState: TrainedModelState.Failed, + modelStateReason: 'something is wrong, boom', + pipelineName: 'ml-inference-pipeline-3', + trainedModelName: 'trained-model-id-3', + types: ['pytorch', 'text_classification'], + }, + { + modelState: TrainedModelState.Starting, + pipelineName: 'ml-inference-pipeline-4', + trainedModelName: 'trained-model-id-4', + types: ['pytorch', 'fill_mask'], + }, ]; const response = await fetchAndAddTrainedModelData( @@ -426,10 +490,10 @@ describe('fetchAndAddTrainedModelData lib function', () => { ); expect(mockClient.ml.getTrainedModels).toHaveBeenCalledWith({ - model_id: 'trained-model-id-1,trained-model-id-2', + model_id: 'trained-model-id-1,trained-model-id-2,trained-model-id-3,trained-model-id-4', }); expect(mockClient.ml.getTrainedModelsStats).toHaveBeenCalledWith({ - model_id: 'trained-model-id-1,trained-model-id-2', + model_id: 'trained-model-id-1,trained-model-id-2,trained-model-id-3,trained-model-id-4', }); expect(response).toEqual(expected); }); @@ -551,11 +615,7 @@ describe('fetchMlInferencePipelineProcessors lib function', () => { const expected: InferencePipeline[] = [ trainedModelDataObject['trained-model-id-1'], - { - isDeployed: false, - pipelineName: 'ml-inference-pipeline-3', - types: ['lang_ident', 'ner'], - }, + trainedModelDataObject['ml-inference-pipeline-3'], ]; const response = await fetchMlInferencePipelineProcessors( diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.ts b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.ts index 3b695d53ba9ab..95839a9b6ac20 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_ml_inference_pipeline_processors.ts @@ -9,7 +9,7 @@ import { MlTrainedModelConfig } from '@elastic/elasticsearch/lib/api/typesWithBo import { ElasticsearchClient } from '@kbn/core/server'; import { BUILT_IN_MODEL_TAG } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; -import { InferencePipeline } from '../../../common/types/pipelines'; +import { InferencePipeline, TrainedModelState } from '../../../common/types/pipelines'; import { getInferencePipelineNameFromIndexName } from '../../utils/ml_inference_pipeline_utils'; export type InferencePipelineData = InferencePipeline & { @@ -58,7 +58,7 @@ export const fetchPipelineProcessorInferenceData = async ( const trainedModelName = inferenceProcessor?.inference?.model_id; if (trainedModelName) pipelineProcessorData.push({ - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: pipelineProcessorName, trainedModelName, types: [], @@ -98,7 +98,7 @@ export const getMlModelConfigsForModelIds = async ( if (trainedModelNames.includes(trainedModelName)) { modelConfigs[trainedModelName] = { - isDeployed: false, + modelState: TrainedModelState.NotDeployed, pipelineName: '', trainedModelName, types: getMlModelTypesForModelConfig(trainedModelData), @@ -109,8 +109,27 @@ export const getMlModelConfigsForModelIds = async ( trainedModelsStats.trained_model_stats.forEach((trainedModelStats) => { const trainedModelName = trainedModelStats.model_id; if (modelConfigs.hasOwnProperty(trainedModelName)) { - const isDeployed = trainedModelStats.deployment_stats?.state === 'started'; - modelConfigs[trainedModelName].isDeployed = isDeployed; + let modelState: TrainedModelState; + switch (trainedModelStats.deployment_stats?.state) { + case 'started': + modelState = TrainedModelState.Started; + break; + case 'starting': + modelState = TrainedModelState.Starting; + break; + case 'stopping': + modelState = TrainedModelState.Stopping; + break; + // @ts-ignore: type is wrong, "failed" is a possible state + case 'failed': + modelState = TrainedModelState.Failed; + break; + default: + modelState = TrainedModelState.NotDeployed; + break; + } + modelConfigs[trainedModelName].modelState = modelState; + modelConfigs[trainedModelName].modelStateReason = trainedModelStats.deployment_stats?.reason; } }); @@ -131,11 +150,12 @@ export const fetchAndAddTrainedModelData = async ( if (!model) { return data; } - const { types, isDeployed } = model; + const { types, modelState, modelStateReason } = model; return { ...data, types, - isDeployed, + modelState, + modelStateReason, }; }); }; diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.test.ts b/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.test.ts index 6d49e2e53cfba..18a4b28650769 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.test.ts @@ -56,7 +56,7 @@ describe('generateApiKey lib function', () => { name: 'index_name-connector', role_descriptors: { ['index-name-connector-role']: { - cluster: ['monitor/main'], + cluster: ['monitor'], index: [ { names: ['index_name', `${CONNECTORS_INDEX}*`], @@ -91,7 +91,7 @@ describe('generateApiKey lib function', () => { name: 'index_name-connector', role_descriptors: { ['index-name-connector-role']: { - cluster: ['monitor/main'], + cluster: ['monitor'], index: [ { names: ['index_name', `${CONNECTORS_INDEX}*`], @@ -138,7 +138,7 @@ describe('generateApiKey lib function', () => { name: 'index_name-connector', role_descriptors: { ['index-name-connector-role']: { - cluster: ['monitor/main'], + cluster: ['monitor'], index: [ { names: ['index_name', `${CONNECTORS_INDEX}*`], diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.ts b/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.ts index f76fcf41fa245..74559dbe84995 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/generate_api_key.ts @@ -16,7 +16,7 @@ export const generateApiKey = async (client: IScopedClusterClient, indexName: st name: `${indexName}-connector`, role_descriptors: { [`${toAlphanumeric(indexName)}-connector-role`]: { - cluster: ['monitor/main'], + cluster: ['monitor'], index: [ { names: [indexName, `${CONNECTORS_INDEX}*`], diff --git a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/connectors.ts b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/connectors.ts index c0dcc2dbdb0a9..0aaf30ef126d4 100644 --- a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/connectors.ts +++ b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/connectors.ts @@ -114,7 +114,7 @@ export function registerConnectorRoutes({ router, log }: RouteDependencies) { connectorId: schema.string(), }), body: schema.object({ - nextSyncConfig: schema.string(), + nextSyncConfig: schema.maybe(schema.string()), }), }, }, diff --git a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts index fd4452ccb46af..db46da11f5f57 100644 --- a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts +++ b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts @@ -360,7 +360,7 @@ export function registerIndexRoutes({ pipelineName, modelId, sourceField, - destinationField || modelId, + destinationField, client.asCurrentUser ); } catch (error) { diff --git a/x-pack/plugins/enterprise_search/server/ui_settings.ts b/x-pack/plugins/enterprise_search/server/ui_settings.ts index 3334e625bc08f..99fb5906a3050 100644 --- a/x-pack/plugins/enterprise_search/server/ui_settings.ts +++ b/x-pack/plugins/enterprise_search/server/ui_settings.ts @@ -5,29 +5,9 @@ * 2.0. */ -import { schema } from '@kbn/config-schema'; import { UiSettingsParams } from '@kbn/core/types'; -import { i18n } from '@kbn/i18n'; - -import { - enterpriseSearchFeatureId, - enableBehavioralAnalyticsSection, -} from '../common/ui_settings_keys'; /** * uiSettings definitions for Enterprise Search */ -export const uiSettings: Record> = { - [enableBehavioralAnalyticsSection]: { - category: [enterpriseSearchFeatureId], - description: i18n.translate('xpack.enterpriseSearch.uiSettings.analytics.description', { - defaultMessage: 'Enable the new Analytics section in Enterprise Search.', - }), - name: i18n.translate('xpack.enterpriseSearch.uiSettings.analytics.name', { - defaultMessage: 'Enable Behavioral Analytics', - }), - requiresPageReload: true, - schema: schema.boolean(), - value: false, - }, -}; +export const uiSettings: Record> = {}; diff --git a/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.test.ts b/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.test.ts index c34bbae2f97f1..d3aa24560594d 100644 --- a/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.test.ts +++ b/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.test.ts @@ -16,6 +16,16 @@ import { getPrefixedInferencePipelineProcessorName, } from './ml_inference_pipeline_utils'; +const mockClient = { + ingest: { + getPipeline: jest.fn(), + putPipeline: jest.fn(), + }, + ml: { + getTrainedModels: jest.fn(), + }, +}; + describe('createMlInferencePipeline util function', () => { const pipelineName = 'my-pipeline'; const modelId = 'my-model-id'; @@ -23,16 +33,6 @@ describe('createMlInferencePipeline util function', () => { const destinationField = 'my-dest-field'; const inferencePipelineGeneratedName = getPrefixedInferencePipelineProcessorName(pipelineName); - const mockClient = { - ingest: { - getPipeline: jest.fn(), - putPipeline: jest.fn(), - }, - ml: { - getTrainedModels: jest.fn(), - }, - }; - mockClient.ml.getTrainedModels.mockImplementation(() => Promise.resolve({ trained_model_configs: [ @@ -86,6 +86,32 @@ describe('createMlInferencePipeline util function', () => { ); }); + it('should default the destination field to the pipeline name', async () => { + mockClient.ingest.getPipeline.mockImplementation(() => Promise.reject({ statusCode: 404 })); // Pipeline does not exist + mockClient.ingest.putPipeline.mockImplementation(() => Promise.resolve({ acknowledged: true })); + + await createMlInferencePipeline( + pipelineName, + modelId, + sourceField, + undefined, // Omitted destination field + mockClient as unknown as ElasticsearchClient + ); + + // Verify the object passed to pipeline creation contains the default target field name + expect(mockClient.ingest.putPipeline).toHaveBeenCalledWith( + expect.objectContaining({ + processors: expect.arrayContaining([ + expect.objectContaining({ + inference: expect.objectContaining({ + target_field: `ml.inference.${pipelineName}`, + }), + }), + ]), + }) + ); + }); + it('should throw an error without creating the pipeline if it already exists', () => { mockClient.ingest.getPipeline.mockImplementation(() => Promise.resolve({ @@ -111,13 +137,6 @@ describe('addSubPipelineToIndexSpecificMlPipeline util function', () => { const parentPipelineId = getInferencePipelineNameFromIndexName(indexName); const pipelineName = 'ml-inference-my-pipeline'; - const mockClient = { - ingest: { - getPipeline: jest.fn(), - putPipeline: jest.fn(), - }, - }; - beforeEach(() => { jest.clearAllMocks(); }); diff --git a/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts b/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts index ebe69f98118d1..dfcd8d4884972 100644 --- a/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts +++ b/x-pack/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts @@ -15,6 +15,7 @@ import { formatMlPipelineBody } from '../lib/pipelines/create_pipeline_definitio import { getInferencePipelineNameFromIndexName, getPrefixedInferencePipelineProcessorName, + formatPipelineName, } from './ml_inference_pipeline_utils'; /** @@ -41,14 +42,14 @@ export const createAndReferenceMlInferencePipeline = async ( pipelineName: string, modelId: string, sourceField: string, - destinationField: string, + destinationField: string | null | undefined, esClient: ElasticsearchClient ): Promise => { const createPipelineResult = await createMlInferencePipeline( pipelineName, modelId, sourceField, - destinationField || modelId, + destinationField, esClient ); @@ -76,7 +77,7 @@ export const createMlInferencePipeline = async ( pipelineName: string, modelId: string, sourceField: string, - destinationField: string, + destinationField: string | null | undefined, esClient: ElasticsearchClient ): Promise => { const inferencePipelineGeneratedName = getPrefixedInferencePipelineProcessorName(pipelineName); @@ -99,7 +100,7 @@ export const createMlInferencePipeline = async ( inferencePipelineGeneratedName, modelId, sourceField, - destinationField, + destinationField || formatPipelineName(pipelineName), esClient ); diff --git a/x-pack/plugins/enterprise_search/server/utils/ml_inference_pipeline_utils.ts b/x-pack/plugins/enterprise_search/server/utils/ml_inference_pipeline_utils.ts index e059f5b9090c0..6547034f25403 100644 --- a/x-pack/plugins/enterprise_search/server/utils/ml_inference_pipeline_utils.ts +++ b/x-pack/plugins/enterprise_search/server/utils/ml_inference_pipeline_utils.ts @@ -13,7 +13,7 @@ export const getPrefixedInferencePipelineProcessorName = (pipelineName: string) ? formatPipelineName(pipelineName) : `ml-inference-${formatPipelineName(pipelineName)}`; -const formatPipelineName = (rawName: string) => +export const formatPipelineName = (rawName: string) => rawName .trim() .replace(/\s+/g, '_') // Convert whitespaces to underscores diff --git a/x-pack/plugins/event_log/README.md b/x-pack/plugins/event_log/README.md index c1d5869e7ed48..05b05946b652d 100644 --- a/x-pack/plugins/event_log/README.md +++ b/x-pack/plugins/event_log/README.md @@ -159,6 +159,7 @@ Below is a document in the expected structure, with descriptions of the fields: es_search_duration_ms: "total time spent performing ES searches as measured by Elasticsearch", total_search_duration_ms: "total time spent performing ES searches as measured by Kibana; includes network latency and time spent serializing/deserializing request/response", total_indexing_duration_ms: "total time spent indexing documents during current rule execution cycle", + total_enrichment_duration_ms: "total time spent enriching documents during current rule execution cycle", execution_gap_duration_s: "duration in seconds of execution gap" } } diff --git a/x-pack/plugins/event_log/generated/mappings.json b/x-pack/plugins/event_log/generated/mappings.json index db6719fed996a..4756b4f2e5534 100644 --- a/x-pack/plugins/event_log/generated/mappings.json +++ b/x-pack/plugins/event_log/generated/mappings.json @@ -347,6 +347,9 @@ }, "total_run_duration_ms": { "type": "long" + }, + "total_enrichment_duration_ms": { + "type": "long" } } } diff --git a/x-pack/plugins/event_log/generated/schemas.ts b/x-pack/plugins/event_log/generated/schemas.ts index b5557f64e9ac7..523ad683eabf2 100644 --- a/x-pack/plugins/event_log/generated/schemas.ts +++ b/x-pack/plugins/event_log/generated/schemas.ts @@ -150,6 +150,7 @@ export const EventSchema = schema.maybe( claim_to_start_duration_ms: ecsStringOrNumber(), prepare_rule_duration_ms: ecsStringOrNumber(), total_run_duration_ms: ecsStringOrNumber(), + total_enrichment_duration_ms: ecsStringOrNumber(), }) ), }) diff --git a/x-pack/plugins/event_log/scripts/mappings.js b/x-pack/plugins/event_log/scripts/mappings.js index 98050b6557210..65c9220fb5355 100644 --- a/x-pack/plugins/event_log/scripts/mappings.js +++ b/x-pack/plugins/event_log/scripts/mappings.js @@ -130,6 +130,9 @@ exports.EcsCustomPropertyMappings = { total_run_duration_ms: { type: 'long', }, + total_enrichment_duration_ms: { + type: 'long', + }, }, }, }, diff --git a/x-pack/plugins/files/public/components/upload_file/upload_file.tsx b/x-pack/plugins/files/public/components/upload_file/upload_file.tsx index c3b958c12d22d..8e0d8ed59392b 100644 --- a/x-pack/plugins/files/public/components/upload_file/upload_file.tsx +++ b/x-pack/plugins/files/public/components/upload_file/upload_file.tsx @@ -117,6 +117,8 @@ export const UploadFile = ({ return () => subs.forEach((sub) => sub.unsubscribe()); }, [uploadState, onDone, onError]); + useEffect(() => uploadState.dispose, [uploadState]); + return ( { it('calls file client with expected arguments', async () => { testScheduler.run(({ expectObservable, cold, flush }) => { - const file1 = { name: 'test.png', size: 1 } as File; + const file1 = { name: 'test.png', size: 1, type: 'image/png' } as File; uploadState.setFiles([file1]); @@ -113,7 +113,7 @@ describe('UploadState', () => { filesClient.delete.mockReturnValue(of(undefined) as any); const file1 = { name: 'test' } as File; - const file2 = { name: 'test 2.png' } as File; + const file2 = { name: 'test 2.png', type: 'image/png' } as File; uploadState.setFiles([file1, file2]); diff --git a/x-pack/plugins/files/public/components/upload_file/upload_state.ts b/x-pack/plugins/files/public/components/upload_file/upload_state.ts index e8bbc206e6054..d5fbc04512fdc 100644 --- a/x-pack/plugins/files/public/components/upload_file/upload_state.ts +++ b/x-pack/plugins/files/public/components/upload_file/upload_state.ts @@ -25,6 +25,7 @@ import { type Observable, combineLatest, distinctUntilChanged, + Subscription, } from 'rxjs'; import type { FileKind, FileJSON } from '../../../common/types'; import type { FilesClient } from '../../types'; @@ -62,38 +63,41 @@ export class UploadState { public readonly uploading$ = new BehaviorSubject(false); public readonly done$ = new Subject(); + private subscriptions: Subscription[]; + constructor( private readonly fileKind: FileKind, private readonly client: FilesClient, private readonly opts: UploadOptions = { allowRepeatedUploads: false } ) { const latestFiles$ = this.files$$.pipe(switchMap((files$) => combineLatest(files$))); - - latestFiles$ - .pipe( - map((files) => files.some((file) => file.status === 'uploading')), - distinctUntilChanged() - ) - .subscribe(this.uploading$); - - latestFiles$ - .pipe( - map((files) => { - const errorFile = files.find((file) => Boolean(file.error)); - return errorFile ? errorFile.error : undefined; - }), - filter(Boolean) - ) - .subscribe(this.error$); - - latestFiles$ - .pipe( - filter( - (files) => Boolean(files.length) && files.every((file) => file.status === 'uploaded') - ), - map((files) => files.map((file) => ({ id: file.id!, kind: this.fileKind.id }))) - ) - .subscribe(this.done$); + this.subscriptions = [ + latestFiles$ + .pipe( + map((files) => files.some((file) => file.status === 'uploading')), + distinctUntilChanged() + ) + .subscribe(this.uploading$), + + latestFiles$ + .pipe( + map((files) => { + const errorFile = files.find((file) => Boolean(file.error)); + return errorFile ? errorFile.error : undefined; + }), + filter(Boolean) + ) + .subscribe(this.error$), + + latestFiles$ + .pipe( + filter( + (files) => Boolean(files.length) && files.every((file) => file.status === 'uploaded') + ), + map((files) => files.map((file) => ({ id: file.id!, kind: this.fileKind.id }))) + ) + .subscribe(this.done$), + ]; } public isUploading(): boolean { @@ -165,7 +169,8 @@ export class UploadState { file$.setState({ status: 'uploading', error: undefined }); - const { name, mime } = parseFileName(file.name); + const { name } = parseFileName(file.name); + const mime = file.type || undefined; return from( this.client.create({ @@ -226,6 +231,10 @@ export class UploadState { return upload$; }; + + public dispose = (): void => { + for (const sub of this.subscriptions) sub.unsubscribe(); + }; } export const createUploadState = ({ diff --git a/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.test.ts b/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.test.ts index f03b019f6aca3..bfe27b50a9f43 100644 --- a/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.test.ts +++ b/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.test.ts @@ -11,28 +11,24 @@ describe('parseFileName', () => { test('file.png', () => { expect(parseFileName('file.png')).toEqual({ name: 'file', - mime: 'image/png', }); }); test(' Something_* really -=- strange.abc.wav', () => { expect(parseFileName(' Something_* really -=- strange.abc.wav')).toEqual({ name: 'Something__ really ___ strange_abc', - mime: 'audio/wave', }); }); test('!@#$%^&*()', () => { expect(parseFileName('!@#$%^&*()')).toEqual({ name: '__________', - mime: undefined, }); }); test('reallylong.repeat(100).dmg', () => { expect(parseFileName('reallylong'.repeat(100) + '.dmg')).toEqual({ name: 'reallylong'.repeat(100).slice(0, 256), - mime: 'application/x-apple-diskimage', }); }); }); diff --git a/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.ts b/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.ts index 22e6833851825..485b3013631dd 100644 --- a/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.ts +++ b/x-pack/plugins/files/public/components/upload_file/util/parse_file_name.ts @@ -5,11 +5,8 @@ * 2.0. */ -import mime from 'mime-types'; - interface Result { name: string; - mime?: string; } export function parseFileName(fileName: string): Result { @@ -19,6 +16,5 @@ export function parseFileName(fileName: string): Result { .trim() .slice(0, 256) .replace(/[^a-z0-9\s]/gi, '_'), // replace invalid chars - mime: mime.lookup(fileName) || undefined, }; } diff --git a/x-pack/plugins/files/public/types.ts b/x-pack/plugins/files/public/types.ts index ac5ec40c2c252..25aab6e787b6b 100644 --- a/x-pack/plugins/files/public/types.ts +++ b/x-pack/plugins/files/public/types.ts @@ -117,8 +117,10 @@ export interface FilesClient extends GlobalEndpoints { /** * Get a string for downloading a file that can be passed to a button element's * href for download. + * + * @param args - get download URL args */ - getDownloadHref: (file: FileJSON) => string; + getDownloadHref: (args: Pick) => string; /** * Share a file by creating a new file share instance. * diff --git a/x-pack/plugins/fleet/.storybook/context/index.tsx b/x-pack/plugins/fleet/.storybook/context/index.tsx index 7ef04979969e0..1d5416cf0483d 100644 --- a/x-pack/plugins/fleet/.storybook/context/index.tsx +++ b/x-pack/plugins/fleet/.storybook/context/index.tsx @@ -72,7 +72,7 @@ export const StorybookContext: React.FC<{ storyContext?: Parameters }, customIntegrations: { ContextProvider: getStorybookContextProvider(), - languageClientsUiComponents: new Map(), + languageClientsUiComponents: {}, }, docLinks: getDocLinks(), http: getHttp(), diff --git a/x-pack/plugins/fleet/common/authz.test.ts b/x-pack/plugins/fleet/common/authz.test.ts new file mode 100644 index 0000000000000..cadb90651b01c --- /dev/null +++ b/x-pack/plugins/fleet/common/authz.test.ts @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DEFAULT_APP_CATEGORIES } from '@kbn/core-application-common'; + +import { + calculatePackagePrivilegesFromCapabilities, + calculatePackagePrivilegesFromKibanaPrivileges, +} from './authz'; +import { ENDPOINT_PRIVILEGES } from './constants'; + +const SECURITY_SOLUTION_ID = DEFAULT_APP_CATEGORIES.security.id; + +function generateActions( + privileges: typeof ENDPOINT_PRIVILEGES, + overrides: Record = {} +) { + return privileges.reduce((acc, privilege) => { + const executePackageAction = overrides[privilege] || false; + + return { + ...acc, + [privilege]: { + executePackageAction, + }, + }; + }, {}); +} + +describe('fleet authz', () => { + describe('calculatePackagePrivilegesFromCapabilities', () => { + it('calculates privileges correctly', () => { + const endpointCapabilities = { + writeEndpointList: true, + writeTrustedApplications: true, + writePolicyManagement: false, + readPolicyManagement: true, + writeHostIsolationExceptions: true, + writeHostIsolation: false, + }; + const expected = { + endpoint: { + actions: generateActions(ENDPOINT_PRIVILEGES, endpointCapabilities), + }, + }; + const actual = calculatePackagePrivilegesFromCapabilities({ + navLinks: {}, + management: {}, + catalogue: {}, + siem: endpointCapabilities, + }); + + expect(actual).toEqual(expected); + }); + }); + + describe('calculatePackagePrivilegesFromKibanaPrivileges', () => { + it('calculates privileges correctly', () => { + const endpointPrivileges = [ + { privilege: `${SECURITY_SOLUTION_ID}-writeEndpointList`, authorized: true }, + { privilege: `${SECURITY_SOLUTION_ID}-writeTrustedApplications`, authorized: true }, + { privilege: `${SECURITY_SOLUTION_ID}-writePolicyManagement`, authorized: false }, + { privilege: `${SECURITY_SOLUTION_ID}-readPolicyManagement`, authorized: true }, + { privilege: `${SECURITY_SOLUTION_ID}-writeHostIsolationExceptions`, authorized: true }, + { privilege: `${SECURITY_SOLUTION_ID}-writeHostIsolation`, authorized: false }, + { privilege: `${SECURITY_SOLUTION_ID}-ignoreMe`, authorized: true }, + ]; + const expected = { + endpoint: { + actions: generateActions(ENDPOINT_PRIVILEGES, { + writeEndpointList: true, + writeTrustedApplications: true, + writePolicyManagement: false, + readPolicyManagement: true, + writeHostIsolationExceptions: true, + writeHostIsolation: false, + }), + }, + }; + const actual = calculatePackagePrivilegesFromKibanaPrivileges(endpointPrivileges); + expect(actual).toEqual(expected); + }); + }); +}); diff --git a/x-pack/plugins/fleet/common/authz.ts b/x-pack/plugins/fleet/common/authz.ts index c8ae7b76d0403..72812576e13b3 100644 --- a/x-pack/plugins/fleet/common/authz.ts +++ b/x-pack/plugins/fleet/common/authz.ts @@ -5,6 +5,11 @@ * 2.0. */ +import { DEFAULT_APP_CATEGORIES } from '@kbn/core-application-common'; +import type { Capabilities } from '@kbn/core-capabilities-common'; + +import { ENDPOINT_PRIVILEGES } from './constants'; + export interface FleetAuthz { fleet: { all: boolean; @@ -27,6 +32,16 @@ export interface FleetAuthz { readIntegrationPolicies: boolean; writeIntegrationPolicies: boolean; }; + + packagePrivileges?: { + [packageName: string]: { + actions: { + [key: string]: { + executePackageAction: boolean; + }; + }; + }; + }; } interface CalculateParams { @@ -72,3 +87,70 @@ export const calculateAuthz = ({ writeIntegrationPolicies: fleet.all && integrations.all, }, }); + +export function calculatePackagePrivilegesFromCapabilities( + capabilities: Capabilities | undefined +): FleetAuthz['packagePrivileges'] { + if (!capabilities) { + return {}; + } + + const endpointActions = ENDPOINT_PRIVILEGES.reduce((acc, privilege) => { + return { + ...acc, + [privilege]: { + executePackageAction: capabilities.siem[privilege] || false, + }, + }; + }, {}); + + return { + endpoint: { + actions: endpointActions, + }, + }; +} + +function getAuthorizationFromPrivileges( + kibanaPrivileges: Array<{ + resource?: string; + privilege: string; + authorized: boolean; + }>, + searchPrivilege: string +): boolean { + const privilege = kibanaPrivileges.find((p) => + p.privilege.endsWith(`${DEFAULT_APP_CATEGORIES.security.id}-${searchPrivilege}`) + ); + return privilege?.authorized || false; +} + +export function calculatePackagePrivilegesFromKibanaPrivileges( + kibanaPrivileges: + | Array<{ + resource?: string; + privilege: string; + authorized: boolean; + }> + | undefined +): FleetAuthz['packagePrivileges'] { + if (!kibanaPrivileges || !kibanaPrivileges.length) { + return {}; + } + + const endpointActions = ENDPOINT_PRIVILEGES.reduce((acc, privilege: string) => { + const kibanaPrivilege = getAuthorizationFromPrivileges(kibanaPrivileges, privilege); + return { + ...acc, + [privilege]: { + executePackageAction: kibanaPrivilege, + }, + }; + }, {}); + + return { + endpoint: { + actions: endpointActions, + }, + }; +} diff --git a/x-pack/plugins/fleet/common/constants/authz.ts b/x-pack/plugins/fleet/common/constants/authz.ts new file mode 100644 index 0000000000000..d7a0ca4ade2eb --- /dev/null +++ b/x-pack/plugins/fleet/common/constants/authz.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const ENDPOINT_PRIVILEGES = [ + 'writeEndpointList', + 'readEndpointList', + 'writeTrustedApplications', + 'readTrustedApplications', + 'writeHostIsolationExceptions', + 'readHostIsolationExceptions', + 'writeBlocklist', + 'readBlocklist', + 'writeEventFilters', + 'readEventFilters', + 'writePolicyManagement', + 'readPolicyManagement', + 'writeActionsLogManagement', + 'readActionsLogManagement', + 'writeHostIsolation', + 'writeProcessOperations', + 'writeFileOperations', +] as const; diff --git a/x-pack/plugins/fleet/common/constants/index.ts b/x-pack/plugins/fleet/common/constants/index.ts index 615a48f7493cf..955abb6b7456c 100644 --- a/x-pack/plugins/fleet/common/constants/index.ts +++ b/x-pack/plugins/fleet/common/constants/index.ts @@ -16,6 +16,7 @@ export * from './enrollment_api_key'; export * from './settings'; export * from './preconfiguration'; export * from './download_source'; +export * from './authz'; // TODO: This is the default `index.max_result_window` ES setting, which dictates // the maximum amount of results allowed to be returned from a search. It's possible diff --git a/x-pack/plugins/fleet/common/index.ts b/x-pack/plugins/fleet/common/index.ts index d9e3fd8b9ceb6..e8995b4bf6b74 100644 --- a/x-pack/plugins/fleet/common/index.ts +++ b/x-pack/plugins/fleet/common/index.ts @@ -48,6 +48,8 @@ export { // Should probably be removed SO_SEARCH_LIMIT, // Statuses + // Authz + ENDPOINT_PRIVILEGES, } from './constants'; export { // Route services diff --git a/x-pack/plugins/fleet/common/mocks.ts b/x-pack/plugins/fleet/common/mocks.ts index bc8880ed385af..d5aca8398abd8 100644 --- a/x-pack/plugins/fleet/common/mocks.ts +++ b/x-pack/plugins/fleet/common/mocks.ts @@ -7,6 +7,7 @@ import type { DeletePackagePoliciesResponse, NewPackagePolicy, PackagePolicy } from './types'; import type { FleetAuthz } from './authz'; +import { ENDPOINT_PRIVILEGES } from './constants'; export const createNewPackagePolicyMock = (): NewPackagePolicy => { return { @@ -61,6 +62,15 @@ export const deletePackagePolicyMock = (): DeletePackagePoliciesResponse => { * Creates mock `authz` object */ export const createFleetAuthzMock = (): FleetAuthz => { + const endpointActions = ENDPOINT_PRIVILEGES.reduce((acc, privilege) => { + return { + ...acc, + [privilege]: { + executePackageAction: true, + }, + }; + }, {}); + return { fleet: { all: true, @@ -80,5 +90,10 @@ export const createFleetAuthzMock = (): FleetAuthz => { readIntegrationPolicies: true, writeIntegrationPolicies: true, }, + packagePrivileges: { + endpoint: { + actions: endpointActions, + }, + }, }; }; diff --git a/x-pack/plugins/fleet/common/openapi/bundled.json b/x-pack/plugins/fleet/common/openapi/bundled.json index 88f091ad98310..71b4ec04d4e98 100644 --- a/x-pack/plugins/fleet/common/openapi/bundled.json +++ b/x-pack/plugins/fleet/common/openapi/bundled.json @@ -1254,23 +1254,8 @@ "type": "object", "properties": { "actionId": { - "type": "string", - "description": "action id when running in async mode (>10k agents)" + "type": "string" } - }, - "additionalProperties": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "error": { - "type": "string" - } - }, - "required": [ - "success" - ] } } } @@ -1849,23 +1834,8 @@ "type": "object", "properties": { "actionId": { - "type": "string", - "description": "action id when running in async mode (>10k agents)" + "type": "string" } - }, - "additionalProperties": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "error": { - "type": "string" - } - }, - "required": [ - "success" - ] } } } @@ -1931,23 +1901,8 @@ "type": "object", "properties": { "actionId": { - "type": "string", - "description": "action id when running in async mode (>10k agents)" + "type": "string" } - }, - "additionalProperties": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "error": { - "type": "string" - } - }, - "required": [ - "success" - ] } } } @@ -2020,23 +1975,8 @@ "type": "object", "properties": { "actionId": { - "type": "string", - "description": "action id when running in async mode (>10k agents)" + "type": "string" } - }, - "additionalProperties": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "error": { - "type": "string" - } - }, - "required": [ - "success" - ] } } } diff --git a/x-pack/plugins/fleet/common/openapi/bundled.yaml b/x-pack/plugins/fleet/common/openapi/bundled.yaml index 86928fca0b2f4..92347809b0616 100644 --- a/x-pack/plugins/fleet/common/openapi/bundled.yaml +++ b/x-pack/plugins/fleet/common/openapi/bundled.yaml @@ -774,16 +774,6 @@ paths: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success '400': description: BAD REQUEST content: @@ -1145,16 +1135,6 @@ paths: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-reassign-agents parameters: - $ref: '#/components/parameters/kbn_xsrf' @@ -1195,16 +1175,6 @@ paths: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-unenroll-agents parameters: - $ref: '#/components/parameters/kbn_xsrf' @@ -1250,16 +1220,6 @@ paths: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-update-agent-tags parameters: - $ref: '#/components/parameters/kbn_xsrf' diff --git a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_reassign.yaml b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_reassign.yaml index cd333e94e4750..17c4365f01e32 100644 --- a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_reassign.yaml +++ b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_reassign.yaml @@ -11,16 +11,6 @@ post: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-reassign-agents parameters: - $ref: ../components/headers/kbn_xsrf.yaml diff --git a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_unenroll.yaml b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_unenroll.yaml index ff04eda0be8a8..f5e244f86f74b 100644 --- a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_unenroll.yaml +++ b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_unenroll.yaml @@ -11,16 +11,6 @@ post: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-unenroll-agents parameters: - $ref: ../components/headers/kbn_xsrf.yaml diff --git a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_update_tags.yaml b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_update_tags.yaml index 80643ebd3625e..2eb129e802179 100644 --- a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_update_tags.yaml +++ b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_update_tags.yaml @@ -11,16 +11,6 @@ post: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success operationId: bulk-update-agent-tags parameters: - $ref: ../components/headers/kbn_xsrf.yaml diff --git a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_upgrade.yaml b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_upgrade.yaml index 1d9136353f01b..9a74054f492a7 100644 --- a/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_upgrade.yaml +++ b/x-pack/plugins/fleet/common/openapi/paths/agents@bulk_upgrade.yaml @@ -11,16 +11,6 @@ post: properties: actionId: type: string - description: action id when running in async mode (>10k agents) - additionalProperties: - type: object - properties: - success: - type: boolean - error: - type: string - required: - - success '400': description: BAD REQUEST content: diff --git a/x-pack/plugins/fleet/common/services/agent_status.ts b/x-pack/plugins/fleet/common/services/agent_status.ts index 72b912e573af3..55f93fca48d6f 100644 --- a/x-pack/plugins/fleet/common/services/agent_status.ts +++ b/x-pack/plugins/fleet/common/services/agent_status.ts @@ -47,7 +47,7 @@ export function getAgentStatus(agent: Agent | FleetServerAgent): AgentStatus { ? agent.policy_revision_idx : undefined; - if (!policyRevision || (agent.upgrade_started_at && agent.upgrade_status !== 'completed')) { + if (!policyRevision || (agent.upgrade_started_at && !agent.upgraded_at)) { return 'updating'; } @@ -75,7 +75,7 @@ export function getPreviousAgentStatusForOfflineAgents( ? agent.policy_revision_idx : undefined; - if (!policyRevision || (agent.upgrade_started_at && agent.upgrade_status !== 'completed')) { + if (!policyRevision || (agent.upgrade_started_at && !agent.upgraded_at)) { return 'updating'; } } @@ -109,7 +109,7 @@ export function buildKueryForOfflineAgents(path: string = ''): string { } export function buildKueryForUpgradingAgents(path: string = ''): string { - return `(${path}upgrade_started_at:*) and not (${path}upgrade_status:completed)`; + return `(${path}upgrade_started_at:*) and not (${path}upgraded_at:*)`; } export function buildKueryForUpdatingAgents(path: string = ''): string { diff --git a/x-pack/plugins/fleet/common/services/is_agent_upgradeable.ts b/x-pack/plugins/fleet/common/services/is_agent_upgradeable.ts index c4c9fa7e75a69..2a523d1a2eabb 100644 --- a/x-pack/plugins/fleet/common/services/is_agent_upgradeable.ts +++ b/x-pack/plugins/fleet/common/services/is_agent_upgradeable.ts @@ -25,7 +25,7 @@ export function isAgentUpgradeable(agent: Agent, kibanaVersion: string, versionT return false; } // check that the agent is not already in the process of updating - if (agent.upgrade_started_at && agent.upgrade_status !== 'completed') { + if (agent.upgrade_started_at && !agent.upgraded_at) { return false; } if (versionToUpgrade !== undefined) { diff --git a/x-pack/plugins/fleet/common/types/models/agent.ts b/x-pack/plugins/fleet/common/types/models/agent.ts index 9ca69b5100625..5def12287b4fd 100644 --- a/x-pack/plugins/fleet/common/types/models/agent.ts +++ b/x-pack/plugins/fleet/common/types/models/agent.ts @@ -75,9 +75,8 @@ interface AgentBase { enrolled_at: string; unenrolled_at?: string; unenrollment_started_at?: string; - upgraded_at?: string; + upgraded_at?: string | null; upgrade_started_at?: string | null; - upgrade_status?: 'started' | 'completed'; access_api_key_id?: string; default_api_key?: string; default_api_key_id?: string; @@ -188,15 +187,11 @@ export interface FleetServerAgent { /** * Date/time the Elastic Agent was last upgraded */ - upgraded_at?: string; + upgraded_at?: string | null; /** * Date/time the Elastic Agent started the current upgrade */ upgrade_started_at?: string | null; - /** - * Upgrade status - */ - upgrade_status?: 'started' | 'completed'; /** * ID of the API key the Elastic Agent must used to contact Fleet Server */ diff --git a/x-pack/plugins/fleet/common/types/models/package_spec.ts b/x-pack/plugins/fleet/common/types/models/package_spec.ts index 4463bb81097e2..52f993499ea4e 100644 --- a/x-pack/plugins/fleet/common/types/models/package_spec.ts +++ b/x-pack/plugins/fleet/common/types/models/package_spec.ts @@ -42,6 +42,7 @@ export type PackageSpecCategory = | 'datastore' | 'elastic_stack' | 'google_cloud' + | 'infrastructure' | 'kubernetes' | 'languages' | 'message_queue' diff --git a/x-pack/plugins/fleet/common/types/rest_spec/agent.ts b/x-pack/plugins/fleet/common/types/rest_spec/agent.ts index f1fbe4469de44..9a18613d95834 100644 --- a/x-pack/plugins/fleet/common/types/rest_spec/agent.ts +++ b/x-pack/plugins/fleet/common/types/rest_spec/agent.ts @@ -72,13 +72,9 @@ export interface PostBulkAgentUnenrollRequest { }; } -export type BulkAgentAction = Record< - Agent['id'], - { - success: boolean; - error?: string; - } -> & { actionId?: string }; +export interface BulkAgentAction { + actionId: string; +} export type PostBulkAgentUnenrollResponse = BulkAgentAction; diff --git a/x-pack/plugins/fleet/dev_docs/fleet_ui_extensions.md b/x-pack/plugins/fleet/dev_docs/fleet_ui_extensions.md index 9dcb7112f7ef0..46788ecac5da0 100644 --- a/x-pack/plugins/fleet/dev_docs/fleet_ui_extensions.md +++ b/x-pack/plugins/fleet/dev_docs/fleet_ui_extensions.md @@ -33,6 +33,12 @@ export class Plugin { component: LazyEndpointPolicyCreateExtension, }); + registerExtension({ + package: 'endpoint', + view: 'package-policy-create-multi-step', + component: LazyEndpointPolicyCreateMultiStepExtension, + }); + registerExtension({ package: 'endpoint', view: 'package-detail-custom', diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/confirm_incoming_data_with_preview.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/confirm_incoming_data_with_preview.tsx index af0e3c882ea50..011134151cbd7 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/confirm_incoming_data_with_preview.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/confirm_incoming_data_with_preview.tsx @@ -75,7 +75,8 @@ const HitPreview: React.FC<{ hit: SearchHit }> = ({ hit }) => { ); const listItems = Object.entries(hitForDisplay).map(([key, value]) => ({ title: `${key}:`, - description: value, + // Ensures arrays and collections of nested objects are displayed correctly + description: JSON.stringify(value), })); return ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/page_steps/add_integration.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/page_steps/add_integration.tsx index bce4d71b04259..c5ccd2916e465 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/page_steps/add_integration.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/page_steps/add_integration.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { useCallback, useState, useEffect } from 'react'; +import React, { useCallback, useState, useEffect, useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiSpacer, EuiButtonEmpty, EuiFlexItem, EuiFlexGroup } from '@elastic/eui'; import { safeLoad } from 'js-yaml'; @@ -19,9 +19,9 @@ import { isVerificationError } from '../../../../../../../../services'; import type { MultiPageStepLayoutProps } from '../../types'; import type { PackagePolicyFormState } from '../../../types'; import type { NewPackagePolicy } from '../../../../../../types'; -import { sendCreatePackagePolicy, useStartServices } from '../../../../../../hooks'; +import { sendCreatePackagePolicy, useStartServices, useUIExtension } from '../../../../../../hooks'; import type { RequestError } from '../../../../../../hooks'; -import { Error } from '../../../../../../components'; +import { Error, ExtensionWrapper } from '../../../../../../components'; import { sendGeneratePackagePolicy } from '../../hooks'; import { CreatePackagePolicyBottomBar, StandaloneModeWarningCallout } from '..'; import type { PackagePolicyValidationResults } from '../../../services'; @@ -212,6 +212,55 @@ export const AddIntegrationPageStep: React.FC = (props getBasePolicy(); }, []); // eslint-disable-line react-hooks/exhaustive-deps + const extensionView = useUIExtension(packageInfo.name ?? '', 'package-policy-create-multi-step'); + const addIntegrationExtensionView = useMemo(() => { + return ( + extensionView && ( + + + + ) + ); + }, [packagePolicy, extensionView]); + + const content = useMemo(() => { + if (packageInfo.name !== 'endpoint') { + return ( + <> + + + {validationResults && ( + + + + )} + + ); + } + }, [ + formState, + integrationInfo?.name, + packageInfo, + packagePolicy, + updatePackagePolicy, + validationResults, + ]); + if (!agentPolicy) { return ( = (props return ( <> {isManaged ? null : } - - - {validationResults && ( - - - - )} + {content} + {addIntegrationExtensionView} setIsManaged(true)} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.test.tsx new file mode 100644 index 0000000000000..68a3420780039 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.test.tsx @@ -0,0 +1,316 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { act, render, fireEvent } from '@testing-library/react'; +// eslint-disable-next-line @kbn/eslint/module_migration +import { IntlProvider } from 'react-intl'; + +import { useActionStatus } from '../hooks'; +import { useGetAgentPolicies, useStartServices } from '../../../../hooks'; + +import { AgentActivityFlyout } from './agent_activity_flyout'; + +jest.mock('../hooks'); +jest.mock('../../../../hooks'); + +const mockUseActionStatus = useActionStatus as jest.Mock; +const mockUseGetAgentPolicies = useGetAgentPolicies as jest.Mock; +const mockUseStartServices = useStartServices as jest.Mock; + +describe('AgentActivityFlyout', () => { + const mockOnClose = jest.fn(); + const mockOnAbortSuccess = jest.fn(); + const mockAbortUpgrade = jest.fn(); + + beforeEach(() => { + mockOnClose.mockReset(); + mockOnAbortSuccess.mockReset(); + mockAbortUpgrade.mockReset(); + mockUseActionStatus.mockReset(); + mockUseGetAgentPolicies.mockReturnValue({ + data: { + items: [ + { id: 'policy1', name: 'Policy 1' }, + { id: 'policy2', name: 'Policy 2' }, + ], + }, + }); + mockUseStartServices.mockReturnValue({ + docLinks: { links: { fleet: { upgradeElasticAgent: 'https://elastic.co' } } }, + }); + }); + + beforeEach(() => { + jest.useFakeTimers('modern').setSystemTime(new Date('2022-09-15T10:00:00.000Z')); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + const renderComponent = () => { + return render( + + + + ); + }; + + it('should render agent activity for in progress upgrade', () => { + const mockActionStatuses = [ + { + actionId: 'action2', + nbAgentsActionCreated: 5, + nbAgentsAck: 0, + version: '8.5.0', + startTime: '2022-09-15T10:00:00.000Z', + type: 'UPGRADE', + nbAgentsActioned: 5, + status: 'IN_PROGRESS', + expiration: '2099-09-16T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 0, + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.getByText('Agent activity')).toBeInTheDocument(); + + expect( + result.container.querySelector('[data-test-subj="upgradeInProgressTitle"]')!.textContent + ).toEqual('Upgrading 5 agents to version 8.5.0'); + // compare without whitespace,   doesn't match + expect( + result.container + .querySelector('[data-test-subj="upgradeInProgressDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Started on Sep 15, 2022 10:00 AM. Learn more'.replace(/\s/g, '')); + + act(() => { + fireEvent.click(result.getByText('Abort upgrade')); + }); + + expect(mockAbortUpgrade).toHaveBeenCalled(); + }); + + it('should render agent activity for scheduled upgrade', () => { + const mockActionStatuses = [ + { + actionId: 'action2', + nbAgentsActionCreated: 5, + nbAgentsAck: 0, + version: '8.5.0', + startTime: '2022-09-16T10:00:00.000Z', + type: 'UPGRADE', + nbAgentsActioned: 5, + status: 'IN_PROGRESS', + expiration: '2099-09-17T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 0, + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.getByText('Agent activity')).toBeInTheDocument(); + + expect( + result.container.querySelector('[data-test-subj="upgradeInProgressTitle"]')!.textContent + ).toEqual('5 agents scheduled to upgrade to version 8.5.0'); + expect( + result.container + .querySelector('[data-test-subj="upgradeInProgressDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Scheduled for Sep 16, 2022 10:00 AM. Learn more'.replace(/\s/g, '')); + + act(() => { + fireEvent.click(result.getByText('Abort upgrade')); + }); + + expect(mockAbortUpgrade).toHaveBeenCalled(); + }); + + it('should render agent activity for complete upgrade', () => { + const mockActionStatuses = [ + { + actionId: 'action3', + nbAgentsActionCreated: 2, + nbAgentsAck: 2, + type: 'UPGRADE', + nbAgentsActioned: 2, + status: 'COMPLETE', + expiration: '2099-09-16T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 0, + completionTime: '2022-09-15T12:00:00.000Z', + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.container.querySelector('[data-test-subj="statusTitle"]')!.textContent).toEqual( + '2 agents upgraded' + ); + expect( + result.container + .querySelector('[data-test-subj="statusDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Completed Sep 15, 2022 12:00 PM'.replace(/\s/g, '')); + }); + + it('should render agent activity for expired unenroll', () => { + const mockActionStatuses = [ + { + actionId: 'action4', + nbAgentsActionCreated: 3, + nbAgentsAck: 0, + type: 'UNENROLL', + nbAgentsActioned: 3, + status: 'EXPIRED', + expiration: '2022-09-14T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 0, + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.container.querySelector('[data-test-subj="statusTitle"]')!.textContent).toEqual( + 'Agent unenrollment expired' + ); + expect( + result.container + .querySelector('[data-test-subj="statusDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Expired on Sep 14, 2022 10:00 AM'.replace(/\s/g, '')); + }); + + it('should render agent activity for cancelled upgrade', () => { + const mockActionStatuses = [ + { + actionId: 'action5', + nbAgentsActionCreated: 3, + nbAgentsAck: 0, + startTime: '2022-09-15T10:00:00.000Z', + type: 'UPGRADE', + nbAgentsActioned: 3, + status: 'CANCELLED', + expiration: '2099-09-16T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 0, + cancellationTime: '2022-09-15T11:00:00.000Z', + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.container.querySelector('[data-test-subj="statusTitle"]')!.textContent).toEqual( + 'Agent upgrade cancelled' + ); + expect( + result.container + .querySelector('[data-test-subj="statusDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Cancelled on Sep 15, 2022 11:00 AM'.replace(/\s/g, '')); + }); + + it('should render agent activity for failed reassign', () => { + const mockActionStatuses = [ + { + actionId: 'action7', + nbAgentsActionCreated: 1, + nbAgentsAck: 0, + type: 'POLICY_REASSIGN', + nbAgentsActioned: 1, + status: 'FAILED', + expiration: '2099-09-16T10:00:00.000Z', + newPolicyId: 'policy1', + creationTime: '2022-09-15T10:00:00.000Z', + nbAgentsFailed: 1, + completionTime: '2022-09-15T11:00:00.000Z', + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.container.querySelector('[data-test-subj="statusTitle"]')!.textContent).toEqual( + '0 of 1 agent assigned to a new policy' + ); + expect( + result.container + .querySelector('[data-test-subj="statusDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain( + 'A problem occurred during this operation. Started on Sep 15, 2022 10:00 AM.'.replace( + /\s/g, + '' + ) + ); + }); + + it('should render agent activity for unknown action', () => { + const mockActionStatuses = [ + { + actionId: 'action8', + nbAgentsActionCreated: 3, + nbAgentsAck: 0, + type: 'UNKNOWN', + nbAgentsActioned: 3, + status: 'COMPLETE', + expiration: '2022-09-14T10:00:00.000Z', + creationTime: '2022-09-15T10:00:00.000Z', + completionTime: '2022-09-15T12:00:00.000Z', + nbAgentsFailed: 0, + }, + ]; + mockUseActionStatus.mockReturnValue({ + currentActions: mockActionStatuses, + abortUpgrade: mockAbortUpgrade, + isFirstLoading: true, + }); + const result = renderComponent(); + + expect(result.container.querySelector('[data-test-subj="statusTitle"]')!.textContent).toEqual( + '0 of 3 agents actioned' + ); + expect( + result.container + .querySelector('[data-test-subj="statusDescription"]')! + .textContent?.replace(/\s/g, '') + ).toContain('Completed Sep 15, 2022 12:00 PM'.replace(/\s/g, '')); + }); +}); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.tsx index 929eb4bbf54d1..dfa6623f4a90a 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/agent_activity_flyout.tsx @@ -176,6 +176,7 @@ export const AgentActivityFlyout: React.FunctionComponent<{ ) : null} {Object.keys(otherDays).map((day) => ( } actions={otherDays[day]} abortUpgrade={abortUpgrade} @@ -215,9 +216,13 @@ const ActivitySection: React.FunctionComponent<{
{actions.map((currentAction) => currentAction.type === 'UPGRADE' && currentAction.status === 'IN_PROGRESS' ? ( - + ) : ( - + ) )} @@ -272,7 +277,7 @@ const inProgressTitle = (action: ActionStatus) => ( defaultMessage="{inProgressText} {nbAgents} {agents} {reassignText}{upgradeText}" values={{ nbAgents: - action.nbAgentsAck === action.nbAgentsActioned + action.nbAgentsAck >= action.nbAgentsActioned ? action.nbAgentsAck : action.nbAgentsAck === 0 ? action.nbAgentsActioned @@ -438,14 +443,19 @@ const ActivityItem: React.FunctionComponent<{ action: ActionStatus }> = ({ actio {displayByStatus[action.status].icon} - + {displayByStatus[action.status].title}
- {displayByStatus[action.status].description} + + {displayByStatus[action.status].description} +
@@ -486,7 +496,7 @@ export const UpgradeInProgressActivityItem: React.FunctionComponent<{ {isScheduled ? : }
- + {isScheduled && action.startTime ? ( - +

{isScheduled && action.startTime ? ( <> @@ -541,7 +551,7 @@ export const UpgradeInProgressActivityItem: React.FunctionComponent<{ size="s" onClick={onClickAbortUpgrade} isLoading={isAborting} - data-test-subj="currentBulkUpgrade.abortBtn" + data-test-subj="abortBtn" > props.theme.eui.euiSizeL}; -`; export interface Props { totalAgents: number; totalInactiveAgents: number; @@ -228,42 +224,36 @@ export const AgentBulkActions: React.FunctionComponent = ({ }} onClosePopover={() => { setIsTagAddVisible(false); + closeMenu(); }} /> )} - {(selectionMode === 'manual' && selectedAgents.length) || - (selectionMode === 'query' && totalAgents > 0) ? ( - <> - - - - - } - isOpen={isMenuOpen} - closePopover={closeMenu} - panelPaddingSize="none" - anchorPosition="downLeft" + + - - - - - ) : ( - - )} + + + } + isOpen={isMenuOpen} + closePopover={closeMenu} + panelPaddingSize="none" + anchorPosition="downLeft" + > + + + ); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/bulk_actions.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.test.tsx similarity index 67% rename from x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/bulk_actions.test.tsx rename to x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.test.tsx index 71e673fd30e19..33fd16419a1bd 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/bulk_actions.test.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.test.tsx @@ -20,8 +20,7 @@ import { FleetStatusProvider, ConfigContext, KibanaVersionContext } from '../../ import { getMockTheme } from '../../../../../../mocks'; -import { AgentBulkActions } from './bulk_actions'; -import type { Props } from './bulk_actions'; +import { SearchAndFilterBar } from './search_and_filter_bar'; const mockTheme = getMockTheme({ eui: { @@ -29,13 +28,19 @@ const mockTheme = getMockTheme({ }, }); -const TestComponent = (props: Props) => ( +jest.mock('../../../../components', () => { + return { + SearchBar: () =>

, + }; +}); + +const TestComponent = (props: any) => ( - + @@ -43,10 +48,10 @@ const TestComponent = (props: Props) => ( ); -describe('AgentBulkActions', () => { +describe('SearchAndFilterBar', () => { it('should show no Actions button when no agent is selected', async () => { const selectedAgents: Agent[] = []; - const props: Props = { + const props: any = { totalAgents: 10, totalInactiveAgents: 2, selectionMode: 'manual', @@ -54,8 +59,12 @@ describe('AgentBulkActions', () => { selectedAgents, refreshAgents: () => undefined, visibleAgents: [], - allTags: [], + tags: [], agentPolicies: [], + selectedStatus: [], + selectedTags: [], + selectedAgentPolicies: [], + showAgentActivityTour: {}, }; const testBed = registerTestBed(TestComponent)(props); const { exists } = testBed; @@ -76,7 +85,7 @@ describe('AgentBulkActions', () => { local_metadata: {}, }, ]; - const props: Props = { + const props: any = { totalAgents: 10, totalInactiveAgents: 2, selectionMode: 'manual', @@ -84,8 +93,34 @@ describe('AgentBulkActions', () => { selectedAgents, refreshAgents: () => undefined, visibleAgents: [], - allTags: [], + tags: [], + agentPolicies: [], + selectedStatus: [], + selectedTags: [], + selectedAgentPolicies: [], + showAgentActivityTour: {}, + }; + const testBed = registerTestBed(TestComponent)(props); + const { exists } = testBed; + + expect(exists('agentBulkActionsButton')).not.toBeNull(); + }); + + it('should show an Actions button when agents selected in query mode', async () => { + const props: any = { + totalAgents: 10, + totalInactiveAgents: 2, + selectionMode: 'query', + currentQuery: '', + selectedAgents: [], + refreshAgents: () => undefined, + visibleAgents: [], + tags: [], agentPolicies: [], + selectedStatus: [], + selectedTags: [], + selectedAgentPolicies: [], + showAgentActivityTour: {}, }; const testBed = registerTestBed(TestComponent)(props); const { exists } = testBed; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.tsx index e90e1ae713227..9b16136df2d96 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.tsx @@ -69,6 +69,10 @@ const ClearAllTagsFilterItem = styled(EuiFilterSelectItem)` padding: ${(props) => props.theme.eui.euiSizeS}; `; +const FlexEndEuiFlexItem = styled(EuiFlexItem)` + align-self: flex-end; +`; + export const SearchAndFilterBar: React.FunctionComponent<{ agentPolicies: AgentPolicy[]; draftKuery: string; @@ -151,7 +155,51 @@ export const SearchAndFilterBar: React.FunctionComponent<{ return ( <> {/* Search and filter bar */} - + + + + + + + + + } + > + + + + + + + + } + > + + + + + + + @@ -328,63 +376,22 @@ export const SearchAndFilterBar: React.FunctionComponent<{ - {selectedAgents.length === 0 && ( - - - } - > - - - - + {(selectionMode === 'manual' && selectedAgents.length) || + (selectionMode === 'query' && totalAgents > 0) ? ( + + - )} - - - - {selectedAgents.length === 0 && ( - - - } - > - - - - - - )} - - - + ) : null} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.test.tsx index 8c4f9f3003c82..465db5236338c 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.test.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.test.tsx @@ -270,6 +270,59 @@ describe('TagsAddRemove', () => { ); }); + it('should add new tag twice quickly when not found in search and button clicked - bulk selection', () => { + mockBulkUpdateTags.mockImplementation((agents, tagsToAdd, tagsToRemove, onSuccess) => + onSuccess(false) + ); + + const result = renderComponent(undefined, 'query'); + const searchInput = result.getByRole('combobox'); + + fireEvent.input(searchInput, { + target: { value: 'newTag' }, + }); + + fireEvent.click(result.getAllByText('Create a new tag "newTag"')[0].closest('button')!); + + fireEvent.input(searchInput, { + target: { value: 'newTag2' }, + }); + + fireEvent.click(result.getAllByText('Create a new tag "newTag2"')[0].closest('button')!); + + expect(mockBulkUpdateTags).toHaveBeenCalledWith( + 'query', + ['newTag2', 'newTag'], + [], + expect.anything(), + 'Tag created', + 'Tag creation failed' + ); + }); + + it('should remove tags twice quickly on bulk selection', () => { + selectedTags = ['tag1', 'tag2']; + mockBulkUpdateTags.mockImplementation((agents, tagsToAdd, tagsToRemove, onSuccess) => + onSuccess(false) + ); + + const result = renderComponent(undefined, ''); + const getTag = (name: string) => result.getByText(name); + + fireEvent.click(getTag('tag1')); + + fireEvent.click(getTag('tag2')); + + expect(mockBulkUpdateTags).toHaveBeenCalledWith( + '', + [], + ['tag2', 'tag1'], + expect.anything(), + undefined, + undefined + ); + }); + it('should make tag options button visible on mouse enter', async () => { const result = renderComponent('agent1'); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.tsx index a03ec3808e9ab..70b4da44dad68 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/tags_add_remove.tsx @@ -6,7 +6,7 @@ */ import React, { Fragment, useEffect, useState, useMemo, useCallback } from 'react'; -import { difference } from 'lodash'; +import { difference, uniq } from 'lodash'; import styled from 'styled-components'; import type { EuiSelectableOption } from '@elastic/eui'; import { @@ -95,8 +95,9 @@ export const TagsAddRemove: React.FC = ({ if (hasCompleted) { return onTagsUpdated(); } - const newSelectedTags = difference(selectedTags, tagsToRemove).concat(tagsToAdd); - const allTagsWithNew = allTags.includes(tagsToAdd[0]) ? allTags : allTags.concat(tagsToAdd); + const selected = labels.filter((tag) => tag.checked === 'on').map((tag) => tag.label); + const newSelectedTags = difference(selected, tagsToRemove).concat(tagsToAdd); + const allTagsWithNew = uniq(allTags.concat(newSelectedTags)); const allTagsWithRemove = isRenameOrDelete ? difference(allTagsWithNew, tagsToRemove) : allTagsWithNew; @@ -109,8 +110,8 @@ export const TagsAddRemove: React.FC = ({ successMessage?: string, errorMessage?: string ) => { - const newSelectedTags = difference(selectedTags, tagsToRemove).concat(tagsToAdd); if (agentId) { + const newSelectedTags = difference(selectedTags, tagsToRemove).concat(tagsToAdd); updateTagsHook.updateTags( agentId, newSelectedTags, @@ -119,10 +120,22 @@ export const TagsAddRemove: React.FC = ({ errorMessage ); } else { + // sending updated tags to add/remove, in case multiple actions are done quickly and the first one is not yet propagated + const updatedTagsToAdd = tagsToAdd.concat( + labels + .filter((tag) => tag.checked === 'on' && !selectedTags.includes(tag.label)) + .map((tag) => tag.label) + ); + const updatedTagsToRemove = tagsToRemove.concat( + labels + .filter((tag) => tag.checked !== 'on' && selectedTags.includes(tag.label)) + .map((tag) => tag.label) + ); + updateTagsHook.bulkUpdateTags( agents!, - tagsToAdd, - tagsToRemove, + updatedTagsToAdd, + updatedTagsToRemove, (hasCompleted) => handleTagsUpdated(tagsToAdd, tagsToRemove, hasCompleted), successMessage, errorMessage diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_reassign_policy_modal/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_reassign_policy_modal/index.tsx index cae8b00fb6d3d..cb3f0d77eed34 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_reassign_policy_modal/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_reassign_policy_modal/index.tsx @@ -82,20 +82,13 @@ export const AgentReassignAgentPolicyModal: React.FunctionComponent = ({ throw res.error; } setIsSubmitting(false); - const hasCompleted = isSingleAgent || Object.keys(res.data ?? {}).length > 0; const successMessage = i18n.translate( 'xpack.fleet.agentReassignPolicy.successSingleNotificationTitle', { - defaultMessage: 'Agent policy reassigned', + defaultMessage: 'Reassigning agent policy', } ); - const submittedMessage = i18n.translate( - 'xpack.fleet.agentReassignPolicy.submittedNotificationTitle', - { - defaultMessage: 'Agent policy reassign submitted', - } - ); - notifications.toasts.addSuccess(hasCompleted ? successMessage : submittedMessage); + notifications.toasts.addSuccess(successMessage); onClose(); } catch (error) { setIsSubmitting(false); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_unenroll_modal/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_unenroll_modal/index.tsx index 7c0c0136c3d09..72b1e00c1ed02 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_unenroll_modal/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_unenroll_modal/index.tsx @@ -40,7 +40,7 @@ export const AgentUnenrollAgentModal: React.FunctionComponent = ({ async function onSubmit() { try { setIsSubmitting(true); - const { error, data } = isSingleAgent + const { error } = isSingleAgent ? await sendPostAgentUnenroll((agents[0] as Agent).id, { revoke: forceUnenroll, }) @@ -52,13 +52,6 @@ export const AgentUnenrollAgentModal: React.FunctionComponent = ({ throw error; } setIsSubmitting(false); - const hasCompleted = isSingleAgent || Object.keys(data ?? {}).length > 0; - const submittedMessage = i18n.translate( - 'xpack.fleet.unenrollAgents.submittedNotificationTitle', - { - defaultMessage: 'Agent(s) unenroll submitted', - } - ); if (forceUnenroll) { const successMessage = isSingleAgent ? i18n.translate('xpack.fleet.unenrollAgents.successForceSingleNotificationTitle', { @@ -67,7 +60,7 @@ export const AgentUnenrollAgentModal: React.FunctionComponent = ({ : i18n.translate('xpack.fleet.unenrollAgents.successForceMultiNotificationTitle', { defaultMessage: 'Agents unenrolled', }); - notifications.toasts.addSuccess(hasCompleted ? successMessage : submittedMessage); + notifications.toasts.addSuccess(successMessage); } else { const successMessage = isSingleAgent ? i18n.translate('xpack.fleet.unenrollAgents.successSingleNotificationTitle', { @@ -76,7 +69,7 @@ export const AgentUnenrollAgentModal: React.FunctionComponent = ({ : i18n.translate('xpack.fleet.unenrollAgents.successMultiNotificationTitle', { defaultMessage: 'Unenrolling agents', }); - notifications.toasts.addSuccess(hasCompleted ? successMessage : submittedMessage); + notifications.toasts.addSuccess(successMessage); } onClose(); } catch (error) { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_upgrade_modal/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_upgrade_modal/index.tsx index c1c45f47ff02f..d7d376e83e316 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_upgrade_modal/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/agent_upgrade_modal/index.tsx @@ -162,7 +162,7 @@ export const AgentUpgradeAgentModal: React.FunctionComponent { - ++acc.total; - ++acc[result.success ? 'success' : 'error']; - return acc; - }, - { - total: 0, - success: 0, - error: 0, - } - ); setIsSubmitting(false); - const hasCompleted = isSingleAgent || Object.keys(data ?? {}).length > 0; - const submittedMessage = i18n.translate( - 'xpack.fleet.upgradeAgents.submittedNotificationTitle', - { - defaultMessage: 'Agent(s) upgrade submitted', - } + notifications.toasts.addSuccess( + i18n.translate('xpack.fleet.upgradeAgents.successNotificationTitle', { + defaultMessage: 'Upgrading agent(s)', + }) ); - - if (!hasCompleted) { - notifications.toasts.addSuccess(submittedMessage); - } else if (counts.success === counts.total) { - notifications.toasts.addSuccess( - i18n.translate('xpack.fleet.upgradeAgents.successSingleNotificationTitle', { - defaultMessage: 'Upgrading {count, plural, one {# agent} other {# agents}}', - values: { count: isSingleAgent ? 1 : counts.total }, - }) - ); - } else if (counts.error === counts.total) { - notifications.toasts.addDanger( - i18n.translate('xpack.fleet.upgradeAgents.bulkResultAllErrorsNotificationTitle', { - defaultMessage: - 'Error upgrading {count, plural, one {agent} other {{count} agents} =true {all selected agents}}', - values: { count: isAllAgents || agentCount }, - }) - ); - } else { - notifications.toasts.addWarning({ - text: i18n.translate('xpack.fleet.upgradeAgents.bulkResultErrorResultsSummary', { - defaultMessage: - '{count} {count, plural, one {agent was} other {agents were}} not successful', - values: { count: counts.error }, - }), - }); - } onClose(); } catch (error) { setIsSubmitting(false); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom_languages_overview.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom_languages_overview.tsx index 93e7c6e0fac22..c8c1914599f08 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom_languages_overview.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom_languages_overview.tsx @@ -6,9 +6,10 @@ */ import React from 'react'; import { useParams, Redirect } from 'react-router-dom'; +import { capitalize } from 'lodash'; import { getCustomIntegrationsStart } from '../../../../../../services/custom_integrations'; -import { useLink } from '../../../../../../hooks'; +import { useLink, useBreadcrumbs } from '../../../../hooks'; export interface CustomLanguageClientsParams { pkgkey: string; } @@ -20,10 +21,9 @@ export interface CustomLanguageClientsParams { export const CustomLanguagesOverview = () => { const { pkgkey } = useParams(); const { getPath } = useLink(); + useBreadcrumbs('integration_details_overview', { pkgTitle: capitalize(pkgkey) }); - const Component = getCustomIntegrationsStart().languageClientsUiComponents.get( - `language_client.${pkgkey}` - ); + const Component = getCustomIntegrationsStart().languageClientsUiComponents[pkgkey]; return Component ? : ; }; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.test.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.test.ts index 8d556434f8828..e085b9034235b 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.test.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.test.ts @@ -131,7 +131,7 @@ describe('getInstallPkgRouteOptions', () => { expect(getInstallPkgRouteOptions(opts)).toEqual(['fleet', expectedOptions]); }); - it('should not navigate to steps app for endpoint', () => { + it('should navigate to steps app for endpoint', () => { const opts = { currentPath: 'currentPath', integration: 'myintegration', @@ -144,7 +144,7 @@ describe('getInstallPkgRouteOptions', () => { const expectedRedirectURl = '/detail/endpoint-1.0.0/policies?integration=myintegration'; const expectedOptions = { - path: '/integrations/endpoint-1.0.0/add-integration/myintegration', + path: '/integrations/endpoint-1.0.0/add-integration/myintegration?useMultiPageLayout', state: { onCancelUrl: 'currentPath', onCancelNavigateTo: [ diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.ts index c4e6d7ffc4a84..6a8612a44f42f 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/get_install_route_options.ts @@ -13,7 +13,6 @@ const EXCLUDED_PACKAGES = [ 'apm', 'cloud_security_posture', 'dga', - 'endpoint', 'fleet_server', 'kubernetes', 'osquery_manager', diff --git a/x-pack/plugins/fleet/public/index.ts b/x-pack/plugins/fleet/public/index.ts index a55937999c4d6..823d46becb4ff 100644 --- a/x-pack/plugins/fleet/public/index.ts +++ b/x-pack/plugins/fleet/public/index.ts @@ -35,6 +35,9 @@ export type { PackagePolicyCreateExtension, PackagePolicyCreateExtensionComponent, PackagePolicyCreateExtensionComponentProps, + PackagePolicyCreateMultiStepExtension, + PackagePolicyCreateMultiStepExtensionComponent, + PackagePolicyCreateMultiStepExtensionComponentProps, PackagePolicyEditExtension, PackagePolicyEditExtensionComponent, PackagePolicyEditExtensionComponentProps, diff --git a/x-pack/plugins/fleet/public/plugin.ts b/x-pack/plugins/fleet/public/plugin.ts index 5b5a31461c911..b1d845aa9e52f 100644 --- a/x-pack/plugins/fleet/public/plugin.ts +++ b/x-pack/plugins/fleet/public/plugin.ts @@ -46,7 +46,7 @@ import type { GlobalSearchPluginSetup } from '@kbn/global-search-plugin/public'; import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; import { PLUGIN_ID, INTEGRATIONS_PLUGIN_ID, setupRouteService, appRoutesService } from '../common'; -import { calculateAuthz } from '../common/authz'; +import { calculateAuthz, calculatePackagePrivilegesFromCapabilities } from '../common/authz'; import { parseExperimentalConfigValue } from '../common/experimental_features'; import type { CheckPermissionsResponse, PostFleetSetupResponse } from '../common/types'; import type { FleetAuthz } from '../common'; @@ -277,17 +277,20 @@ export class FleetPlugin implements Plugin { const permissionsResponse = await getPermissions(); diff --git a/x-pack/plugins/fleet/public/types/ui_extensions.ts b/x-pack/plugins/fleet/public/types/ui_extensions.ts index c3a9f05fc7d9f..24f9fef730613 100644 --- a/x-pack/plugins/fleet/public/types/ui_extensions.ts +++ b/x-pack/plugins/fleet/public/types/ui_extensions.ts @@ -132,6 +132,25 @@ export interface PackagePolicyCreateExtension { Component: LazyExoticComponent; } +/** + * UI Component Extension is used on the pages displaying the ability to Create a multi step + * Integration Policy + */ +export type PackagePolicyCreateMultiStepExtensionComponent = + ComponentType; + +export interface PackagePolicyCreateMultiStepExtensionComponentProps { + /** The integration policy being created */ + newPolicy: NewPackagePolicy; +} + +/** Extension point registration contract for Integration Policy Create views in multi-step onboarding */ +export interface PackagePolicyCreateMultiStepExtension { + package: string; + view: 'package-policy-create-multi-step'; + Component: LazyExoticComponent; +} + /** * UI Component Extension is used to display a Custom tab (and view) under a given Integration */ @@ -178,4 +197,5 @@ export type UIExtensionPoint = | PackagePolicyCreateExtension | PackageAssetsExtension | PackageGenericErrorsListExtension - | AgentEnrollmentFlyoutFinalStepExtension; + | AgentEnrollmentFlyoutFinalStepExtension + | PackagePolicyCreateMultiStepExtension; diff --git a/x-pack/plugins/fleet/server/constants/index.ts b/x-pack/plugins/fleet/server/constants/index.ts index 87f0b5eeedfcf..cd0c0262a77d2 100644 --- a/x-pack/plugins/fleet/server/constants/index.ts +++ b/x-pack/plugins/fleet/server/constants/index.ts @@ -64,6 +64,8 @@ export { DEFAULT_DOWNLOAD_SOURCE_URI, DOWNLOAD_SOURCE_SAVED_OBJECT_TYPE, DEFAULT_DOWNLOAD_SOURCE_ID, + // Authz + ENDPOINT_PRIVILEGES, } from '../../common/constants'; export { diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts index 1ae6fb81742d1..86f202381119f 100644 --- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts @@ -25,8 +25,6 @@ import type { GetOneAgentResponse, GetAgentStatusResponse, PutAgentReassignResponse, - PostBulkAgentReassignResponse, - PostBulkUpdateAgentTagsResponse, GetAgentTagsResponse, GetAvailableVersionsResponse, GetActionStatusResponse, @@ -151,15 +149,7 @@ export const bulkUpdateAgentTagsHandler: RequestHandler< request.body.tagsToRemove ?? [] ); - const body = results.items.reduce((acc: any, so: any) => { - acc[so.id] = { - success: !so.error, - error: so.error?.message, - }; - return acc; - }, {}); - - return response.ok({ body: { ...body, actionId: results.actionId } }); + return response.ok({ body: { actionId: results.actionId } }); } catch (error) { return defaultFleetErrorHandler({ error, response }); } @@ -267,15 +257,7 @@ export const postBulkAgentsReassignHandler: RequestHandler< request.body.policy_id ); - const body = results.items.reduce((acc, so) => { - acc[so.id] = { - success: !so.error, - error: so.error?.message, - }; - return acc; - }, {}); - - return response.ok({ body: { ...body, actionId: results.actionId } }); + return response.ok({ body: { actionId: results.actionId } }); } catch (error) { return defaultFleetErrorHandler({ error, response }); } diff --git a/x-pack/plugins/fleet/server/routes/agent/unenroll_handler.ts b/x-pack/plugins/fleet/server/routes/agent/unenroll_handler.ts index db5a497a30869..740cf3a7b716c 100644 --- a/x-pack/plugins/fleet/server/routes/agent/unenroll_handler.ts +++ b/x-pack/plugins/fleet/server/routes/agent/unenroll_handler.ts @@ -8,10 +8,7 @@ import type { RequestHandler } from '@kbn/core/server'; import type { TypeOf } from '@kbn/config-schema'; -import type { - PostAgentUnenrollResponse, - PostBulkAgentUnenrollResponse, -} from '../../../common/types'; +import type { PostAgentUnenrollResponse } from '../../../common/types'; import type { PostAgentUnenrollRequestSchema, PostBulkAgentUnenrollRequestSchema, @@ -59,15 +56,8 @@ export const postBulkAgentsUnenrollHandler: RequestHandler< force: request.body?.force, batchSize: request.body?.batchSize, }); - const body = results.items.reduce((acc, so) => { - acc[so.id] = { - success: !so.error, - error: so.error?.message, - }; - return acc; - }, {}); - return response.ok({ body: { ...body, actionId: results.actionId } }); + return response.ok({ body: { actionId: results.actionId } }); } catch (error) { return defaultFleetErrorHandler({ error, response }); } diff --git a/x-pack/plugins/fleet/server/routes/agent/upgrade_handler.ts b/x-pack/plugins/fleet/server/routes/agent/upgrade_handler.ts index 4af0c1ff653b2..a79edbaa36856 100644 --- a/x-pack/plugins/fleet/server/routes/agent/upgrade_handler.ts +++ b/x-pack/plugins/fleet/server/routes/agent/upgrade_handler.ts @@ -11,11 +11,7 @@ import type { TypeOf } from '@kbn/config-schema'; import semverCoerce from 'semver/functions/coerce'; import semverGt from 'semver/functions/gt'; -import type { - PostAgentUpgradeResponse, - PostBulkAgentUpgradeResponse, - GetCurrentUpgradesResponse, -} from '../../../common/types'; +import type { PostAgentUpgradeResponse, GetCurrentUpgradesResponse } from '../../../common/types'; import type { PostAgentUpgradeRequestSchema, PostBulkAgentUpgradeRequestSchema } from '../../types'; import * as AgentService from '../../services/agents'; import { appContextService } from '../../services'; @@ -47,26 +43,43 @@ export const postAgentUpgradeHandler: RequestHandler< }, }); } - const agent = await getAgentById(esClient, request.params.agentId); + try { + const agent = await getAgentById(esClient, request.params.agentId); - if (agent.unenrollment_started_at || agent.unenrolled_at) { - return response.customError({ - statusCode: 400, - body: { - message: 'cannot upgrade an unenrolling or unenrolled agent', - }, - }); - } - if (!force && !isAgentUpgradeable(agent, kibanaVersion, version)) { - return response.customError({ - statusCode: 400, - body: { - message: `agent ${request.params.agentId} is not upgradeable`, - }, - }); - } + const fleetServerAgents = await getAllFleetServerAgents(soClient, esClient); + const agentIsFleetServer = fleetServerAgents.some( + (fleetServerAgent) => fleetServerAgent.id === agent.id + ); + if (!agentIsFleetServer) { + try { + checkFleetServerVersion(version, fleetServerAgents); + } catch (err) { + return response.customError({ + statusCode: 400, + body: { + message: err.message, + }, + }); + } + } + + if (agent.unenrollment_started_at || agent.unenrolled_at) { + return response.customError({ + statusCode: 400, + body: { + message: 'cannot upgrade an unenrolling or unenrolled agent', + }, + }); + } + if (!force && !isAgentUpgradeable(agent, kibanaVersion, version)) { + return response.customError({ + statusCode: 400, + body: { + message: `agent ${request.params.agentId} is not upgradeable`, + }, + }); + } - try { await AgentService.sendUpgradeAgentAction({ soClient, esClient, @@ -125,15 +138,8 @@ export const postBulkAgentsUpgradeHandler: RequestHandler< batchSize, }; const results = await AgentService.sendUpgradeAgentsActions(soClient, esClient, upgradeOptions); - const body = results.items.reduce((acc, so) => { - acc[so.id] = { - success: !so.error, - error: so.error?.message, - }; - return acc; - }, {}); - - return response.ok({ body: { ...body, actionId: results.actionId } }); + + return response.ok({ body: { actionId: results.actionId } }); } catch (error) { return defaultFleetErrorHandler({ error, response }); } diff --git a/x-pack/plugins/fleet/server/routes/security.ts b/x-pack/plugins/fleet/server/routes/security.ts index 410bd9a5b9224..da90480944a46 100644 --- a/x-pack/plugins/fleet/server/routes/security.ts +++ b/x-pack/plugins/fleet/server/routes/security.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { DEFAULT_APP_CATEGORIES } from '@kbn/core-application-common'; import type { IRouter, RouteConfig, @@ -17,11 +18,11 @@ import type { import type { FleetAuthz } from '../../common'; import { INTEGRATIONS_PLUGIN_ID } from '../../common'; -import { calculateAuthz } from '../../common/authz'; +import { calculateAuthz, calculatePackagePrivilegesFromKibanaPrivileges } from '../../common/authz'; import { appContextService } from '../services'; import type { FleetRequestHandlerContext } from '../types'; -import { PLUGIN_ID } from '../constants'; +import { PLUGIN_ID, ENDPOINT_PRIVILEGES } from '../constants'; function checkSecurityEnabled() { return appContextService.getSecurityLicense().isEnabled(); @@ -63,12 +64,16 @@ export async function getAuthzFromRequest(req: KibanaRequest): Promise + security.authz.actions.api.get(`${DEFAULT_APP_CATEGORIES.security.id}-${privilege}`) + ); const { privileges } = await checkPrivileges({ kibana: [ security.authz.actions.api.get(`${PLUGIN_ID}-all`), security.authz.actions.api.get(`${PLUGIN_ID}-setup`), security.authz.actions.api.get(`${INTEGRATIONS_PLUGIN_ID}-all`), security.authz.actions.api.get(`${INTEGRATIONS_PLUGIN_ID}-read`), + ...endpointPrivileges, ], }); const fleetAllAuth = getAuthorizationFromPrivileges(privileges.kibana, `${PLUGIN_ID}-all`); @@ -82,14 +87,17 @@ export async function getAuthzFromRequest(req: KibanaRequest): Promise; + protected abstract processAgents(agents: Agent[]): Promise<{ actionId: string }>; /** * Common runner logic accross all agent bulk actions @@ -73,7 +73,7 @@ export abstract class ActionRunner { * On errors, starts a task with Task Manager to retry max 3 times * If the last batch was stored in state, retry continues from there (searchAfter) */ - public async runActionAsyncWithRetry(): Promise<{ items: BulkActionResult[]; actionId: string }> { + public async runActionAsyncWithRetry(): Promise<{ actionId: string }> { appContextService .getLogger() .info( @@ -131,7 +131,7 @@ export abstract class ActionRunner { }) ); - return { items: [], actionId: this.actionParams.actionId! }; + return { actionId: this.actionParams.actionId! }; } private async createCheckResultTask() { @@ -146,7 +146,7 @@ export abstract class ActionRunner { ); } - private async processBatch(agents: Agent[]): Promise<{ items: BulkActionResult[] }> { + private async processBatch(agents: Agent[]): Promise<{ actionId: string }> { if (this.retryParams.retryCount) { try { const actions = await getAgentActions(this.esClient, this.actionParams!.actionId!); @@ -154,7 +154,7 @@ export abstract class ActionRunner { // skipping batch if there is already an action document present with last agent ids for (const action of actions) { if (action.agents?.[0] === agents[0].id) { - return { items: [] }; + return { actionId: this.actionParams.actionId! }; } } } catch (error) { @@ -165,7 +165,7 @@ export abstract class ActionRunner { return await this.processAgents(agents); } - async processAgentsInBatches(): Promise<{ items: BulkActionResult[] }> { + async processAgentsInBatches(): Promise<{ actionId: string }> { const start = Date.now(); const pitId = this.retryParams.pitId; @@ -188,10 +188,10 @@ export abstract class ActionRunner { appContextService .getLogger() .debug('currentAgents returned 0 hits, returning from bulk action query'); - return { items: [] }; // stop executing if there are no more results + return { actionId: this.actionParams.actionId! }; // stop executing if there are no more results } - let results = await this.processBatch(currentAgents); + await this.processBatch(currentAgents); let allAgentsProcessed = currentAgents.length; while (allAgentsProcessed < res.total) { @@ -205,8 +205,7 @@ export abstract class ActionRunner { .debug('currentAgents returned 0 hits, returning from bulk action query'); break; // stop executing if there are no more results } - const currentResults = await this.processBatch(currentAgents); - results = { items: results.items.concat(currentResults.items) }; + await this.processBatch(currentAgents); allAgentsProcessed += currentAgents.length; if (this.checkTaskId) { // updating check task with latest checkpoint (this.retryParams.searchAfter) @@ -220,6 +219,6 @@ export abstract class ActionRunner { appContextService .getLogger() .info(`processed ${allAgentsProcessed} agents, took ${Date.now() - start}ms`); - return { ...results }; + return { actionId: this.actionParams.actionId! }; } } diff --git a/x-pack/plugins/fleet/server/services/agents/action_status.ts b/x-pack/plugins/fleet/server/services/agents/action_status.ts index 0db6d6db9d86c..8489c25e3fd8d 100644 --- a/x-pack/plugins/fleet/server/services/agents/action_status.ts +++ b/x-pack/plugins/fleet/server/services/agents/action_status.ts @@ -39,6 +39,12 @@ export async function getActionStatuses( terms: { field: 'action_id', size: actions.length || 10 }, aggs: { max_timestamp: { max: { field: '@timestamp' } }, + agent_count: { + cardinality: { + field: 'agent_id', + precision_threshold: 40000, // max value + }, + }, }, }, }, @@ -58,7 +64,7 @@ export async function getActionStatuses( const matchingBucket = (acks?.aggregations?.ack_counts as any)?.buckets?.find( (bucket: any) => bucket.key === action.actionId ); - const nbAgentsAck = matchingBucket?.doc_count ?? 0; + const nbAgentsAck = (matchingBucket?.agent_count as any)?.value ?? 0; const completionTime = (matchingBucket?.max_timestamp as any)?.value_as_string; const nbAgentsActioned = action.nbAgentsActioned || action.nbAgentsActionCreated; const complete = nbAgentsAck >= nbAgentsActioned; diff --git a/x-pack/plugins/fleet/server/services/agents/actions.ts b/x-pack/plugins/fleet/server/services/agents/actions.ts index 20cb2fb94e51d..17c745bfd285f 100644 --- a/x-pack/plugins/fleet/server/services/agents/actions.ts +++ b/x-pack/plugins/fleet/server/services/agents/actions.ts @@ -134,6 +134,7 @@ export async function bulkCreateAgentActionResults( await esClient.bulk({ index: AGENT_ACTIONS_RESULTS_INDEX, body: bulkBody, + refresh: 'wait_for', }); } @@ -242,8 +243,8 @@ export async function cancelAgentAction(esClient: ElasticsearchClient, actionId: hit._source.agents.map((agentId) => ({ agentId, data: { + upgraded_at: null, upgrade_started_at: null, - upgrade_status: 'completed', }, })) ); diff --git a/x-pack/plugins/fleet/server/services/agents/crud.test.ts b/x-pack/plugins/fleet/server/services/agents/crud.test.ts index c6d63b35ac7be..bee3d9fef09fc 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud.test.ts @@ -9,7 +9,7 @@ import type { ElasticsearchClient } from '@kbn/core/server'; import type { Agent } from '../../types'; -import { errorsToResults, getAgentsByKuery, getAgentTags } from './crud'; +import { getAgentsByKuery, getAgentTags } from './crud'; jest.mock('../../../common/services/is_agent_upgradeable', () => ({ isAgentUpgradeable: jest.fn().mockImplementation((agent: Agent) => agent.id.includes('up')), @@ -292,38 +292,4 @@ describe('Agents CRUD test', () => { ]); }); }); - - describe('errorsToResults', () => { - it('should transform errors to results', () => { - const results = errorsToResults([{ id: '1' } as Agent, { id: '2' } as Agent], { - '1': new Error('error'), - }); - expect(results).toEqual([ - { id: '1', success: false, error: new Error('error') }, - { id: '2', success: true }, - ]); - }); - - it('should transform errors to results with skip success', () => { - const results = errorsToResults( - [{ id: '1' } as Agent, { id: '2' } as Agent], - { '1': new Error('error') }, - undefined, - true - ); - expect(results).toEqual([{ id: '1', success: false, error: new Error('error') }]); - }); - - it('should transform errors to results preserve order', () => { - const results = errorsToResults( - [{ id: '1' } as Agent, { id: '2' } as Agent], - { '1': new Error('error') }, - ['2', '1'] - ); - expect(results).toEqual([ - { id: '2', success: true }, - { id: '1', success: false, error: new Error('error') }, - ]); - }); - }); }); diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts index 7b3af0c77e626..55a244664238b 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud.ts @@ -250,34 +250,6 @@ export async function getAgentsByKuery( }; } -export function errorsToResults( - agents: Agent[], - errors: Record, - agentIds?: string[], - skipSuccess?: boolean -): BulkActionResult[] { - if (!skipSuccess) { - const givenOrder = agentIds ? agentIds : agents.map((agent) => agent.id); - return givenOrder.map((agentId) => { - const hasError = agentId in errors; - const result: BulkActionResult = { - id: agentId, - success: !hasError, - }; - if (hasError) { - result.error = errors[agentId]; - } - return result; - }); - } else { - return Object.entries(errors).map(([agentId, error]) => ({ - id: agentId, - success: false, - error, - })); - } -} - export async function getAllAgentsByKuery( esClient: ElasticsearchClient, options: Omit & { @@ -433,6 +405,7 @@ export async function bulkUpdateAgents( { update: { _id: agentId, + retry_on_conflict: 3, }, }, { diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts index a54c2cb56c944..3fb9d2ee1f33b 100644 --- a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts @@ -96,4 +96,29 @@ describe('reassignAgents (plural)', () => { }); expect(calledWithActionResults.body?.[1] as any).toEqual(expectedObject); }); + + it('should report errors from ES agent update call', async () => { + const { soClient, esClient, agentInRegularDoc, regularAgentPolicySO2 } = createClientMock(); + esClient.bulk.mockResponse({ + items: [ + { + update: { + _id: agentInRegularDoc._id, + error: new Error('version conflict'), + }, + }, + ], + } as any); + const idsToReassign = [agentInRegularDoc._id]; + await reassignAgents(soClient, esClient, { agentIds: idsToReassign }, regularAgentPolicySO2.id); + + const calledWithActionResults = esClient.bulk.mock.calls[1][0] as estypes.BulkRequest; + const expectedObject = expect.objectContaining({ + '@timestamp': expect.anything(), + action_id: expect.anything(), + agent_id: agentInRegularDoc._id, + error: 'version conflict', + }); + expect(calledWithActionResults.body?.[1] as any).toEqual(expectedObject); + }); }); diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.ts b/x-pack/plugins/fleet/server/services/agents/reassign.ts index c04a5b3b9ad3e..6a81606697228 100644 --- a/x-pack/plugins/fleet/server/services/agents/reassign.ts +++ b/x-pack/plugins/fleet/server/services/agents/reassign.ts @@ -8,7 +8,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { SavedObjectsClientContract, ElasticsearchClient } from '@kbn/core/server'; import Boom from '@hapi/boom'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { agentPolicyService } from '../agent_policy'; import { AgentReassignmentError, HostedAgentPolicyRestrictionRelatedError } from '../../errors'; @@ -89,7 +89,7 @@ export async function reassignAgents( batchSize?: number; }, newAgentPolicyId: string -): Promise<{ items: BulkActionResult[]; actionId?: string }> { +): Promise<{ actionId: string }> { const newAgentPolicy = await agentPolicyService.get(soClient, newAgentPolicyId); if (!newAgentPolicy) { throw Boom.notFound(`Agent policy not found: ${newAgentPolicyId}`); @@ -141,12 +141,5 @@ export async function reassignAgents( } } - return await reassignBatch( - soClient, - esClient, - { newAgentPolicyId }, - givenAgents, - outgoingErrors, - 'agentIds' in options ? options.agentIds : undefined - ); + return await reassignBatch(soClient, esClient, { newAgentPolicyId }, givenAgents, outgoingErrors); } diff --git a/x-pack/plugins/fleet/server/services/agents/reassign_action_runner.ts b/x-pack/plugins/fleet/server/services/agents/reassign_action_runner.ts index 8724a68d330e7..96405e464b358 100644 --- a/x-pack/plugins/fleet/server/services/agents/reassign_action_runner.ts +++ b/x-pack/plugins/fleet/server/services/agents/reassign_action_runner.ts @@ -7,7 +7,7 @@ import uuid from 'uuid'; import type { SavedObjectsClientContract, ElasticsearchClient } from '@kbn/core/server'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { AgentReassignmentError, HostedAgentPolicyRestrictionRelatedError } from '../../errors'; @@ -15,22 +15,14 @@ import { appContextService } from '../app_context'; import { ActionRunner } from './action_runner'; -import { errorsToResults, bulkUpdateAgents } from './crud'; +import { bulkUpdateAgents } from './crud'; import { bulkCreateAgentActionResults, createAgentAction } from './actions'; import { getHostedPolicies, isHostedAgent } from './hosted_agent'; import { BulkActionTaskType } from './bulk_actions_resolver'; export class ReassignActionRunner extends ActionRunner { - protected async processAgents(agents: Agent[]): Promise<{ items: BulkActionResult[] }> { - return await reassignBatch( - this.soClient, - this.esClient, - this.actionParams! as any, - agents, - {}, - undefined, - true - ); + protected async processAgents(agents: Agent[]): Promise<{ actionId: string }> { + return await reassignBatch(this.soClient, this.esClient, this.actionParams! as any, agents, {}); } protected getTaskType() { @@ -51,10 +43,8 @@ export async function reassignBatch( total?: number; }, givenAgents: Agent[], - outgoingErrors: Record, - agentIds?: string[], - skipSuccess?: boolean -): Promise<{ items: BulkActionResult[] }> { + outgoingErrors: Record +): Promise<{ actionId: string }> { const errors: Record = { ...outgoingErrors }; const hostedPolicies = await getHostedPolicies(soClient, givenAgents); @@ -74,17 +64,15 @@ export async function reassignBatch( return agents; }, []); - const result = { items: errorsToResults(givenAgents, errors, agentIds, skipSuccess) }; - if (agentsToUpdate.length === 0) { // early return if all agents failed validation appContextService .getLogger() .debug('No agents to update, skipping agent update and action creation'); - return result; + throw new AgentReassignmentError('No agents to reassign, already assigned or hosted agents'); } - await bulkUpdateAgents( + const res = await bulkUpdateAgents( esClient, agentsToUpdate.map((agent) => ({ agentId: agent.id, @@ -95,6 +83,12 @@ export async function reassignBatch( })) ); + res.items + .filter((item) => !item.success) + .forEach((item) => { + errors[item.id] = item.error!; + }); + const actionId = options.actionId ?? uuid(); const errorCount = Object.keys(errors).length; const total = options.total ?? agentsToUpdate.length + errorCount; @@ -129,5 +123,5 @@ export async function reassignBatch( ); } - return result; + return { actionId }; } diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts index d96e8b89d2fc1..79612b0bcbf06 100644 --- a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts @@ -223,21 +223,7 @@ describe('unenrollAgents (plural)', () => { agentIds: idsToUnenroll, revoke: true, }); - - expect(unenrolledResponse.items).toMatchObject([ - { - id: 'agent-in-regular-policy', - success: true, - }, - { - id: 'agent-in-hosted-policy', - success: false, - }, - { - id: 'agent-in-regular-policy2', - success: true, - }, - ]); + expect(unenrolledResponse.actionId).toBeDefined(); // calls ES update with correct values const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id]; @@ -301,20 +287,7 @@ describe('unenrollAgents (plural)', () => { force: true, }); - expect(unenrolledResponse.items).toMatchObject([ - { - id: 'agent-in-regular-policy', - success: true, - }, - { - id: 'agent-in-hosted-policy', - success: true, - }, - { - id: 'agent-in-regular-policy2', - success: true, - }, - ]); + expect(unenrolledResponse.actionId).toBeDefined(); // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[1][0]; diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.ts index f7c49f3efcf1c..078b9ce3aef37 100644 --- a/x-pack/plugins/fleet/server/services/agents/unenroll.ts +++ b/x-pack/plugins/fleet/server/services/agents/unenroll.ts @@ -9,7 +9,7 @@ import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/ import uuid from 'uuid'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { HostedAgentPolicyRestrictionRelatedError } from '../../errors'; import { SO_SEARCH_LIMIT } from '../../constants'; @@ -74,7 +74,7 @@ export async function unenrollAgents( revoke?: boolean; batchSize?: number; } -): Promise<{ items: BulkActionResult[]; actionId?: string }> { +): Promise<{ actionId: string }> { if ('agentIds' in options) { const givenAgents = await getAgents(esClient, options); return await unenrollBatch(soClient, esClient, givenAgents, options); diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll_action_runner.ts b/x-pack/plugins/fleet/server/services/agents/unenroll_action_runner.ts index f9ba2e4be44a1..dd5b4e023c2a3 100644 --- a/x-pack/plugins/fleet/server/services/agents/unenroll_action_runner.ts +++ b/x-pack/plugins/fleet/server/services/agents/unenroll_action_runner.ts @@ -11,7 +11,7 @@ import { intersection } from 'lodash'; import { AGENT_ACTIONS_RESULTS_INDEX } from '../../../common'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { FleetError, HostedAgentPolicyRestrictionRelatedError } from '../../errors'; @@ -21,7 +21,7 @@ import { appContextService } from '../app_context'; import { ActionRunner } from './action_runner'; -import { errorsToResults, bulkUpdateAgents } from './crud'; +import { bulkUpdateAgents } from './crud'; import { bulkCreateAgentActionResults, createAgentAction, @@ -31,8 +31,8 @@ import { getHostedPolicies, isHostedAgent } from './hosted_agent'; import { BulkActionTaskType } from './bulk_actions_resolver'; export class UnenrollActionRunner extends ActionRunner { - protected async processAgents(agents: Agent[]): Promise<{ items: BulkActionResult[] }> { - return await unenrollBatch(this.soClient, this.esClient, agents, this.actionParams!, true); + protected async processAgents(agents: Agent[]): Promise<{ actionId: string }> { + return await unenrollBatch(this.soClient, this.esClient, agents, this.actionParams!); } protected getTaskType() { @@ -60,9 +60,8 @@ export async function unenrollBatch( revoke?: boolean; actionId?: string; total?: number; - }, - skipSuccess?: boolean -): Promise<{ items: BulkActionResult[] }> { + } +): Promise<{ actionId: string }> { const hostedPolicies = await getHostedPolicies(soClient, givenAgents); const outgoingErrors: Record = {}; @@ -134,7 +133,7 @@ export async function unenrollBatch( ); return { - items: errorsToResults(givenAgents, outgoingErrors, undefined, skipSuccess), + actionId, }; } diff --git a/x-pack/plugins/fleet/server/services/agents/update_agent_tags.ts b/x-pack/plugins/fleet/server/services/agents/update_agent_tags.ts index 4496e16cbc476..a8c5496a6b028 100644 --- a/x-pack/plugins/fleet/server/services/agents/update_agent_tags.ts +++ b/x-pack/plugins/fleet/server/services/agents/update_agent_tags.ts @@ -8,7 +8,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { AgentReassignmentError } from '../../errors'; import { SO_SEARCH_LIMIT } from '../../constants'; @@ -28,7 +28,7 @@ export async function updateAgentTags( options: ({ agents: Agent[] } | GetAgentsOptions) & { batchSize?: number }, tagsToAdd: string[], tagsToRemove: string[] -): Promise<{ items: BulkActionResult[]; actionId?: string }> { +): Promise<{ actionId: string }> { const outgoingErrors: Record = {}; let givenAgents: Agent[] = []; @@ -69,12 +69,8 @@ export async function updateAgentTags( } } - return await updateTagsBatch( - soClient, - esClient, - givenAgents, - outgoingErrors, - { tagsToAdd, tagsToRemove }, - 'agentIds' in options ? options.agentIds : undefined - ); + return await updateTagsBatch(soClient, esClient, givenAgents, outgoingErrors, { + tagsToAdd, + tagsToRemove, + }); } diff --git a/x-pack/plugins/fleet/server/services/agents/update_agent_tags_action_runner.ts b/x-pack/plugins/fleet/server/services/agents/update_agent_tags_action_runner.ts index 807f2ab1cf073..48f7b455d36b7 100644 --- a/x-pack/plugins/fleet/server/services/agents/update_agent_tags_action_runner.ts +++ b/x-pack/plugins/fleet/server/services/agents/update_agent_tags_action_runner.ts @@ -9,19 +9,19 @@ import type { SavedObjectsClientContract, ElasticsearchClient } from '@kbn/core/ import uuid from 'uuid'; import { difference, uniq } from 'lodash'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { appContextService } from '../app_context'; import { ActionRunner } from './action_runner'; -import { errorsToResults, bulkUpdateAgents } from './crud'; +import { bulkUpdateAgents } from './crud'; import { BulkActionTaskType } from './bulk_actions_resolver'; import { filterHostedPolicies } from './filter_hosted_agents'; import { bulkCreateAgentActionResults, createAgentAction } from './actions'; export class UpdateAgentTagsActionRunner extends ActionRunner { - protected async processAgents(agents: Agent[]): Promise<{ items: BulkActionResult[] }> { + protected async processAgents(agents: Agent[]): Promise<{ actionId: string }> { return await updateTagsBatch( this.soClient, this.esClient, @@ -32,9 +32,7 @@ export class UpdateAgentTagsActionRunner extends ActionRunner { tagsToRemove: this.actionParams?.tagsToRemove, actionId: this.actionParams.actionId, total: this.actionParams.total, - }, - undefined, - true + } ); } @@ -57,10 +55,8 @@ export async function updateTagsBatch( tagsToRemove: string[]; actionId?: string; total?: number; - }, - agentIds?: string[], - skipSuccess?: boolean -): Promise<{ items: BulkActionResult[] }> { + } +): Promise<{ actionId: string }> { const errors: Record = { ...outgoingErrors }; const filteredAgents = await filterHostedPolicies( @@ -135,5 +131,5 @@ export async function updateTagsBatch( ); } - return { items: errorsToResults(filteredAgents, errors, agentIds, skipSuccess) }; + return { actionId }; } diff --git a/x-pack/plugins/fleet/server/services/agents/upgrade.test.ts b/x-pack/plugins/fleet/server/services/agents/upgrade.test.ts index 9692f05822879..db880f56ef474 100644 --- a/x-pack/plugins/fleet/server/services/agents/upgrade.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/upgrade.test.ts @@ -38,7 +38,7 @@ describe('sendUpgradeAgentsActions (plural)', () => { expect(ids).toEqual(idsToAction); for (const doc of docs!) { expect(doc).toHaveProperty('upgrade_started_at'); - expect(doc.upgrade_status).toEqual('started'); + expect(doc.upgraded_at).toEqual(null); } }); it('cannot upgrade from a hosted agent policy by default', async () => { @@ -60,7 +60,7 @@ describe('sendUpgradeAgentsActions (plural)', () => { expect(ids).toEqual(onlyRegular); for (const doc of docs!) { expect(doc).toHaveProperty('upgrade_started_at'); - expect(doc.upgrade_status).toEqual('started'); + expect(doc.upgraded_at).toEqual(null); } // hosted policy is updated in action results with error @@ -98,7 +98,7 @@ describe('sendUpgradeAgentsActions (plural)', () => { expect(ids).toEqual(idsToAction); for (const doc of docs!) { expect(doc).toHaveProperty('upgrade_started_at'); - expect(doc.upgrade_status).toEqual('started'); + expect(doc.upgraded_at).toEqual(null); } }); }); diff --git a/x-pack/plugins/fleet/server/services/agents/upgrade.ts b/x-pack/plugins/fleet/server/services/agents/upgrade.ts index b6c50a3b5dc3c..605aa896de59a 100644 --- a/x-pack/plugins/fleet/server/services/agents/upgrade.ts +++ b/x-pack/plugins/fleet/server/services/agents/upgrade.ts @@ -7,7 +7,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { AgentReassignmentError, HostedAgentPolicyRestrictionRelatedError } from '../../errors'; import { SO_SEARCH_LIMIT } from '../../constants'; @@ -57,8 +57,8 @@ export async function sendUpgradeAgentAction({ type: 'UPGRADE', }); await updateAgent(esClient, agentId, { + upgraded_at: null, upgrade_started_at: now, - upgrade_status: 'started', }); } @@ -73,7 +73,7 @@ export async function sendUpgradeAgentsActions( startTime?: string; batchSize?: number; } -): Promise<{ items: BulkActionResult[]; actionId?: string }> { +): Promise<{ actionId: string }> { // Full set of agents const outgoingErrors: Record = {}; let givenAgents: Agent[] = []; diff --git a/x-pack/plugins/fleet/server/services/agents/upgrade_action_runner.ts b/x-pack/plugins/fleet/server/services/agents/upgrade_action_runner.ts index 28c1ec3d26007..a34f189871a39 100644 --- a/x-pack/plugins/fleet/server/services/agents/upgrade_action_runner.ts +++ b/x-pack/plugins/fleet/server/services/agents/upgrade_action_runner.ts @@ -12,7 +12,7 @@ import uuid from 'uuid'; import { isAgentUpgradeable } from '../../../common/services'; -import type { Agent, BulkActionResult } from '../../types'; +import type { Agent } from '../../types'; import { HostedAgentPolicyRestrictionRelatedError, FleetError } from '../../errors'; @@ -21,21 +21,14 @@ import { appContextService } from '../app_context'; import { ActionRunner } from './action_runner'; import type { GetAgentsOptions } from './crud'; -import { errorsToResults, bulkUpdateAgents } from './crud'; +import { bulkUpdateAgents } from './crud'; import { bulkCreateAgentActionResults, createAgentAction } from './actions'; import { getHostedPolicies, isHostedAgent } from './hosted_agent'; import { BulkActionTaskType } from './bulk_actions_resolver'; export class UpgradeActionRunner extends ActionRunner { - protected async processAgents(agents: Agent[]): Promise<{ items: BulkActionResult[] }> { - return await upgradeBatch( - this.soClient, - this.esClient, - agents, - {}, - this.actionParams! as any, - true - ); + protected async processAgents(agents: Agent[]): Promise<{ actionId: string }> { + return await upgradeBatch(this.soClient, this.esClient, agents, {}, this.actionParams! as any); } protected getTaskType() { @@ -60,9 +53,8 @@ export async function upgradeBatch( upgradeDurationSeconds?: number; startTime?: string; total?: number; - }, - skipSuccess?: boolean -): Promise<{ items: BulkActionResult[] }> { + } +): Promise<{ actionId: string }> { const errors: Record = { ...outgoingErrors }; const hostedPolicies = await getHostedPolicies(soClient, givenAgents); @@ -154,19 +146,14 @@ export async function upgradeBatch( agentsToUpdate.map((agent) => ({ agentId: agent.id, data: { + upgraded_at: null, upgrade_started_at: now, - upgrade_status: 'started', }, })) ); return { - items: errorsToResults( - givenAgents, - errors, - 'agentIds' in options ? options.agentIds : undefined, - skipSuccess - ), + actionId, }; } diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/mappings.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/mappings.test.ts new file mode 100644 index 0000000000000..6925da569bae4 --- /dev/null +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/mappings.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { keyword } from './mappings'; + +describe('mappings', () => { + describe('keyword', () => { + it('should set ignore_above:1024 by default for indexed field', () => { + const mappings = keyword({ + name: 'test', + type: 'keyword', + }); + + expect(mappings).toEqual({ + ignore_above: 1024, + type: 'keyword', + }); + }); + + it('should not set ignore_above for non indexed field', () => { + const mappings = keyword({ + name: 'test', + type: 'keyword', + index: false, + }); + + expect(mappings).toEqual({ + type: 'keyword', + index: false, + }); + }); + + it('should not set ignore_above field with doc_values:false', () => { + const mappings = keyword({ + name: 'test', + type: 'keyword', + doc_values: false, + }); + + expect(mappings).toEqual({ + type: 'keyword', + doc_values: false, + }); + }); + }); +}); diff --git a/x-pack/plugins/fleet/server/services/epm/packages/bundled_packages.ts b/x-pack/plugins/fleet/server/services/epm/packages/bundled_packages.ts index e18b64d8daae8..ede8a25ca254f 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/bundled_packages.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/bundled_packages.ts @@ -22,6 +22,14 @@ export async function getBundledPackages(): Promise { throw new FleetError('xpack.fleet.developer.bundledPackageLocation is not configured'); } + // If the bundled package directory is missing, we log a warning during setup, + // so we can safely ignore this case here and just retun and empty array + try { + await fs.stat(bundledPackageLocation); + } catch (error) { + return []; + } + try { const dirContents = await fs.readdir(bundledPackageLocation); const zipFiles = dirContents.filter((file) => file.endsWith('.zip')); diff --git a/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts b/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts index 6504b6548f078..bf5fe89574b8a 100644 --- a/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts @@ -35,6 +35,7 @@ jest.mock('../..', () => ({ getKibanaBranch: () => 'main', getKibanaVersion: () => '99.0.0', getConfig: () => ({}), + getIsProductionMode: () => false, }, })); diff --git a/x-pack/plugins/fleet/server/services/epm/registry/registry_url.ts b/x-pack/plugins/fleet/server/services/epm/registry/registry_url.ts index 407a61ad7a912..31bb776ee1d69 100644 --- a/x-pack/plugins/fleet/server/services/epm/registry/registry_url.ts +++ b/x-pack/plugins/fleet/server/services/epm/registry/registry_url.ts @@ -21,7 +21,8 @@ const SNAPSHOT_REGISTRY_URL_CDN = 'https://epr-snapshot.elastic.co'; const getDefaultRegistryUrl = (): string => { const branch = appContextService.getKibanaBranch(); - if (branch === 'main') { + const isProduction = appContextService.getIsProductionMode(); + if (!isProduction || branch === 'main') { return SNAPSHOT_REGISTRY_URL_CDN; } else if (appContextService.getKibanaVersion().includes('-SNAPSHOT')) { return STAGING_REGISTRY_URL_CDN; diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index 9bbeb8fd67232..10a076d734f89 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -666,6 +666,158 @@ describe('Package policy service', () => { ).rejects.toThrow('Saved object [abc/123] conflict'); }); + it('should fail to update if the name already exists on another policy', async () => { + const savedObjectsClient = savedObjectsClientMock.create(); + savedObjectsClient.find.mockResolvedValue({ + total: 1, + per_page: 1, + page: 1, + saved_objects: [ + { + id: 'existing-package-policy', + type: 'ingest-package-policies', + score: 1, + references: [], + version: '1.0.0', + attributes: { + name: 'endpoint-1', + description: '', + namespace: 'default', + enabled: true, + policy_id: 'policy-id-1', + package: { + name: 'endpoint', + title: 'Elastic Endpoint', + version: '0.9.0', + }, + inputs: [], + }, + }, + ], + }); + savedObjectsClient.get.mockResolvedValue({ + id: 'the-package-policy-id', + type: 'abcd', + references: [], + version: 'test', + attributes: {}, + }); + savedObjectsClient.update.mockImplementation( + async ( + type: string, + id: string, + attrs: any + ): Promise> => { + savedObjectsClient.get.mockResolvedValue({ + id: 'the-package-policy-id', + type, + references: [], + version: 'test', + attributes: attrs, + }); + return attrs; + } + ); + const elasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + await expect( + packagePolicyService.update( + savedObjectsClient, + elasticsearchClient, + 'the-package-policy-id', + { + name: 'endpoint-1', + description: '', + namespace: 'default', + enabled: true, + policy_id: '93c46720-c217-11ea-9906-b5b8a21b268e', + package: { + name: 'endpoint', + title: 'Elastic Endpoint', + version: '0.9.0', + }, + inputs: [], + } + ) + ).rejects.toThrow( + 'An integration policy with the name endpoint-1 already exists. Please rename it or choose a different name.' + ); + }); + + it('should not fail to update if skipUniqueNameVerification when the name already exists on another policy', async () => { + const savedObjectsClient = savedObjectsClientMock.create(); + savedObjectsClient.find.mockResolvedValue({ + total: 1, + per_page: 1, + page: 1, + saved_objects: [ + { + id: 'existing-package-policy', + type: 'ingest-package-policies', + score: 1, + references: [], + version: '1.0.0', + attributes: { + name: 'endpoint-1', + description: '', + namespace: 'default', + enabled: true, + policy_id: 'policy-id-1', + package: { + name: 'endpoint', + title: 'Elastic Endpoint', + version: '0.9.0', + }, + inputs: [], + }, + }, + ], + }); + savedObjectsClient.get.mockResolvedValue({ + id: 'the-package-policy-id', + type: 'abcd', + references: [], + version: 'test', + attributes: {}, + }); + savedObjectsClient.update.mockImplementation( + async ( + type: string, + id: string, + attrs: any + ): Promise> => { + savedObjectsClient.get.mockResolvedValue({ + id: 'the-package-policy-id', + type, + references: [], + version: 'test', + attributes: attrs, + }); + return attrs; + } + ); + const elasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + const result = await packagePolicyService.update( + savedObjectsClient, + elasticsearchClient, + 'the-package-policy-id', + { + name: 'endpoint-1', + description: '', + namespace: 'default', + enabled: true, + policy_id: '93c46720-c217-11ea-9906-b5b8a21b268e', + package: { + name: 'endpoint', + title: 'Elastic Endpoint', + version: '0.9.0', + }, + inputs: [], + }, + { skipUniqueNameVerification: true } + ); + expect(result.name).toEqual('endpoint-1'); + }); + it('should throw if the user try to update input vars that are frozen', async () => { const savedObjectsClient = savedObjectsClientMock.create(); const mockPackagePolicy = createPackagePolicyMock(); diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 70f65bb9b7987..f52316dd4452b 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -469,7 +469,7 @@ class PackagePolicyClientImpl implements PackagePolicyClient { esClient: ElasticsearchClient, id: string, packagePolicyUpdate: UpdatePackagePolicy, - options?: { user?: AuthenticatedUser; force?: boolean }, + options?: { user?: AuthenticatedUser; force?: boolean; skipUniqueNameVerification?: boolean }, currentVersion?: string ): Promise { const packagePolicy = { ...packagePolicyUpdate, name: packagePolicyUpdate.name.trim() }; @@ -479,22 +479,22 @@ class PackagePolicyClientImpl implements PackagePolicyClient { if (packagePolicyUpdate.is_managed && !options?.force) { throw new PackagePolicyRestrictionRelatedError(`Cannot update package policy ${id}`); } - if (!oldPackagePolicy) { throw new Error('Package policy not found'); } - // Check that the name does not exist already but exclude the current package policy - const existingPoliciesWithName = await this.list(soClient, { - perPage: SO_SEARCH_LIMIT, - kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name:"${packagePolicy.name}"`, - }); - const filtered = (existingPoliciesWithName?.items || []).filter((p) => p.id !== id); - - if (filtered.length > 0) { - throw new FleetError( - `An integration policy with the name ${packagePolicy.name} already exists. Please rename it or choose a different name.` - ); + if (!options?.skipUniqueNameVerification) { + // Check that the name does not exist already but exclude the current package policy + const existingPoliciesWithName = await this.list(soClient, { + perPage: SO_SEARCH_LIMIT, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name:"${packagePolicy.name}"`, + }); + const filtered = (existingPoliciesWithName?.items || []).filter((p) => p.id !== id); + if (filtered.length > 0) { + throw new FleetError( + `An integration policy with the name ${packagePolicy.name} already exists. Please rename it or choose a different name.` + ); + } } let inputs = restOfPackagePolicy.inputs.map((input) => @@ -801,7 +801,6 @@ class PackagePolicyClientImpl implements PackagePolicyClient { savedObjectsClient: soClient, pkgName: packagePolicy!.package!.name, pkgVersion: pkgVersion ?? '', - skipArchive: true, }); } @@ -930,12 +929,17 @@ class PackagePolicyClientImpl implements PackagePolicyClient { ); updatePackagePolicy.elasticsearch = packageInfo.elasticsearch; + const updateOptions = { + skipUniqueNameVerification: true, + ...options, + }; + await this.update( soClient, esClient, id, updatePackagePolicy, - options, + updateOptions, packagePolicy.package!.version ); diff --git a/x-pack/plugins/fleet/server/services/package_policy_service.ts b/x-pack/plugins/fleet/server/services/package_policy_service.ts index 4dd36a8c4fdf4..0a16a01c3dc4c 100644 --- a/x-pack/plugins/fleet/server/services/package_policy_service.ts +++ b/x-pack/plugins/fleet/server/services/package_policy_service.ts @@ -97,7 +97,7 @@ export interface PackagePolicyClient { esClient: ElasticsearchClient, id: string, packagePolicyUpdate: UpdatePackagePolicy, - options?: { user?: AuthenticatedUser; force?: boolean }, + options?: { user?: AuthenticatedUser; force?: boolean; skipUniqueNameVerification?: boolean }, currentVersion?: string ): Promise; diff --git a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.test.ts b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.test.ts index a8eaa39d427df..e6fa2e008e4bb 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.test.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.test.ts @@ -112,6 +112,33 @@ describe('output preconfiguration', () => { expect(spyAgentPolicyServicBumpAllAgentPoliciesForOutput).not.toBeCalled(); }); + it('should create a preconfigured output with ca_trusted_fingerprint that does not exists', async () => { + const soClient = savedObjectsClientMock.create(); + const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + await createOrUpdatePreconfiguredOutputs(soClient, esClient, [ + { + id: 'non-existing-output-1', + name: 'Output 1', + type: 'elasticsearch', + is_default: false, + is_default_monitoring: false, + hosts: ['http://test.fr'], + ca_trusted_fingerprint: 'testfingerprint', + }, + ]); + + expect(mockedOutputService.create).toBeCalled(); + expect(mockedOutputService.create).toBeCalledWith( + expect.anything(), + expect.objectContaining({ + ca_trusted_fingerprint: 'testfingerprint', + }), + expect.anything() + ); + expect(mockedOutputService.update).not.toBeCalled(); + expect(spyAgentPolicyServicBumpAllAgentPoliciesForOutput).not.toBeCalled(); + }); + it('should create preconfigured logstash output that does not exist', async () => { const soClient = savedObjectsClientMock.create(); const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; diff --git a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts index a61d8316dcc5f..d7f43ce181a42 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts @@ -78,7 +78,7 @@ export async function createOrUpdatePreconfiguredOutputs( config_yaml: configYaml ?? null, // Set value to null to update these fields on update ca_sha256: outputData.ca_sha256 ?? null, - ca_trusted_fingerprint: outputData.ca_sha256 ?? null, + ca_trusted_fingerprint: outputData.ca_trusted_fingerprint ?? null, ssl: outputData.ssl ?? null, }; diff --git a/x-pack/plugins/fleet/server/services/setup.ts b/x-pack/plugins/fleet/server/services/setup.ts index e9b26e50735b9..f536125e054a2 100644 --- a/x-pack/plugins/fleet/server/services/setup.ts +++ b/x-pack/plugins/fleet/server/services/setup.ts @@ -5,6 +5,8 @@ * 2.0. */ +import fs from 'fs/promises'; + import { compact } from 'lodash'; import pMap from 'p-map'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; @@ -31,7 +33,7 @@ import { outputService } from './output'; import { downloadSourceService } from './download_source'; import { generateEnrollmentAPIKey, hasEnrollementAPIKeysForPolicy } from './api_keys'; -import { settingsService } from '.'; +import { getRegistryUrl, settingsService } from '.'; import { awaitIfPending } from './setup_utils'; import { ensureFleetFinalPipelineIsInstalled } from './epm/elasticsearch/ingest_pipeline/install'; import { ensureDefaultComponentTemplates } from './epm/elasticsearch/template/install'; @@ -64,6 +66,8 @@ async function createSetupSideEffects( const logger = appContextService.getLogger(); logger.info('Beginning fleet setup'); + await ensureFleetDirectories(); + const { agentPolicies: policiesOrUndefined, packages: packagesOrUndefined } = appContextService.getConfig() ?? {}; @@ -266,3 +270,27 @@ export function formatNonFatalErrors( } }); } + +/** + * Confirm existence of various directories used by Fleet and warn if they don't exist + */ +export async function ensureFleetDirectories() { + const logger = appContextService.getLogger(); + const config = appContextService.getConfig(); + + const bundledPackageLocation = config?.developer?.bundledPackageLocation; + const registryUrl = getRegistryUrl(); + + if (!bundledPackageLocation) { + logger.warn('xpack.fleet.developer.bundledPackageLocation is not configured'); + return; + } + + try { + await fs.stat(bundledPackageLocation); + } catch (error) { + logger.warn( + `Bundled package directory ${bundledPackageLocation} does not exist. All packages will be sourced from ${registryUrl}.` + ); + } +} diff --git a/x-pack/plugins/graph/kibana.json b/x-pack/plugins/graph/kibana.json index 641e595893c0a..6db4ca194d7d1 100644 --- a/x-pack/plugins/graph/kibana.json +++ b/x-pack/plugins/graph/kibana.json @@ -9,7 +9,8 @@ "data", "navigation", "savedObjects", - "unifiedSearch" + "unifiedSearch", + "inspector" ], "optionalPlugins": [ "home", diff --git a/x-pack/plugins/graph/public/application.tsx b/x-pack/plugins/graph/public/application.tsx index 1976b12621f4f..bbb14a96ac5eb 100644 --- a/x-pack/plugins/graph/public/application.tsx +++ b/x-pack/plugins/graph/public/application.tsx @@ -27,6 +27,7 @@ import { LicensingPluginStart } from '@kbn/licensing-plugin/public'; import { NavigationPublicPluginStart as NavigationStart } from '@kbn/navigation-plugin/public'; import { Storage } from '@kbn/kibana-utils-plugin/public'; import { FormattedRelative } from '@kbn/i18n-react'; +import { Start as InspectorPublicPluginStart } from '@kbn/inspector-plugin/public'; import { TableListViewKibanaProvider } from '@kbn/content-management-table-list'; import './index.scss'; @@ -70,6 +71,7 @@ export interface GraphDependencies { uiSettings: IUiSettingsClient; history: ScopedHistory; spaces?: SpacesApi; + inspect: InspectorPublicPluginStart; } export type GraphServices = Omit; diff --git a/x-pack/plugins/graph/public/apps/workspace_route.tsx b/x-pack/plugins/graph/public/apps/workspace_route.tsx index 051c0fa66ab89..9b1fde2e7cb25 100644 --- a/x-pack/plugins/graph/public/apps/workspace_route.tsx +++ b/x-pack/plugins/graph/public/apps/workspace_route.tsx @@ -43,6 +43,7 @@ export const WorkspaceRoute = ({ setHeaderActionMenu, spaces, indexPatterns: getIndexPatternProvider, + inspect, }, }: WorkspaceRouteProps) => { /** @@ -64,11 +65,6 @@ export const WorkspaceRoute = ({ [getIndexPatternProvider.get] ); - const { loading, callNodeProxy, callSearchNodeProxy, handleSearchQueryError } = useGraphLoader({ - toastNotifications, - coreStart, - }); - const services = useMemo( () => ({ appName: 'graph', @@ -80,6 +76,12 @@ export const WorkspaceRoute = ({ [coreStart, data, storage, unifiedSearch] ); + const { loading, requestAdapter, callNodeProxy, callSearchNodeProxy, handleSearchQueryError } = + useGraphLoader({ + toastNotifications, + coreStart, + }); + const [store] = useState(() => createGraphStore({ basePath: getBasePath(), @@ -150,6 +152,8 @@ export const WorkspaceRoute = ({ overlays={overlays} savedWorkspace={savedWorkspace} indexPatternProvider={indexPatternProvider} + inspect={inspect} + requestAdapter={requestAdapter} /> diff --git a/x-pack/plugins/graph/public/components/inspect_panel.tsx b/x-pack/plugins/graph/public/components/inspect_panel.tsx deleted file mode 100644 index e6197bac16ba7..0000000000000 --- a/x-pack/plugins/graph/public/components/inspect_panel.tsx +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React, { useMemo, useState } from 'react'; -import { EuiTab, EuiTabs, EuiText } from '@elastic/eui'; -import { monaco, XJsonLang } from '@kbn/monaco'; -import { FormattedMessage } from '@kbn/i18n-react'; -import { CodeEditor } from '@kbn/kibana-react-plugin/public'; -import type { DataView } from '@kbn/data-views-plugin/public'; - -interface InspectPanelProps { - showInspect: boolean; - indexPattern?: DataView; - lastRequest?: string; - lastResponse?: string; -} - -const CODE_EDITOR_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = { - automaticLayout: true, - fontSize: 12, - lineNumbers: 'on', - minimap: { - enabled: false, - }, - overviewRulerBorder: false, - readOnly: true, - scrollbar: { - alwaysConsumeMouseWheel: false, - }, - scrollBeyondLastLine: false, - wordWrap: 'on', - wrappingIndent: 'indent', -}; - -const dummyCallback = () => {}; - -export const InspectPanel = ({ - showInspect, - lastRequest, - lastResponse, - indexPattern, -}: InspectPanelProps) => { - const [selectedTabId, setSelectedTabId] = useState('request'); - - const onRequestClick = () => setSelectedTabId('request'); - const onResponseClick = () => setSelectedTabId('response'); - - const editorContent = useMemo( - () => (selectedTabId === 'request' ? lastRequest : lastResponse), - [lastRequest, lastResponse, selectedTabId] - ); - - if (showInspect) { - return ( -
-
-
- -
- -
- - http://host:port/{indexPattern?.id}/_graph/explore - - - - - - - - - - -
-
-
- ); - } - - return null; -}; diff --git a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx index 57e69d0912a7f..4509a003e839d 100644 --- a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx @@ -261,7 +261,15 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { defaultMessage: 'Toolbar icon', })} > -
+
{urlTemplateIconChoices.map((icon) => ( { aliasTargetId: '', } as SharingSavedObjectProps, spaces: spacesPluginMock.createStartContract(), + inspect: { open: jest.fn() } as unknown as InspectorStart, + requestAdapter: { + start: () => ({ + stats: jest.fn(), + json: jest.fn(), + }), + reset: jest.fn(), + } as unknown as RequestAdapter, workspace: {} as unknown as Workspace, }; it('should display conflict notification if outcome is conflict', () => { diff --git a/x-pack/plugins/graph/public/components/workspace_layout/workspace_layout.tsx b/x-pack/plugins/graph/public/components/workspace_layout/workspace_layout.tsx index 3eede479bd801..5de95636a61dd 100644 --- a/x-pack/plugins/graph/public/components/workspace_layout/workspace_layout.tsx +++ b/x-pack/plugins/graph/public/components/workspace_layout/workspace_layout.tsx @@ -11,6 +11,7 @@ import { EuiSpacer } from '@elastic/eui'; import { connect } from 'react-redux'; import { useLocation } from 'react-router-dom'; import type { DataView } from '@kbn/data-views-plugin/public'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; import { SearchBar } from '../search_bar'; import { GraphState, @@ -20,7 +21,6 @@ import { import { FieldManager } from '../field_manager'; import { ControlType, IndexPatternProvider, TermIntersect, WorkspaceNode } from '../../types'; import { WorkspaceTopNavMenu } from './workspace_top_nav_menu'; -import { InspectPanel } from '../inspect_panel'; import { GuidancePanel } from '../guidance_panel'; import { GraphTitle } from '../graph_title'; import { GraphWorkspaceSavedObject, Workspace } from '../../types'; @@ -49,6 +49,7 @@ type WorkspaceLayoutProps = Pick< | 'canEditDrillDownUrls' | 'overlays' | 'spaces' + | 'inspect' > & { renderCounter: number; workspace?: Workspace; @@ -56,6 +57,7 @@ type WorkspaceLayoutProps = Pick< savedWorkspace: GraphWorkspaceSavedObject; indexPatternProvider: IndexPatternProvider; sharingSavedObjectProps?: SharingSavedObjectProps; + requestAdapter: RequestAdapter; }; interface WorkspaceLayoutStateProps { @@ -80,9 +82,10 @@ export const WorkspaceLayoutComponent = ({ setHeaderActionMenu, sharingSavedObjectProps, spaces, + inspect, + requestAdapter, }: WorkspaceLayoutProps & WorkspaceLayoutStateProps) => { const [currentIndexPattern, setCurrentIndexPattern] = useState(); - const [showInspect, setShowInspect] = useState(false); const [pickerOpen, setPickerOpen] = useState(false); const [mergeCandidates, setMergeCandidates] = useState([]); const [control, setControl] = useState('none'); @@ -188,20 +191,15 @@ export const WorkspaceLayoutComponent = ({ graphSavePolicy={graphSavePolicy} navigation={navigation} capabilities={capabilities} + inspect={inspect} + requestAdapter={requestAdapter} coreStart={coreStart} canEditDrillDownUrls={canEditDrillDownUrls} - setShowInspect={setShowInspect} confirmWipeWorkspace={confirmWipeWorkspace} setHeaderActionMenu={setHeaderActionMenu} isInitialized={isInitialized} /> - {isInitialized && }
>; confirmWipeWorkspace: ( onConfirm: () => void, text?: string, @@ -30,9 +31,11 @@ interface WorkspaceTopNavMenuProps { graphSavePolicy: GraphSavePolicy; navigation: NavigationStart; capabilities: Capabilities; + inspect: InspectorPublicPluginStart; coreStart: CoreStart; canEditDrillDownUrls: boolean; isInitialized: boolean; + requestAdapter: RequestAdapter; } export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { @@ -40,6 +43,12 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { const location = useLocation(); const history = useHistory(); const allSavingDisabled = props.graphSavePolicy === 'none'; + const isInspectDisabled = !props.workspace?.lastRequest || !props.workspace.lastRequest; + + const { onOpenInspector } = useInspector({ + inspect: props.inspect, + requestAdapter: props.requestAdapter, + }); // ===== Menubar configuration ========= const { TopNavMenu } = props.navigation.ui; @@ -107,7 +116,7 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { topNavMenu.push({ key: 'inspect', disableButton() { - return props.workspace === null; + return isInspectDisabled; }, label: i18n.translate('xpack.graph.topNavMenu.inspectLabel', { defaultMessage: 'Inspect', @@ -116,7 +125,14 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { defaultMessage: 'Inspect', }), run: () => { - props.setShowInspect((prevShowInspect) => !prevShowInspect); + onOpenInspector(); + }, + tooltip: () => { + if (isInspectDisabled) { + return i18n.translate('xpack.graph.topNavMenu.inspectButton.disabledTooltip', { + defaultMessage: 'Perform a search or expand a node to enable Inspect', + }); + } }, testId: 'graphInspectButton', }); @@ -162,6 +178,9 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { ownFocus: true, className: 'gphSettingsFlyout', maxWidth: 520, + 'aria-label': i18n.translate('xpack.graph.settings.ariaLabel', { + defaultMessage: 'Settings', + }), } ); }, diff --git a/x-pack/plugins/graph/public/helpers/use_graph_loader.ts b/x-pack/plugins/graph/public/helpers/use_graph_loader.ts index 5b4f3bbbf1e47..0d50039ab9797 100644 --- a/x-pack/plugins/graph/public/helpers/use_graph_loader.ts +++ b/x-pack/plugins/graph/public/helpers/use_graph_loader.ts @@ -5,10 +5,12 @@ * 2.0. */ -import { useCallback, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import type { CoreStart, ToastsStart } from '@kbn/core/public'; import type { IHttpFetchError, ResponseErrorBody } from '@kbn/core-http-browser'; import { i18n } from '@kbn/i18n'; +import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { RequestAdapter } from '@kbn/inspector-plugin/public'; import type { ExploreRequest, GraphExploreCallback, @@ -24,6 +26,7 @@ interface UseGraphLoaderProps { export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoaderProps) => { const [loading, setLoading] = useState(false); + const requestAdapter = useMemo(() => new RequestAdapter(), []); const handleHttpError = useCallback( (error: IHttpFetchError) => { @@ -52,21 +55,56 @@ export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoader [toastNotifications] ); + const getRequestInspector = useCallback( + (indexName: string) => { + const inspectRequest = requestAdapter.start( + i18n.translate('xpack.graph.inspectAdapter.graphExploreRequest.name', { + defaultMessage: 'Data', + }), + { + description: i18n.translate( + 'xpack.graph.inspectAdapter.graphExploreRequest.description', + { + defaultMessage: 'This request queries Elasticsearch to fetch the data for the Graph.', + } + ), + } + ); + inspectRequest.stats({ + indexPattern: { + label: i18n.translate( + 'xpack.graph.inspectAdapter.graphExploreRequest.dataView.description.label', + { defaultMessage: 'Data view' } + ), + value: indexName, + description: i18n.translate( + 'xpack.graph.inspectAdapter.graphExploreRequest.dataView.description', + { defaultMessage: 'The data view that connected to the Elasticsearch indices.' } + ), + }, + }); + return inspectRequest; + }, + [requestAdapter] + ); + // Replacement function for graphClientWorkspace's comms so // that it works with Kibana. const callNodeProxy = useCallback( (indexName: string, query: ExploreRequest, responseHandler: GraphExploreCallback) => { - const request = { - body: JSON.stringify({ - index: indexName, - query, - }), - }; + const dsl = { index: indexName, query }; + const request = { body: JSON.stringify(dsl) }; setLoading(true); + + requestAdapter.reset(); + const inspectRequest = getRequestInspector(indexName); + inspectRequest.json(dsl); + return coreStart.http - .post<{ resp: { timed_out: unknown } }>('../api/graph/graphExplore', request) + .post<{ resp: estypes.GraphExploreResponse }>('../api/graph/graphExplore', request) .then(function (data) { const response = data.resp; + if (response?.timed_out) { toastNotifications.addWarning( i18n.translate('xpack.graph.exploreGraph.timedOutWarningText', { @@ -74,38 +112,48 @@ export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoader }) ); } + inspectRequest.stats({}).ok({ json: response }); responseHandler(response); }) - .catch(handleHttpError) + .catch((e) => { + inspectRequest.error({ json: e }); + handleHttpError(e); + }) .finally(() => setLoading(false)); }, - [coreStart.http, handleHttpError, toastNotifications] + [coreStart.http, getRequestInspector, handleHttpError, requestAdapter, toastNotifications] ); // Helper function for the graphClientWorkspace to perform a query const callSearchNodeProxy = useCallback( (indexName: string, query: SearchRequest, responseHandler: GraphSearchCallback) => { - const request = { - body: JSON.stringify({ - index: indexName, - body: query, - }), - }; + const dsl = { index: indexName, body: query }; + const request = { body: JSON.stringify(dsl) }; setLoading(true); + + requestAdapter.reset(); + const inspectRequest = getRequestInspector(indexName); + inspectRequest.json(dsl); + coreStart.http - .post<{ resp: unknown }>('../api/graph/searchProxy', request) + .post<{ resp: estypes.GraphExploreResponse }>('../api/graph/searchProxy', request) .then(function (data) { const response = data.resp; + inspectRequest.stats({}).ok({ json: response }); responseHandler(response); }) - .catch(handleHttpError) + .catch((e) => { + inspectRequest.error({ json: e }); + handleHttpError(e); + }) .finally(() => setLoading(false)); }, - [coreStart.http, handleHttpError] + [coreStart.http, getRequestInspector, handleHttpError, requestAdapter] ); return { loading, + requestAdapter, callNodeProxy, callSearchNodeProxy, handleSearchQueryError, diff --git a/x-pack/plugins/graph/public/helpers/use_inspector.ts b/x-pack/plugins/graph/public/helpers/use_inspector.ts new file mode 100644 index 0000000000000..d6f237e625c3d --- /dev/null +++ b/x-pack/plugins/graph/public/helpers/use_inspector.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useEffect, useState } from 'react'; +import { + Start as InspectorPublicPluginStart, + InspectorSession, + RequestAdapter, +} from '@kbn/inspector-plugin/public'; + +export const useInspector = ({ + inspect, + requestAdapter, +}: { + inspect: InspectorPublicPluginStart; + requestAdapter: RequestAdapter; +}) => { + const [inspectorSession, setInspectorSession] = useState(); + + useEffect(() => { + return () => { + if (inspectorSession) { + inspectorSession.close(); + } + }; + }, [inspectorSession]); + + const onOpenInspector = useCallback(() => { + const session = inspect.open({ requests: requestAdapter }, {}); + setInspectorSession(session); + }, [inspect, requestAdapter]); + + return { onOpenInspector }; +}; diff --git a/x-pack/plugins/graph/public/plugin.ts b/x-pack/plugins/graph/public/plugin.ts index d4f8471426cc5..96dac017eeabb 100644 --- a/x-pack/plugins/graph/public/plugin.ts +++ b/x-pack/plugins/graph/public/plugin.ts @@ -19,6 +19,7 @@ import { DEFAULT_APP_CATEGORIES, } from '@kbn/core/public'; +import { Start as InspectorPublicPluginStart } from '@kbn/inspector-plugin/public'; import { Storage } from '@kbn/kibana-utils-plugin/public'; import { NavigationPublicPluginStart as NavigationStart } from '@kbn/navigation-plugin/public'; import { DataPublicPluginStart } from '@kbn/data-plugin/public'; @@ -40,6 +41,7 @@ export interface GraphPluginStartDependencies { data: DataPublicPluginStart; unifiedSearch: UnifiedSearchPublicPluginStart; savedObjects: SavedObjectsStart; + inspector: InspectorPublicPluginStart; home?: HomePublicPluginStart; spaces?: SpacesApi; } @@ -110,6 +112,7 @@ export class GraphPlugin savedObjects: pluginsStart.savedObjects, uiSettings: core.uiSettings, spaces: pluginsStart.spaces, + inspect: pluginsStart.inspector, }); }, }); diff --git a/x-pack/plugins/index_lifecycle_management/README.md b/x-pack/plugins/index_lifecycle_management/README.md index 35c2aa063ec23..912b19295790f 100644 --- a/x-pack/plugins/index_lifecycle_management/README.md +++ b/x-pack/plugins/index_lifecycle_management/README.md @@ -115,4 +115,8 @@ this by running: ```bash yarn es snapshot --license=trial -``` \ No newline at end of file +``` + +## Integration tests + +See `./integration_tests/README.md` \ No newline at end of file diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.tsx b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.tsx index ecefe8132c499..246de6e8ed25b 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.tsx +++ b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.tsx @@ -7,7 +7,7 @@ import moment from 'moment-timezone'; -import { init } from './client_integration/helpers/http_requests'; +import { init } from '../integration_tests/helpers/http_requests'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import { usageCollectionPluginMock } from '@kbn/usage-collection-plugin/public/mocks'; import { Index } from '../common/types'; diff --git a/x-pack/plugins/index_lifecycle_management/integration_tests/README.md b/x-pack/plugins/index_lifecycle_management/integration_tests/README.md new file mode 100644 index 0000000000000..5e4bf4360cb72 --- /dev/null +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/README.md @@ -0,0 +1,14 @@ +Most plugins of the deployment management team follow +the similar testing infrastructure where integration tests are located in `__jest__` and run as unit tests. + +The `index_lifecycle_management` tests [were refactored](https://github.com/elastic/kibana/pull/141750) to be run as integration tests because they [became flaky hitting the 5 seconds timeout](https://github.com/elastic/kibana/issues/115307#issuecomment-1238417474) for a jest unit test. + +Jest integration tests are just sit in a different directory and have two main differences: +- They never use parallelism, this allows them to access file system resources, launch services, etc. without needing to worry about conflicts with other tests +- They are allowed to take their sweet time, the default timeout is currently 10 minutes. + +To run these tests use: + +``` +node scripts/jest_integration x-pack/plugins/index_lifecycle_management/ +``` \ No newline at end of file diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/app/app.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/app/app.helpers.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/app/app.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/app/app.helpers.ts index df64fbce3fa1d..66810ebb1e546 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/app/app.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/app/app.helpers.ts @@ -8,7 +8,7 @@ import { act } from 'react-dom/test-utils'; import { HttpSetup } from '@kbn/core/public'; import { registerTestBed, TestBed, TestBedConfig } from '@kbn/test-jest-helpers'; -import { App } from '../../../public/application/app'; +import { App } from '../../public/application/app'; import { WithAppDependencies } from '../helpers'; const getTestBedConfig = (initialEntries: string[]): TestBedConfig => ({ diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/app/app.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/app/app.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/app/app.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/app/app.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/constants.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/constants.ts index 620cb9d6f8dde..a41bea1cb8415 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/constants.ts @@ -7,9 +7,9 @@ import moment from 'moment-timezone'; -import { PolicyFromES } from '../../../common/types'; +import { PolicyFromES } from '../../common/types'; -import { defaultRolloverAction } from '../../../public/application/constants'; +import { defaultRolloverAction } from '../../public/application/constants'; export const POLICY_NAME = 'my_policy'; export const SNAPSHOT_POLICY_NAME = 'my_snapshot_policy'; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/delete_phase.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/delete_phase.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/delete_phase.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/delete_phase.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/delete_phase.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/delete_phase.test.ts similarity index 98% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/delete_phase.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/delete_phase.test.ts index d877f05d06ae1..df6dd516c8a58 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/delete_phase.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/delete_phase.test.ts @@ -6,7 +6,7 @@ */ import { act } from 'react-dom/test-utils'; -import { API_BASE_PATH } from '../../../../common/constants'; +import { API_BASE_PATH } from '../../../common/constants'; import { setupEnvironment } from '../../helpers'; import { DELETE_PHASE_POLICY, diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/downsample.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/downsample.helpers.ts similarity index 95% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/downsample.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/downsample.helpers.ts index be96aaabe4a71..1e6ed336a5f03 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/downsample.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/downsample.helpers.ts @@ -14,7 +14,7 @@ import { createTogglePhaseAction, } from '../../helpers'; import { initTestBed } from '../init_test_bed'; -import { AppServicesContext } from '../../../../public/types'; +import { AppServicesContext } from '../../../public/types'; type SetupReturn = ReturnType; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/downsample.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/downsample.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/downsample.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/downsample.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/edit_warning.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/edit_warning.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/edit_warning.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/edit_warning.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/frozen_phase.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/frozen_phase.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/frozen_phase.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/frozen_phase.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts similarity index 94% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts index 7092d52289de9..b41075c6b6b68 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cloud_aware_behavior.helpers.ts @@ -8,7 +8,7 @@ import { HttpSetup } from '@kbn/core/public'; import { TestBedConfig } from '@kbn/test-jest-helpers'; -import { AppServicesContext } from '../../../../../public/types'; +import { AppServicesContext } from '../../../../public/types'; import { createTogglePhaseAction, createNodeAllocationActions } from '../../../helpers'; import { initTestBed } from '../../init_test_bed'; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cloud_aware_behavior.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cloud_aware_behavior.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cloud_aware_behavior.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cloud_aware_behavior.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cold_phase.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cold_phase.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cold_phase.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cold_phase.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cold_phase.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cold_phase.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/cold_phase.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/cold_phase.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/general_behavior.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/general_behavior.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/general_behavior.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/general_behavior.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/general_behavior.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/general_behavior.test.ts similarity index 98% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/general_behavior.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/general_behavior.test.ts index 1eecd5207664f..4830cee8ee237 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/general_behavior.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/general_behavior.test.ts @@ -17,7 +17,7 @@ import { POLICY_WITH_NODE_ATTR_AND_OFF_ALLOCATION, POLICY_WITH_NODE_ROLE_ALLOCATION, } from '../../constants'; -import { API_BASE_PATH } from '../../../../../common/constants'; +import { API_BASE_PATH } from '../../../../common/constants'; describe(' node allocation general behavior', () => { let testBed: GeneralNodeAllocationTestBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/warm_phase.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/warm_phase.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/warm_phase.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/warm_phase.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/warm_phase.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/warm_phase.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/node_allocation/warm_phase.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/node_allocation/warm_phase.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/request_flyout.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/request_flyout.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/request_flyout.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/request_flyout.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/request_flyout.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/request_flyout.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/request_flyout.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/request_flyout.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/rollover.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/rollover.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/rollover.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/rollover.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/rollover.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/rollover.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/rollover.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/rollover.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.helpers.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.helpers.ts index e70f721a48075..d3b68ffc6a13e 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.helpers.ts @@ -18,7 +18,7 @@ import { createTogglePhaseAction, } from '../../helpers'; import { initTestBed } from '../init_test_bed'; -import { AppServicesContext } from '../../../../public/types'; +import { AppServicesContext } from '../../../public/types'; type SetupReturn = ReturnType; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.test.ts similarity index 99% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.test.ts index 03b7670c1eac5..68e74e23a781c 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/searchable_snapshots.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/searchable_snapshots.test.ts @@ -10,7 +10,7 @@ import { licensingMock } from '@kbn/licensing-plugin/public/mocks'; import { HttpFetchOptionsWithPath } from '@kbn/core/public'; import { setupEnvironment } from '../../helpers'; import { getDefaultHotPhasePolicy } from '../constants'; -import { API_BASE_PATH } from '../../../../common/constants'; +import { API_BASE_PATH } from '../../../common/constants'; import { SearchableSnapshotsTestBed, setupSearchableSnapshotsTestBed, diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timeline.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timeline.helpers.ts similarity index 94% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timeline.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timeline.helpers.ts index 496b27330c931..202388a844464 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timeline.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timeline.helpers.ts @@ -8,7 +8,7 @@ import { HttpSetup } from '@kbn/core/public'; import { createTogglePhaseAction } from '../../helpers'; import { initTestBed } from '../init_test_bed'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; type SetupReturn = ReturnType; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timeline.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timeline.test.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timeline.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timeline.test.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timing.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timing.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timing.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timing.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timing.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timing.test.ts similarity index 95% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timing.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timing.test.ts index 0aee8eb5f0be1..72c6a2a4e789c 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/features/timing.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/features/timing.test.ts @@ -8,7 +8,7 @@ import { act } from 'react-dom/test-utils'; import { setupEnvironment } from '../../helpers'; import { setupTimingTestBed, TimingTestBed } from './timing.helpers'; -import { PhaseWithTiming } from '../../../../common/types'; +import { PhaseWithTiming } from '../../../common/types'; describe(' timing', () => { let testBed: TimingTestBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/cold_phase_validation.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/cold_phase_validation.test.ts similarity index 91% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/cold_phase_validation.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/cold_phase_validation.test.ts index ef2fc67002c14..e75d2cb72ab28 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/cold_phase_validation.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/cold_phase_validation.test.ts @@ -6,12 +6,11 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141645 -describe.skip(' cold phase validation', () => { +describe(' cold phase validation', () => { let testBed: ValidationTestBed; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/downsample_interval.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/downsample_interval.test.ts similarity index 93% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/downsample_interval.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/downsample_interval.test.ts index 79f5fdc6e2840..d2f9943eba68a 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/downsample_interval.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/downsample_interval.test.ts @@ -6,14 +6,13 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; -import { PhaseWithDownsample } from '../../../../common/types'; +import { PhaseWithDownsample } from '../../../common/types'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141160 -describe.skip(' downsample interval validation', () => { +describe(' downsample interval validation', () => { let testBed: ValidationTestBed; let actions: ValidationTestBed['actions']; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/error_indicators.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/error_indicators.test.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/error_indicators.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/error_indicators.test.ts index 349f98766620d..bd4a2caec0be5 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/error_indicators.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/error_indicators.test.ts @@ -9,8 +9,7 @@ import { act } from 'react-dom/test-utils'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141645 -describe.skip(' error indicators', () => { +describe(' error indicators', () => { let testBed: ValidationTestBed; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/hot_phase_validation.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/hot_phase_validation.test.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/hot_phase_validation.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/hot_phase_validation.test.ts index 82b3568d39ce7..71f83a59360d6 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/hot_phase_validation.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/hot_phase_validation.test.ts @@ -6,12 +6,11 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141645 -describe.skip(' hot phase validation', () => { +describe(' hot phase validation', () => { let testBed: ValidationTestBed; let actions: ValidationTestBed['actions']; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/policy_name_validation.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/policy_name_validation.test.ts similarity index 93% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/policy_name_validation.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/policy_name_validation.test.ts index 928380e3d1eac..c530f73a66c11 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/policy_name_validation.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/policy_name_validation.test.ts @@ -6,13 +6,12 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; import { setupEnvironment } from '../../helpers'; import { getGeneratedPolicies } from '../constants'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141645 -describe.skip(' policy name validation', () => { +describe(' policy name validation', () => { let testBed: ValidationTestBed; let actions: ValidationTestBed['actions']; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/timing.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/timing.test.ts similarity index 93% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/timing.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/timing.test.ts index 7db483d6d0ef2..5838f04ba70e9 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/timing.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/timing.test.ts @@ -6,14 +6,13 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; -import { PhaseWithTiming } from '../../../../common/types'; +import { PhaseWithTiming } from '../../../common/types'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/115307 -describe.skip(' timing validation', () => { +describe(' timing validation', () => { let testBed: ValidationTestBed; let actions: ValidationTestBed['actions']; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/validation.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/validation.helpers.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/validation.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/validation.helpers.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/warm_phase_validation.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/warm_phase_validation.test.ts similarity index 95% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/warm_phase_validation.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/warm_phase_validation.test.ts index df0607a0a0e65..47917b1f8e3d7 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/form_validation/warm_phase_validation.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/form_validation/warm_phase_validation.test.ts @@ -6,12 +6,11 @@ */ import { act } from 'react-dom/test-utils'; -import { i18nTexts } from '../../../../public/application/sections/edit_policy/i18n_texts'; +import { i18nTexts } from '../../../public/application/sections/edit_policy/i18n_texts'; import { setupEnvironment } from '../../helpers'; import { setupValidationTestBed, ValidationTestBed } from './validation.helpers'; -// FLAKY: https://github.com/elastic/kibana/issues/141645 -describe.skip(' warm phase validation', () => { +describe(' warm phase validation', () => { let testBed: ValidationTestBed; const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/init_test_bed.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/init_test_bed.ts similarity index 89% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/init_test_bed.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/init_test_bed.ts index 875bf9db36264..56bed7a6e50aa 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/init_test_bed.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/init_test_bed.ts @@ -5,12 +5,12 @@ * 2.0. */ +import { HttpSetup } from '@kbn/core/public'; import { registerTestBed, TestBedConfig } from '@kbn/test-jest-helpers'; -import { HttpSetup } from '@kbn/core/public'; import { WithAppDependencies } from '../helpers'; -import { EditPolicy } from '../../../public/application/sections/edit_policy'; -import { AppServicesContext } from '../../../public/types'; +import { EditPolicy } from '../../public/application/sections/edit_policy'; +import { AppServicesContext } from '../../public/types'; import { POLICY_NAME } from './constants'; const getTestBedConfig = (testBedConfig?: Partial): TestBedConfig => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.helpers.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.helpers.ts similarity index 95% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.helpers.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.helpers.ts index 417f53c63a20c..e439fca0de512 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.helpers.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.helpers.ts @@ -6,7 +6,7 @@ */ import { HttpSetup } from '@kbn/core/public'; -import { AppServicesContext } from '../../../../public/types'; +import { AppServicesContext } from '../../../public/types'; import { createColdPhaseActions, createDeletePhaseActions, diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.test.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.test.ts similarity index 99% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.test.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.test.ts index 983cfbadfa017..05aa66fcc5f25 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/serialization/policy_serialization.test.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/edit_policy/serialization/policy_serialization.test.ts @@ -9,7 +9,7 @@ import { act } from 'react-dom/test-utils'; import { licensingMock } from '@kbn/licensing-plugin/public/mocks'; import { HttpFetchOptionsWithPath } from '@kbn/core/public'; import { setupEnvironment } from '../../helpers'; -import { API_BASE_PATH } from '../../../../common/constants'; +import { API_BASE_PATH } from '../../../common/constants'; import { getDefaultHotPhasePolicy, POLICY_WITH_INCLUDE_EXCLUDE, diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/downsample_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/downsample_actions.ts similarity index 96% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/downsample_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/downsample_actions.ts index 315ed3d58520a..a389a9deebe32 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/downsample_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/downsample_actions.ts @@ -5,9 +5,9 @@ * 2.0. */ -import { TestBed } from '@kbn/test-jest-helpers'; import { act } from 'react-dom/test-utils'; -import { Phase } from '../../../../common/types'; +import { TestBed } from '@kbn/test-jest-helpers'; +import { Phase } from '../../../common/types'; import { createFormToggleAction } from '..'; const createSetDownsampleIntervalAction = diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/errors_actions.ts similarity index 96% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/errors_actions.ts index 4b863071e191c..18f07734fadee 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/errors_actions.ts @@ -7,7 +7,7 @@ import { act } from 'react-dom/test-utils'; import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; const createWaitForValidationAction = (testBed: TestBed) => () => { const { component } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/forcemerge_actions.ts similarity index 96% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/forcemerge_actions.ts index b6ed40de36ca9..619d6bd8be85f 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/forcemerge_actions.ts @@ -7,7 +7,7 @@ import { act } from 'react-dom/test-utils'; import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_set_value_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_set_value_action.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_set_value_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_set_value_action.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_toggle_action.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_toggle_action.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_toggle_and_set_value_action.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/form_toggle_and_set_value_action.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/index.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/index.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/index.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/index.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/index_priority_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/index_priority_actions.ts similarity index 94% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/index_priority_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/index_priority_actions.ts index 79fb77e53cc59..4c6e4604be7d4 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/index_priority_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/index_priority_actions.ts @@ -6,7 +6,7 @@ */ import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; import { createFormToggleAndSetValueAction } from './form_toggle_and_set_value_action'; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/min_age_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/min_age_actions.ts similarity index 94% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/min_age_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/min_age_actions.ts index ef00fdc8d7757..8b4fa2e5f6179 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/min_age_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/min_age_actions.ts @@ -6,7 +6,7 @@ */ import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormSetValueAction } from './form_set_value_action'; export const createMinAgeActions = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/node_allocation_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/node_allocation_actions.ts similarity index 95% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/node_allocation_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/node_allocation_actions.ts index 2a680590654a8..a3cb607b60f99 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/node_allocation_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/node_allocation_actions.ts @@ -8,8 +8,8 @@ import { act } from 'react-dom/test-utils'; import { TestBed } from '@kbn/test-jest-helpers'; -import { DataTierAllocationType } from '../../../../public/application/sections/edit_policy/types'; -import { Phase } from '../../../../common/types'; +import { DataTierAllocationType } from '../../../public/application/sections/edit_policy/types'; +import { Phase } from '../../../common/types'; import { createFormSetValueAction } from './form_set_value_action'; export const createNodeAllocationActions = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/phases.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/phases.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/phases.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/phases.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/readonly_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/readonly_actions.ts similarity index 92% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/readonly_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/readonly_actions.ts index 1a7ec56815b00..fe4c71d76265a 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/readonly_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/readonly_actions.ts @@ -6,7 +6,7 @@ */ import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; export const createReadonlyActions = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/replicas_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/replicas_action.ts similarity index 92% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/replicas_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/replicas_action.ts index 43eca26a4e1ce..35c3afc607513 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/replicas_action.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/replicas_action.ts @@ -6,7 +6,7 @@ */ import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormToggleAndSetValueAction } from './form_toggle_and_set_value_action'; export const createReplicasAction = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/request_flyout_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/request_flyout_actions.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/request_flyout_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/request_flyout_actions.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/rollover_actions.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/rollover_actions.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/save_policy_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/save_policy_action.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/save_policy_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/save_policy_action.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/searchable_snapshot_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/searchable_snapshot_actions.ts similarity index 96% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/searchable_snapshot_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/searchable_snapshot_actions.ts index 3efffcddbece6..c9a019c2bc842 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/searchable_snapshot_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/searchable_snapshot_actions.ts @@ -7,7 +7,7 @@ import { act } from 'react-dom/test-utils'; import { TestBed } from '@kbn/test-jest-helpers'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; export const createSearchableSnapshotActions = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/shrink_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/shrink_actions.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/shrink_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/shrink_actions.ts index def20f73b82fe..4bf39185b8c03 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/shrink_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/shrink_actions.ts @@ -7,7 +7,7 @@ import { TestBed } from '@kbn/test-jest-helpers'; import { act } from 'react-dom/test-utils'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; import { createFormSetValueAction } from './form_set_value_action'; export const createShrinkActions = (testBed: TestBed, phase: Phase) => { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/snapshot_policy_actions.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/snapshot_policy_actions.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/snapshot_policy_actions.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/snapshot_policy_actions.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/toggle_phase_action.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/toggle_phase_action.ts similarity index 96% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/toggle_phase_action.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/toggle_phase_action.ts index c22efae87d5ac..fc89332e47a67 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/toggle_phase_action.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/actions/toggle_phase_action.ts @@ -8,7 +8,7 @@ import { TestBed } from '@kbn/test-jest-helpers'; import { act } from 'react-dom/test-utils'; -import { Phase } from '../../../../common/types'; +import { Phase } from '../../../common/types'; const toggleDeletePhase = async (testBed: TestBed) => { const { find, component } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/global_mocks.tsx b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/global_mocks.tsx similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/global_mocks.tsx rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/global_mocks.tsx diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/http_requests.ts similarity index 97% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/http_requests.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/http_requests.ts index 7ddcd5358404f..70e85c8bc5df4 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/http_requests.ts @@ -6,12 +6,12 @@ */ import { httpServiceMock } from '@kbn/core/public/mocks'; -import { API_BASE_PATH } from '../../../common/constants'; +import { API_BASE_PATH } from '../../common/constants'; import { ListNodesRouteResponse, ListSnapshotReposResponse, NodesDetailsResponse, -} from '../../../common/types'; +} from '../../common/types'; import { getDefaultHotPhasePolicy } from '../edit_policy/constants'; type HttpMethod = 'GET' | 'PUT' | 'DELETE' | 'POST'; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/index.ts similarity index 100% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/index.ts rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/index.ts diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/setup_environment.tsx similarity index 80% rename from x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/setup_environment.tsx rename to x-pack/plugins/index_lifecycle_management/integration_tests/helpers/setup_environment.tsx index 055097c883e94..91aebb485ea7f 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_lifecycle_management/integration_tests/helpers/setup_environment.tsx @@ -19,12 +19,12 @@ import { executionContextServiceMock, } from '@kbn/core/public/mocks'; import { licensingMock } from '@kbn/licensing-plugin/public/mocks'; -import { init as initHttp } from '../../../public/application/services/http'; +import { init as initHttp } from '../../public/application/services/http'; import { init as initHttpRequests } from './http_requests'; -import { init as initUiMetric } from '../../../public/application/services/ui_metric'; -import { init as initNotification } from '../../../public/application/services/notification'; -import { KibanaContextProvider } from '../../../public/shared_imports'; -import { createBreadcrumbsMock } from '../../../public/application/services/breadcrumbs.mock'; +import { init as initUiMetric } from '../../public/application/services/ui_metric'; +import { init as initNotification } from '../../public/application/services/notification'; +import { KibanaContextProvider } from '../../public/shared_imports'; +import { createBreadcrumbsMock } from '../../public/application/services/breadcrumbs.mock'; const breadcrumbService = createBreadcrumbsMock(); const appContextMock = { diff --git a/x-pack/plugins/index_lifecycle_management/jest.integration.config.js b/x-pack/plugins/index_lifecycle_management/jest.integration.config.js new file mode 100644 index 0000000000000..6d1ac5ec2fd8a --- /dev/null +++ b/x-pack/plugins/index_lifecycle_management/jest.integration.config.js @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test/jest_integration', + rootDir: '../../..', + roots: ['/x-pack/plugins/index_lifecycle_management'], + testMatch: ['/**/integration_tests/**/*.test.{js,mjs,ts,tsx}'], + coverageDirectory: + '/target/kibana-coverage/jest/x-pack/plugins/index_lifecycle_management', + coverageReporters: ['text', 'html'], + collectCoverageFrom: [ + '/x-pack/plugins/index_lifecycle_management/{common,public,server}/**/*.{ts,tsx}', + ], +}; diff --git a/x-pack/plugins/index_lifecycle_management/tsconfig.json b/x-pack/plugins/index_lifecycle_management/tsconfig.json index d3a342e110211..4b5d7657ed9f6 100644 --- a/x-pack/plugins/index_lifecycle_management/tsconfig.json +++ b/x-pack/plugins/index_lifecycle_management/tsconfig.json @@ -8,6 +8,7 @@ }, "include": [ "__jest__/**/*", + "integration_tests/**/*", "common/**/*", "public/**/*", "server/**/*", diff --git a/x-pack/plugins/infra/public/apps/metrics_app.tsx b/x-pack/plugins/infra/public/apps/metrics_app.tsx index fdeb7173d5cee..ce8123b5f2223 100644 --- a/x-pack/plugins/infra/public/apps/metrics_app.tsx +++ b/x-pack/plugins/infra/public/apps/metrics_app.tsx @@ -45,6 +45,7 @@ export const renderApp = ( ); return () => { + core.chrome.docTitle.reset(); ReactDOM.unmountComponentAtNode(element); plugins.data.search.session.clear(); }; diff --git a/x-pack/plugins/infra/public/components/document_title.tsx b/x-pack/plugins/infra/public/components/document_title.tsx deleted file mode 100644 index 20e482d9df5b5..0000000000000 --- a/x-pack/plugins/infra/public/components/document_title.tsx +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; - -type TitleProp = string | ((previousTitle: string) => string); - -interface DocumentTitleProps { - title: TitleProp; -} - -interface DocumentTitleState { - index: number; -} - -const wrapWithSharedState = () => { - const titles: string[] = []; - const TITLE_SUFFIX = ' - Kibana'; - - return class extends React.Component { - public componentDidMount() { - this.setState( - () => { - return { index: titles.push('') - 1 }; - }, - () => { - this.pushTitle(this.getTitle(this.props.title)); - this.updateDocumentTitle(); - } - ); - } - - public componentDidUpdate() { - this.pushTitle(this.getTitle(this.props.title)); - this.updateDocumentTitle(); - } - - public componentWillUnmount() { - this.removeTitle(); - this.updateDocumentTitle(); - } - - public render() { - return null; - } - - public getTitle(title: TitleProp) { - return typeof title === 'function' ? title(titles[this.state.index - 1]) : title; - } - - public pushTitle(title: string) { - titles[this.state.index] = title; - } - - public removeTitle() { - titles.pop(); - } - - public updateDocumentTitle() { - const title = (titles[titles.length - 1] || '') + TITLE_SUFFIX; - if (title !== document.title) { - document.title = title; - } - } - }; -}; - -export const DocumentTitle = wrapWithSharedState(); diff --git a/x-pack/plugins/infra/public/hooks/use_breadcrumbs.ts b/x-pack/plugins/infra/public/hooks/use_breadcrumbs.ts index 37801c16bcf1f..97f737380022d 100644 --- a/x-pack/plugins/infra/public/hooks/use_breadcrumbs.ts +++ b/x-pack/plugins/infra/public/hooks/use_breadcrumbs.ts @@ -22,7 +22,7 @@ export const useBreadcrumbs = (app: AppId, appTitle: string, extraCrumbs: Chrome const appLinkProps = useLinkProps({ app }); useEffect(() => { - chrome?.setBreadcrumbs?.([ + const breadcrumbs = [ { ...observabilityLinkProps, text: observabilityTitle, @@ -32,6 +32,11 @@ export const useBreadcrumbs = (app: AppId, appTitle: string, extraCrumbs: Chrome text: appTitle, }, ...extraCrumbs, - ]); + ]; + + const docTitle = [...breadcrumbs].reverse().map((breadcrumb) => breadcrumb.text as string); + + chrome.docTitle.change(docTitle); + chrome.setBreadcrumbs(breadcrumbs); }, [appLinkProps, appTitle, chrome, extraCrumbs, observabilityLinkProps]); }; diff --git a/x-pack/plugins/infra/public/hooks/use_document_title.tsx b/x-pack/plugins/infra/public/hooks/use_document_title.tsx new file mode 100644 index 0000000000000..82fb5a669eb91 --- /dev/null +++ b/x-pack/plugins/infra/public/hooks/use_document_title.tsx @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ChromeBreadcrumb } from '@kbn/core/public'; +import { useEffect } from 'react'; +import { observabilityTitle } from '../translations'; +import { useKibanaContextForPlugin } from './use_kibana'; + +export const useDocumentTitle = (extraTitles: ChromeBreadcrumb[]) => { + const { + services: { chrome }, + } = useKibanaContextForPlugin(); + + useEffect(() => { + const docTitle = [{ text: observabilityTitle }, ...extraTitles] + .reverse() + .map((breadcrumb) => breadcrumb.text as string); + + chrome.docTitle.change(docTitle); + }, [chrome, extraTitles]); +}; 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 e42cfc2d7c54a..8acd4004603e9 100644 --- a/x-pack/plugins/infra/public/pages/logs/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/page_content.tsx @@ -12,7 +12,6 @@ import { Route, Switch } from 'react-router-dom'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { HeaderMenuPortal, useLinkProps } from '@kbn/observability-plugin/public'; import { AlertDropdown } from '../../alerting/log_threshold'; -import { DocumentTitle } from '../../components/document_title'; import { HelpCenterContent } from '../../components/help_center_content'; import { useReadOnlyBadge } from '../../hooks/use_readonly_badge'; import { HeaderActionMenuContext } from '../../utils/header_action_menu_provider'; @@ -62,8 +61,6 @@ export const LogsPageContent: React.FunctionComponent = () => { return ( <> - - {setHeaderActionMenu && theme$ && ( diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page.tsx index bb8e4307fe3b9..19f098a6721bc 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page.tsx @@ -10,7 +10,6 @@ import React from 'react'; import { useTrackPageview } from '@kbn/observability-plugin/public'; import { useLogsBreadcrumbs } from '../../../hooks/use_logs_breadcrumbs'; import { StreamPageContent } from './page_content'; -import { StreamPageHeader } from './page_header'; import { LogsPageProviders } from './page_providers'; import { streamTitle } from '../../../translations'; @@ -26,7 +25,6 @@ export const StreamPage = () => { return ( - diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_header.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_header.tsx deleted file mode 100644 index f6c4ad8c8c139..0000000000000 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_header.tsx +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { i18n } from '@kbn/i18n'; -import React from 'react'; - -import { DocumentTitle } from '../../../components/document_title'; - -export const StreamPageHeader = () => { - return ( - <> - - i18n.translate('xpack.infra.logs.streamPage.documentTitle', { - defaultMessage: '{previousTitle} | Stream', - values: { - previousTitle, - }, - }) - } - /> - - ); -}; diff --git a/x-pack/plugins/infra/public/pages/metrics/hosts/components/hosts_table.tsx b/x-pack/plugins/infra/public/pages/metrics/hosts/components/hosts_table.tsx index 9975de8db7375..57b3ab0e683ac 100644 --- a/x-pack/plugins/infra/public/pages/metrics/hosts/components/hosts_table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/hosts/components/hosts_table.tsx @@ -64,7 +64,7 @@ const getLensHostsTable = ( dataType: 'string', operationType: 'terms', scale: 'ordinal', - sourceField: 'host.os.name', + sourceField: 'host.os.type', isBucketed: true, params: { size: 10000, diff --git a/x-pack/plugins/infra/public/pages/metrics/hosts/index.tsx b/x-pack/plugins/infra/public/pages/metrics/hosts/index.tsx index 5c2fed9753b80..a5dfd7f2ddd0f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/hosts/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/hosts/index.tsx @@ -6,13 +6,10 @@ */ import { EuiErrorBoundary } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; import React from 'react'; import { useTrackPageview } from '@kbn/observability-plugin/public'; import { APP_WRAPPER_CLASS } from '@kbn/core/public'; -import { DocumentTitle } from '../../../components/document_title'; - import { SourceErrorPage } from '../../../components/source_error_page'; import { SourceLoadingPage } from '../../../components/source_loading_page'; import { useSourceContext } from '../../../containers/metrics_source'; @@ -42,16 +39,6 @@ export const HostsPage = () => { ]); return ( - - i18n.translate('xpack.infra.infrastructureHostsPage.documentTitle', { - defaultMessage: '{previousTitle} | Hosts', - values: { - previousTitle, - }, - }) - } - /> {isLoading && !source ? ( ) : metricIndicesExist && source ? ( diff --git a/x-pack/plugins/infra/public/pages/metrics/index.tsx b/x-pack/plugins/infra/public/pages/metrics/index.tsx index 9c02424aac949..691069a978e83 100644 --- a/x-pack/plugins/infra/public/pages/metrics/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/index.tsx @@ -15,7 +15,6 @@ import { useKibana } from '@kbn/kibana-react-plugin/public'; import { HeaderMenuPortal } from '@kbn/observability-plugin/public'; import { useLinkProps } from '@kbn/observability-plugin/public'; import { MetricsSourceConfigurationProperties } from '../../../common/metrics_sources'; -import { DocumentTitle } from '../../components/document_title'; import { HelpCenterContent } from '../../components/help_center_content'; import { useReadOnlyBadge } from '../../hooks/use_readonly_badge'; import { @@ -73,12 +72,6 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => { - - { return ( - - i18n.translate('xpack.infra.infrastructureSnapshotPage.documentTitle', { - defaultMessage: '{previousTitle} | Inventory', - values: { - previousTitle, - }, - }) - } - /> {isLoading && !source ? ( ) : metricIndicesExist ? ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.test.tsx new file mode 100644 index 0000000000000..25ae3b3717bd6 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.test.tsx @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; + +import { PageError } from './page_error'; +import { errorTitle } from '../../../../translations'; +import { InfraHttpError } from '../../../../types'; +import { useDocumentTitle } from '../../../../hooks/use_document_title'; +import { I18nProvider } from '@kbn/i18n-react'; + +jest.mock('../../../../hooks/use_document_title', () => ({ + useDocumentTitle: jest.fn(), +})); + +const renderErrorPage = () => + render( + + + + ); + +describe('PageError component', () => { + it('renders correctly and set title', () => { + const { getByText } = renderErrorPage(); + expect(useDocumentTitle).toHaveBeenCalledWith([{ text: `${errorTitle}` }]); + + expect(getByText('Error Message')).toBeInTheDocument(); + expect(getByText('Please click the back button and try again.')).toBeInTheDocument(); + }); +}); diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.tsx index a6665e0d244f2..b4cdb47399e98 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/page_error.tsx @@ -6,11 +6,11 @@ */ import React from 'react'; -import { i18n } from '@kbn/i18n'; +import { useDocumentTitle } from '../../../../hooks/use_document_title'; import { InvalidNodeError } from './invalid_node'; -import { DocumentTitle } from '../../../../components/document_title'; import { ErrorPageBody } from '../../../error'; import { InfraHttpError } from '../../../../types'; +import { errorTitle } from '../../../../translations'; interface Props { name: string; @@ -18,18 +18,10 @@ interface Props { } export const PageError = ({ error, name }: Props) => { + useDocumentTitle([{ text: errorTitle }]); + return ( <> - - i18n.translate('xpack.infra.metricDetailPage.documentTitleError', { - defaultMessage: '{previousTitle} | Uh oh', - values: { - previousTitle, - }, - }) - } - /> {error.body?.statusCode === 404 ? ( ) : ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx index 823b9d703f502..9b92901976bff 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx @@ -9,7 +9,6 @@ import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; import { EuiTheme, withTheme } from '@kbn/kibana-react-plugin/common'; import { useLinkProps } from '@kbn/observability-plugin/public'; -import { DocumentTitle } from '../../../components/document_title'; import { withMetricPageProviders } from './page_providers'; import { useMetadata } from './hooks/use_metadata'; import { useMetricsBreadcrumbs } from '../../../hooks/use_metrics_breadcrumbs'; @@ -100,14 +99,6 @@ export const MetricDetail = withMetricPageProviders( return ( <> - {metadata ? ( - - i18n.translate('xpack.infra.infrastructureMetricsExplorerPage.documentTitle', { - defaultMessage: '{previousTitle} | Metrics Explorer', - values: { - previousTitle, - }, - }) - } - /> IFieldFormat; export interface ExistingFields { diff --git a/x-pack/plugins/lens/public/app_plugin/app.test.tsx b/x-pack/plugins/lens/public/app_plugin/app.test.tsx index ab74c115d39db..58e65b3b79bbe 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.test.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.test.tsx @@ -202,7 +202,7 @@ describe('Lens App', () => { }, }); const navigationComponent = services.navigation.ui - .TopNavMenu as unknown as React.ReactElement; + .AggregateQueryTopNavMenu as unknown as React.ReactElement; const extraEntry = instance.find(navigationComponent).prop('config')[0]; expect(extraEntry.label).toEqual('My entry'); expect(extraEntry.run).toBe(runFn); @@ -367,7 +367,7 @@ describe('Lens App', () => { Promise.resolve({ id, isTimeBased: () => true, isPersisted: () => true } as DataView) ); const { services } = await mountWith({ services: customServices }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ showDatePicker: true }), {} ); @@ -382,7 +382,7 @@ describe('Lens App', () => { const customProps = makeDefaultProps(); customProps.datasourceMap.testDatasource.isTimeBased = () => true; const { services } = await mountWith({ props: customProps, services: customServices }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ showDatePicker: true }), {} ); @@ -397,7 +397,7 @@ describe('Lens App', () => { const customProps = makeDefaultProps(); customProps.datasourceMap.testDatasource.isTimeBased = () => false; const { services } = await mountWith({ props: customProps, services: customServices }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ showDatePicker: false }), {} ); @@ -495,7 +495,7 @@ describe('Lens App', () => { }); instance.update(); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ query: 'fake query', indexPatterns: [ @@ -518,7 +518,7 @@ describe('Lens App', () => { .mockImplementation((id) => Promise.reject({ reason: 'Could not locate that data view' })); const customProps = makeDefaultProps(); const { services } = await mountWith({ props: customProps, services: customServices }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ indexPatterns: [] }), {} ); @@ -633,7 +633,9 @@ describe('Lens App', () => { expect(getButton(instance).disableButton).toEqual(false); await act(async () => { - const topNavMenuConfig = instance.find(services.navigation.ui.TopNavMenu).prop('config'); + const topNavMenuConfig = instance + .find(services.navigation.ui.AggregateQueryTopNavMenu) + .prop('config'); expect(topNavMenuConfig).not.toContainEqual( expect.objectContaining(navMenuItems.expectedSaveAndReturnButton) ); @@ -671,7 +673,9 @@ describe('Lens App', () => { }); await act(async () => { - const topNavMenuConfig = instance.find(services.navigation.ui.TopNavMenu).prop('config'); + const topNavMenuConfig = instance + .find(services.navigation.ui.AggregateQueryTopNavMenu) + .prop('config'); expect(topNavMenuConfig).toContainEqual( expect.objectContaining(navMenuItems.expectedSaveAndReturnButton) ); @@ -699,7 +703,9 @@ describe('Lens App', () => { }); await act(async () => { - const topNavMenuConfig = instance.find(services.navigation.ui.TopNavMenu).prop('config'); + const topNavMenuConfig = instance + .find(services.navigation.ui.AggregateQueryTopNavMenu) + .prop('config'); expect(topNavMenuConfig).toContainEqual( expect.objectContaining(navMenuItems.expectedSaveAndReturnButton) ); @@ -1002,7 +1008,7 @@ describe('Lens App', () => { describe('query bar state management', () => { it('uses the default time and query language settings', async () => { const { lensStore, services } = await mountWith({}); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ query: { query: '', language: 'lucene' }, dateRangeFrom: 'now-7d', @@ -1029,13 +1035,13 @@ describe('Lens App', () => { max: moment('2021-01-09T08:00:00.000Z'), }); await act(async () => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-14d', to: 'now-7d' }, query: { query: 'new', language: 'lucene' }, }) ); instance.update(); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ query: { query: 'new', language: 'lucene' }, dateRangeFrom: 'now-14d', @@ -1089,7 +1095,7 @@ describe('Lens App', () => { }); act(() => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-14d', to: 'now-7d' }, query: { query: '', language: 'lucene' }, }) @@ -1103,7 +1109,7 @@ describe('Lens App', () => { }); // trigger again, this time changing just the query act(() => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-14d', to: 'now-7d' }, query: { query: 'new', language: 'lucene' }, }) @@ -1139,7 +1145,7 @@ describe('Lens App', () => { }, }; await mountWith({ services }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ showSaveQuery: false }), {} ); @@ -1147,7 +1153,7 @@ describe('Lens App', () => { it('persists the saved query ID when the query is saved', async () => { const { instance, services } = await mountWith({}); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ showSaveQuery: true, savedQuery: undefined, @@ -1158,7 +1164,7 @@ describe('Lens App', () => { {} ); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSaved')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSaved')!({ id: '1', attributes: { title: '', @@ -1167,7 +1173,7 @@ describe('Lens App', () => { }, }); }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ savedQuery: { id: '1', @@ -1185,7 +1191,7 @@ describe('Lens App', () => { it('changes the saved query ID when the query is updated', async () => { const { instance, services } = await mountWith({}); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSaved')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSaved')!({ id: '1', attributes: { title: '', @@ -1195,16 +1201,18 @@ describe('Lens App', () => { }); }); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSavedQueryUpdated')!({ - id: '2', - attributes: { - title: 'new title', - description: '', - query: { query: '', language: 'lucene' }, - }, - }); + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSavedQueryUpdated')!( + { + id: '2', + attributes: { + title: 'new title', + description: '', + query: { query: '', language: 'lucene' }, + }, + } + ); }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ savedQuery: { id: '2', @@ -1222,16 +1230,18 @@ describe('Lens App', () => { it('updates the query if saved query is selected', async () => { const { instance, services } = await mountWith({}); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSavedQueryUpdated')!({ - id: '2', - attributes: { - title: 'new title', - description: '', - query: { query: 'abc:def', language: 'lucene' }, - }, - }); + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSavedQueryUpdated')!( + { + id: '2', + attributes: { + title: 'new title', + description: '', + query: { query: 'abc:def', language: 'lucene' }, + }, + } + ); }); - expect(services.navigation.ui.TopNavMenu).toHaveBeenCalledWith( + expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ query: { query: 'abc:def', language: 'lucene' }, }), @@ -1242,7 +1252,7 @@ describe('Lens App', () => { it('clears all existing unpinned filters when the active saved query is cleared', async () => { const { instance, services, lensStore } = await mountWith({}); act(() => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-14d', to: 'now-7d' }, query: { query: 'new', language: 'lucene' }, }) @@ -1255,7 +1265,9 @@ describe('Lens App', () => { FilterManager.setFiltersStore([pinned], FilterStateStore.GLOBAL_STATE); act(() => services.data.query.filterManager.setFilters([pinned, unpinned])); instance.update(); - act(() => instance.find(services.navigation.ui.TopNavMenu).prop('onClearSavedQuery')!()); + act(() => + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onClearSavedQuery')!() + ); instance.update(); expect(lensStore.getState()).toEqual({ lens: expect.objectContaining({ @@ -1269,7 +1281,7 @@ describe('Lens App', () => { it('updates the searchSessionId when the query is updated', async () => { const { instance, lensStore, services } = await mountWith({}); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSaved')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSaved')!({ id: '1', attributes: { title: '', @@ -1279,14 +1291,16 @@ describe('Lens App', () => { }); }); act(() => { - instance.find(services.navigation.ui.TopNavMenu).prop('onSavedQueryUpdated')!({ - id: '2', - attributes: { - title: 'new title', - description: '', - query: { query: '', language: 'lucene' }, - }, - }); + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onSavedQueryUpdated')!( + { + id: '2', + attributes: { + title: 'new title', + description: '', + query: { query: '', language: 'lucene' }, + }, + } + ); }); instance.update(); expect(lensStore.getState()).toEqual({ @@ -1299,7 +1313,7 @@ describe('Lens App', () => { it('updates the searchSessionId when the active saved query is cleared', async () => { const { instance, services, lensStore } = await mountWith({}); act(() => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-14d', to: 'now-7d' }, query: { query: 'new', language: 'lucene' }, }) @@ -1312,7 +1326,9 @@ describe('Lens App', () => { FilterManager.setFiltersStore([pinned], FilterStateStore.GLOBAL_STATE); act(() => services.data.query.filterManager.setFilters([pinned, unpinned])); instance.update(); - act(() => instance.find(services.navigation.ui.TopNavMenu).prop('onClearSavedQuery')!()); + act(() => + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onClearSavedQuery')!() + ); instance.update(); expect(lensStore.getState()).toEqual({ lens: expect.objectContaining({ @@ -1324,7 +1340,7 @@ describe('Lens App', () => { it('dispatches update to searchSessionId and dateRange when the user hits refresh', async () => { const { instance, services, lensStore } = await mountWith({}); act(() => - instance.find(services.navigation.ui.TopNavMenu).prop('onQuerySubmit')!({ + instance.find(services.navigation.ui.AggregateQueryTopNavMenu).prop('onQuerySubmit')!({ dateRange: { from: 'now-7d', to: 'now' }, }) ); diff --git a/x-pack/plugins/lens/public/app_plugin/app.tsx b/x-pack/plugins/lens/public/app_plugin/app.tsx index 46233dc6db6c6..22bff02cb5925 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.tsx @@ -6,7 +6,7 @@ */ import './app.scss'; -import React, { useState, useEffect, useCallback, useMemo } from 'react'; +import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiBreadcrumb, EuiConfirmModal } from '@elastic/eui'; import { useExecutionContext, useKibana } from '@kbn/kibana-react-plugin/public'; @@ -79,6 +79,8 @@ export function App({ dashboardFeatureFlag, } = lensAppServices; + const saveAndExit = useRef<() => void>(); + const dispatch = useLensDispatch(); const dispatchSetState: DispatchSetState = useCallback( (state: Partial) => dispatch(setState(state)), @@ -115,6 +117,7 @@ export function App({ undefined ); const [isGoBackToVizEditorModalVisible, setIsGoBackToVizEditorModalVisible] = useState(false); + const [shouldCloseAndSaveTextBasedQuery, setShouldCloseAndSaveTextBasedQuery] = useState(false); const savedObjectId = (initialInput as LensByReferenceInput)?.savedObjectId; useEffect(() => { @@ -261,6 +264,12 @@ export function App({ initialContext, ]); + const switchDatasource = useCallback(() => { + if (saveAndExit && saveAndExit.current) { + saveAndExit.current(); + } + }, []); + const runSave = useCallback( (saveProps: SaveProps, options: { saveToLibrary: boolean }) => { dispatch(applyChanges()); @@ -274,7 +283,9 @@ export function App({ persistedDoc, onAppLeave, redirectTo, + switchDatasource, originatingApp: incomingState?.originatingApp, + textBasedLanguageSave: shouldCloseAndSaveTextBasedQuery, ...lensAppServices, }, saveProps, @@ -284,6 +295,7 @@ export function App({ if (newState) { dispatchSetState(newState); setIsSaveModalVisible(false); + setShouldCloseAndSaveTextBasedQuery(false); } }, () => { @@ -293,19 +305,20 @@ export function App({ ); }, [ - incomingState?.originatingApp, + dispatch, lastKnownDoc, - persistedDoc, getIsByValueMode, savedObjectsTagging, initialInput, redirectToOrigin, + persistedDoc, onAppLeave, redirectTo, + switchDatasource, + incomingState?.originatingApp, + shouldCloseAndSaveTextBasedQuery, lensAppServices, dispatchSetState, - dispatch, - setIsSaveModalVisible, ] ); @@ -392,6 +405,14 @@ export function App({ [dataViews, uiActions, http, notifications, uiSettings, data, initialContext, dispatch] ); + const onTextBasedSavedAndExit = useCallback(async ({ onSave, onCancel }) => { + setIsSaveModalVisible(true); + setShouldCloseAndSaveTextBasedQuery(true); + saveAndExit.current = () => { + onSave(); + }; + }, []); + return ( <>
@@ -416,6 +437,7 @@ export function App({ initialContext={initialContext} theme$={theme$} indexPatternService={indexPatternService} + onTextBasedSavedAndExit={onTextBasedSavedAndExit} /> {getLegacyUrlConflictCallout()} {(!isLoading || persistedDoc) && ( diff --git a/x-pack/plugins/lens/public/app_plugin/lens_top_nav.tsx b/x-pack/plugins/lens/public/app_plugin/lens_top_nav.tsx index 47ccc5aac74e8..8875d2d0f9839 100644 --- a/x-pack/plugins/lens/public/app_plugin/lens_top_nav.tsx +++ b/x-pack/plugins/lens/public/app_plugin/lens_top_nav.tsx @@ -8,13 +8,16 @@ import { isEqual } from 'lodash'; import { i18n } from '@kbn/i18n'; import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react'; +import { isOfAggregateQueryType } from '@kbn/es-query'; import { useStore } from 'react-redux'; import { TopNavMenuData } from '@kbn/navigation-plugin/public'; import { downloadMultipleAs } from '@kbn/share-plugin/public'; import { tableHasFormulas } from '@kbn/data-plugin/common'; import { exporters, getEsQueryConfig } from '@kbn/data-plugin/public'; import type { DataView } from '@kbn/data-views-plugin/public'; +import type { DataViewPickerProps } from '@kbn/unified-search-plugin/public'; import { useKibana } from '@kbn/kibana-react-plugin/public'; +import { ENABLE_SQL } from '../../common'; import { LensAppServices, LensTopNavActions, @@ -28,6 +31,7 @@ import { useLensDispatch, LensAppState, DispatchSetState, + switchAndCleanDatasource, } from '../state_management'; import { getIndexPatternsObjects, @@ -220,6 +224,7 @@ export const LensTopNavMenu = ({ theme$, indexPatternService, currentDoc, + onTextBasedSavedAndExit, }: LensTopNavMenuProps) => { const { data, @@ -254,7 +259,9 @@ export const LensTopNavMenu = ({ [dispatch] ); const [indexPatterns, setIndexPatterns] = useState([]); + const [dataViewsList, setDataViewsList] = useState([]); const [currentIndexPattern, setCurrentIndexPattern] = useState(); + const [isOnTextBasedMode, setIsOnTextBasedMode] = useState(false); const [rejectedIndexPatterns, setRejectedIndexPatterns] = useState([]); const dispatchChangeIndexPattern = React.useCallback( @@ -355,6 +362,25 @@ export const LensTopNavMenu = ({ } }, [indexPatterns]); + useEffect(() => { + const fetchDataViews = async () => { + const totalDataViewsList = []; + const dataViewsIds = await data.dataViews.getIds(); + for (let i = 0; i < dataViewsIds.length; i++) { + const d = await data.dataViews.get(dataViewsIds[i]); + totalDataViewsList.push(d); + } + setDataViewsList(totalDataViewsList); + }; + fetchDataViews(); + }, [data]); + + useEffect(() => { + if (typeof query === 'object' && query !== null && isOfAggregateQueryType(query)) { + setIsOnTextBasedMode(true); + } + }, [query]); + useEffect(() => { return () => { // Make sure to close the editors when unmounting @@ -363,7 +389,7 @@ export const LensTopNavMenu = ({ }; }, []); - const { TopNavMenu } = navigation.ui; + const { AggregateQueryTopNavMenu } = navigation.ui; const { from, to } = data.query.timefilter.timefilter.getTime(); const savingToLibraryPermitted = Boolean(isSaveable && application.capabilities.visualize.save); @@ -550,7 +576,7 @@ export const LensTopNavMenu = ({ ); return discover.locator!.getRedirectUrl({ - dataViewSpec: dataViews.indexPatterns[meta.id].spec, + dataViewSpec: dataViews.indexPatterns[meta.id]?.spec, timeRange: data.query.timefilter.timefilter.getTime(), filters: newFilters, query: newQuery, @@ -617,10 +643,30 @@ export const LensTopNavMenu = ({ if (newQuery) { if (!isEqual(newQuery, query)) { dispatchSetState({ query: newQuery }); + // check if query is text-based (sql, essql etc) and switchAndCleanDatasource + if (isOfAggregateQueryType(newQuery) && !isOnTextBasedMode) { + setIsOnTextBasedMode(true); + dispatch( + switchAndCleanDatasource({ + newDatasourceId: 'textBasedLanguages', + visualizationId: visualization?.activeId, + currentIndexPatternId: currentIndexPattern?.id, + }) + ); + } } } }, - [data.query.timefilter.timefilter, data.search.session, dispatchSetState, query] + [ + currentIndexPattern?.id, + data.query.timefilter.timefilter, + data.search.session, + dispatch, + dispatchSetState, + isOnTextBasedMode, + query, + visualization?.activeId, + ] ); const onSavedWrapped = useCallback( @@ -722,6 +768,13 @@ export const LensTopNavMenu = ({ closeDataViewEditor.current = dataViewEditor.openEditor({ onSave: async (dataView) => { if (dataView.id) { + dispatch( + switchAndCleanDatasource({ + newDatasourceId: 'indexpattern', + visualizationId: visualization?.activeId, + currentIndexPatternId: dataView?.id, + }) + ); dispatchChangeIndexPattern(dataView); setCurrentIndexPattern(dataView); } @@ -730,9 +783,16 @@ export const LensTopNavMenu = ({ }); } : undefined, - [canEditDataView, dataViewEditor, dispatchChangeIndexPattern] + [canEditDataView, dataViewEditor, dispatch, dispatchChangeIndexPattern, visualization?.activeId] ); + // setting that enables/disables SQL + const isSQLModeEnabled = uiSettings.get(ENABLE_SQL); + const supportedTextBasedLanguages = []; + if (isSQLModeEnabled) { + supportedTextBasedLanguages.push('SQL'); + } + const dataViewPickerProps = { trigger: { label: currentIndexPattern?.getName?.() || '', @@ -744,16 +804,42 @@ export const LensTopNavMenu = ({ onDataViewCreated: createNewDataView, adHocDataViews: indexPatterns.filter((pattern) => !pattern.isPersisted()), onChangeDataView: (newIndexPatternId: string) => { - const currentDataView = indexPatterns.find( + const currentDataView = dataViewsList.find( (indexPattern) => indexPattern.id === newIndexPatternId ); setCurrentIndexPattern(currentDataView); dispatchChangeIndexPattern(newIndexPatternId); + if (isOnTextBasedMode) { + dispatch( + switchAndCleanDatasource({ + newDatasourceId: 'indexpattern', + visualizationId: visualization?.activeId, + currentIndexPatternId: newIndexPatternId, + }) + ); + setIsOnTextBasedMode(false); + } }, + textBasedLanguages: supportedTextBasedLanguages as DataViewPickerProps['textBasedLanguages'], }; + // text based languages errors should also appear to the unified search bar + const textBasedLanguageModeErrors: Error[] = []; + if (activeDatasourceId && allLoaded) { + if ( + datasourceMap[activeDatasourceId] && + datasourceMap[activeDatasourceId].getUnifiedSearchErrors + ) { + const errors = datasourceMap[activeDatasourceId].getUnifiedSearchErrors?.( + datasourceStates[activeDatasourceId].state + ); + if (errors) { + textBasedLanguageModeErrors.push(...errors); + } + } + } return ( - boolean; persistedDoc?: Document; originatingApp?: string; + textBasedLanguageSave?: boolean; + switchDatasource?: () => void; } & ExtraProps & LensAppServices, saveProps: SaveProps, @@ -211,6 +213,9 @@ export const runSaveLensVisualization = async ( onAppLeave, redirectTo, dashboardFeatureFlag, + textBasedLanguageSave, + switchDatasource, + application, } = props; if (!lastKnownDoc) { @@ -318,8 +323,12 @@ export const runSaveLensVisualization = async ( // remove editor state so the connection is still broken after reload stateTransfer.clearEditorState?.(APP_ID); - - redirectTo?.(newInput.savedObjectId); + if (textBasedLanguageSave) { + switchDatasource?.(); + application.navigateToApp('lens', { path: '/' }); + } else { + redirectTo?.(newInput.savedObjectId); + } return { isLinkedToOriginatingApp: false }; } diff --git a/x-pack/plugins/lens/public/app_plugin/show_underlying_data.test.ts b/x-pack/plugins/lens/public/app_plugin/show_underlying_data.test.ts index 8a8c7bbe1f973..7030e58982ee5 100644 --- a/x-pack/plugins/lens/public/app_plugin/show_underlying_data.test.ts +++ b/x-pack/plugins/lens/public/app_plugin/show_underlying_data.test.ts @@ -81,6 +81,7 @@ describe('getLayerMetaInfo', () => { getSourceId: jest.fn(), getMaxPossibleNumValues: jest.fn(), getFilters: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }; mockDatasource.getPublicAPI.mockReturnValue(updatedPublicAPI); expect( @@ -99,6 +100,7 @@ describe('getLayerMetaInfo', () => { getSourceId: jest.fn(), getMaxPossibleNumValues: jest.fn(), getFilters: jest.fn(() => ({ error: 'filters error' })), + isTextBasedLanguage: jest.fn(() => false), }; mockDatasource.getPublicAPI.mockReturnValue(updatedPublicAPI); expect( @@ -158,6 +160,7 @@ describe('getLayerMetaInfo', () => { getVisualDefaults: jest.fn(), getSourceId: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), getFilters: jest.fn(() => ({ enabled: { kuery: [[{ language: 'kuery', query: 'memory > 40000' }]], diff --git a/x-pack/plugins/lens/public/app_plugin/show_underlying_data.ts b/x-pack/plugins/lens/public/app_plugin/show_underlying_data.ts index 0390b516bcd4a..d5c264c5ade0c 100644 --- a/x-pack/plugins/lens/public/app_plugin/show_underlying_data.ts +++ b/x-pack/plugins/lens/public/app_plugin/show_underlying_data.ts @@ -14,6 +14,7 @@ import { FilterStateStore, TimeRange, EsQueryConfig, + isOfQueryType, } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { RecursiveReadonly } from '@kbn/utility-types'; @@ -183,7 +184,7 @@ export function combineQueryAndFilters( lucene: [], }; - const allQueries = Array.isArray(query) ? query : query ? [query] : []; + const allQueries = Array.isArray(query) ? query : query && isOfQueryType(query) ? [query] : []; const nonEmptyQueries = allQueries.filter((q) => Boolean(q.query.trim())); [queries.lucene, queries.kuery] = partition(nonEmptyQueries, (q) => q.language === 'lucene'); diff --git a/x-pack/plugins/lens/public/app_plugin/types.ts b/x-pack/plugins/lens/public/app_plugin/types.ts index c57e580e1ad35..b2466c60e6e4e 100644 --- a/x-pack/plugins/lens/public/app_plugin/types.ts +++ b/x-pack/plugins/lens/public/app_plugin/types.ts @@ -119,6 +119,7 @@ export interface LensTopNavMenuProps { currentDoc: Document | undefined; theme$: Observable; indexPatternService: IndexPatternServiceAPI; + onTextBasedSavedAndExit: ({ onSave }: { onSave: () => void }) => Promise; } export interface HistoryLocationState { diff --git a/x-pack/plugins/lens/public/async_services.ts b/x-pack/plugins/lens/public/async_services.ts index 1740354de7880..c0ccd2a71ce2b 100644 --- a/x-pack/plugins/lens/public/async_services.ts +++ b/x-pack/plugins/lens/public/async_services.ts @@ -30,8 +30,10 @@ export * from './visualizations/gauge/gauge_visualization'; export * from './visualizations/gauge'; export * from './indexpattern_datasource/indexpattern'; +export { getTextBasedLanguagesDatasource } from './text_based_languages_datasource/text_based_languages'; export { createFormulaPublicApi } from './indexpattern_datasource/operations/definitions/formula/formula_public_api'; +export * from './text_based_languages_datasource'; export * from './indexpattern_datasource'; export * from './lens_ui_telemetry'; export * from './lens_ui_errors'; diff --git a/x-pack/plugins/lens/public/data_views_service/loader.ts b/x-pack/plugins/lens/public/data_views_service/loader.ts index d773f9c5ea509..9ffb99a54f403 100644 --- a/x-pack/plugins/lens/public/data_views_service/loader.ts +++ b/x-pack/plugins/lens/public/data_views_service/loader.ts @@ -42,6 +42,7 @@ export function convertDataViewIntoLensIndexPattern( displayName: field.displayName, type: field.type, aggregatable: field.aggregatable, + filterable: field.filterable, searchable: field.searchable, meta: dataView.metaFields.includes(field.name), esTypes: field.esTypes, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.test.tsx index 93d336b9445e6..102b1e3f2dd27 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.test.tsx @@ -7,6 +7,8 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; +import type { Query, AggregateQuery } from '@kbn/es-query'; + import { createMockFramePublicAPI, mockVisualizationMap, @@ -25,6 +27,7 @@ import { mountWithProvider } from '../../../mocks'; import { LayerType, layerTypes } from '../../../../common'; import { ReactWrapper } from 'enzyme'; import { addLayer } from '../../../state_management'; +import { AddLayerButton } from './add_layer'; import { createIndexPatternServiceMock } from '../../../mocks/data_views_service_mock'; jest.mock('../../../id_generator'); @@ -68,7 +71,8 @@ describe('ConfigPanel', () => { function prepareAndMountComponent( props: ReturnType, - customStoreProps?: Partial + customStoreProps?: Partial, + query?: Query | AggregateQuery ) { (generateId as jest.Mock).mockReturnValue(`newId`); return mountWithProvider( @@ -82,6 +86,7 @@ describe('ConfigPanel', () => { }, }, activeDatasourceId: 'testDatasource', + query: query as Query, }, storeDeps: mockStoreDeps({ datasourceMap: props.datasourceMap, @@ -466,4 +471,28 @@ describe('ConfigPanel', () => { expect(datasourceMap.testDatasource.initializeDimension).not.toHaveBeenCalled(); }); }); + + describe('text based languages', () => { + it('should not allow to add a new layer', async () => { + const datasourceMap = mockDatasourceMap(); + const visualizationMap = mockVisualizationMap(); + + visualizationMap.testVis.getSupportedLayers = jest.fn(() => [ + { type: layerTypes.DATA, label: 'Data Layer' }, + { + type: layerTypes.REFERENCELINE, + label: 'Reference layer', + }, + ]); + datasourceMap.testDatasource.initializeDimension = jest.fn(); + const props = getDefaultProps({ datasourceMap, visualizationMap }); + + const { instance } = await prepareAndMountComponent( + props, + {}, + { sql: 'SELECT * from "foo"' } + ); + expect(instance.find(AddLayerButton).exists()).toBe(false); + }); + }); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx index c410bce76626d..77005154fa4e2 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx @@ -8,6 +8,7 @@ import React, { useMemo, memo, useCallback } from 'react'; import { EuiForm } from '@elastic/eui'; import { ActionExecutionContext } from '@kbn/ui-actions-plugin/public'; +import { isOfAggregateQueryType } from '@kbn/es-query'; import { UPDATE_FILTER_REFERENCES_ACTION, UPDATE_FILTER_REFERENCES_TRIGGER, @@ -52,7 +53,7 @@ export function LayerPanels( } ) { const { activeVisualization, datasourceMap, indexPatternService } = props; - const { activeDatasourceId, visualization, datasourceStates } = useLensSelector( + const { activeDatasourceId, visualization, datasourceStates, query } = useLensSelector( (state) => state.lens ); @@ -185,6 +186,8 @@ export function LayerPanels( [dispatchLens, props.framePublicAPI.dataViews, props.indexPatternService] ); + const hideAddLayerButton = query && isOfAggregateQueryType(query); + return ( {layerIds.map((layerId, layerIndex) => ( @@ -264,16 +267,18 @@ export function LayerPanels( indexPatternService={indexPatternService} /> ))} - { - const layerId = generateId(); - dispatchLens(addLayer({ layerId, layerType })); - setNextFocusedLayerId(layerId); - }} - /> + {!hideAddLayerButton && ( + { + const layerId = generateId(); + dispatchLens(addLayer({ layerId, layerType })); + setNextFocusedLayerId(layerId); + }} + /> + )} ); } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/clone_layer_action.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/clone_layer_action.tsx index dbaa4aa0fd069..26d4c1f04f41a 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/clone_layer_action.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/clone_layer_action.tsx @@ -13,6 +13,7 @@ interface CloneLayerAction { execute: () => void; layerIndex: number; activeVisualization: Visualization; + isTextBasedLanguage?: boolean; } export const getCloneLayerAction = (props: CloneLayerAction): LayerAction => { @@ -23,7 +24,7 @@ export const getCloneLayerAction = (props: CloneLayerAction): LayerAction => { return { execute: props.execute, displayName, - isCompatible: Boolean(props.activeVisualization.cloneLayer), + isCompatible: Boolean(props.activeVisualization.cloneLayer && !props.isTextBasedLanguage), icon: 'copy', 'data-test-subj': `lnsLayerClone--${props.layerIndex}`, }; diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/layer_actions.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/layer_actions.tsx index 46abe207637a4..b9ca695882ef2 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/layer_actions.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_actions/layer_actions.tsx @@ -31,6 +31,7 @@ export interface LayerActionsProps { isOnlyLayer: boolean; activeVisualization: Visualization; layerType?: LayerType; + isTextBasedLanguage?: boolean; core: Pick; } @@ -111,6 +112,7 @@ export const LayerActions = (props: LayerActionsProps) => { execute: props.onCloneLayer, layerIndex: props.layerIndex, activeVisualization: props.activeVisualization, + isTextBasedLanguage: props.isTextBasedLanguage, }), getRemoveLayerAction({ execute: props.onRemoveLayer, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.test.tsx index baece355d1d54..74394e89f0d63 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.test.tsx @@ -243,7 +243,7 @@ describe('LayerPanel', () => { filterOperations: () => true, supportsMoreColumns: true, dataTestSubj: 'lnsGroup', - required: true, + requiredMinDimensionCount: 1, }, ], }); @@ -303,37 +303,83 @@ describe('LayerPanel', () => { expect(groups.findWhere((e) => e.prop('error') === '')).toHaveLength(1); }); - it('should render the required warning when only one group is configured (with requiredMinDimensionCount)', async () => { - mockVisualization.getConfiguration.mockReturnValue({ - groups: [ - { - groupLabel: 'A', - groupId: 'a', - accessors: [{ columnId: 'x' }], - filterOperations: () => true, - supportsMoreColumns: false, - dataTestSubj: 'lnsGroup', - }, - { - groupLabel: 'B', - groupId: 'b', - accessors: [{ columnId: 'y' }], - filterOperations: () => true, - supportsMoreColumns: true, - dataTestSubj: 'lnsGroup', - requiredMinDimensionCount: 2, - }, - ], - }); - - const { instance } = await mountWithProvider(); + it.each` + minDimensions | accessors | errors + ${1} | ${0} | ${1} + ${2} | ${0} | ${2} + ${2} | ${1} | ${2} + `( + 'should render the required warning for $errors fields when only one group is configured with requiredMinDimensionCount: $minDimensions and $accessors accessors', + async ({ minDimensions, accessors, errors }) => { + mockVisualization.getConfiguration.mockReturnValue({ + groups: [ + { + groupLabel: 'A', + groupId: 'a', + accessors: [{ columnId: 'x' }], + filterOperations: () => true, + supportsMoreColumns: false, + dataTestSubj: 'lnsGroup', + }, + { + groupLabel: 'B', + groupId: 'b', + accessors: [{ columnId: 'y' }].slice(0, accessors), + filterOperations: () => true, + supportsMoreColumns: true, + dataTestSubj: 'lnsGroup', + requiredMinDimensionCount: minDimensions, + }, + ], + }); + const { instance } = await mountWithProvider(); + + const errorMessage = errors === 1 ? 'Requires field' : 'Requires 2 fields'; + + const group = instance.find(EuiFormRow).findWhere((e) => e.prop('error') === errorMessage); + + expect(group).toHaveLength(1); + } + ); + + it.each` + minDimensions | accessors + ${0} | ${0} + ${0} | ${1} + ${1} | ${1} + ${1} | ${2} + ${2} | ${2} + `( + 'should not render the required warning when only one group is configured with requiredMinDimensionCount: $minDimensions and $accessors accessors', + async ({ minDimensions, accessors }) => { + mockVisualization.getConfiguration.mockReturnValue({ + groups: [ + { + groupLabel: 'A', + groupId: 'a', + accessors: [{ columnId: 'x' }], + filterOperations: () => true, + supportsMoreColumns: false, + dataTestSubj: 'lnsGroup', + }, + { + groupLabel: 'B', + groupId: 'b', + accessors: [{ columnId: 'y' }, { columnId: 'z' }].slice(0, accessors), + filterOperations: () => true, + supportsMoreColumns: true, + dataTestSubj: 'lnsGroup', + requiredMinDimensionCount: minDimensions, + }, + ], + }); + const { instance } = await mountWithProvider(); - const group = instance - .find(EuiFormRow) - .findWhere((e) => e.prop('error') === 'Requires 2 fields'); + const group = instance.find(EuiFormRow).findWhere((e) => e.prop('error')); - expect(group).toHaveLength(1); - }); + expect(group).toHaveLength(0); + } + ); it('should render the datasource and visualization panels inside the dimension container', async () => { mockVisualization.getConfiguration.mockReturnValueOnce({ 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 b3552c6fdf2e5..cc748df7c3ecd 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 @@ -307,6 +307,8 @@ export function LayerPanel( ); const { dataViews } = props.framePublicAPI; + const [datasource] = Object.values(framePublicAPI.datasourceLayers); + const isTextBasedLanguage = Boolean(datasource?.isTextBasedLanguage()); return ( <> @@ -337,6 +339,7 @@ export function LayerPanel( layerType={activeVisualization.getLayerType(layerId, visualizationState)} onRemoveLayer={onRemoveLayer} onCloneLayer={onCloneLayer} + isTextBasedLanguage={isTextBasedLanguage} core={core} /> @@ -378,20 +381,25 @@ export function LayerPanel( let errorText: string = ''; if (!isEmptyLayer) { - if (group.requiredMinDimensionCount) { - errorText = i18n.translate( - 'xpack.lens.editorFrame.requiresTwoOrMoreFieldsWarningLabel', - { - defaultMessage: 'Requires {requiredMinDimensionCount} fields', - values: { - requiredMinDimensionCount: group.requiredMinDimensionCount, - }, - } - ); - } else if (group.required && group.accessors.length === 0) { - errorText = i18n.translate('xpack.lens.editorFrame.requiresFieldWarningLabel', { - defaultMessage: 'Requires field', - }); + if ( + group.requiredMinDimensionCount && + group.requiredMinDimensionCount > group.accessors.length + ) { + if (group.requiredMinDimensionCount > 1) { + errorText = i18n.translate( + 'xpack.lens.editorFrame.requiresTwoOrMoreFieldsWarningLabel', + { + defaultMessage: 'Requires {requiredMinDimensionCount} fields', + values: { + requiredMinDimensionCount: group.requiredMinDimensionCount, + }, + } + ); + } else { + errorText = i18n.translate('xpack.lens.editorFrame.requiresFieldWarningLabel', { + defaultMessage: 'Requires field', + }); + } } else if (group.dimensionsTooMany && group.dimensionsTooMany > 0) { errorText = i18n.translate( 'xpack.lens.editorFrame.tooManyDimensionsSingularWarningLabel', @@ -405,7 +413,7 @@ export function LayerPanel( ); } } - const isOptional = !group.required && !group.suggestedValue; + const isOptional = !group.requiredMinDimensionCount && !group.suggestedValue; return ( { ], }; - const [showDatasourceSwitcher, setDatasourceSwitcher] = useState(false); - return ( <> - {Object.keys(props.datasourceMap).length > 1 && ( - setDatasourceSwitcher(true)} - iconType="gear" - /> - } - isOpen={showDatasourceSwitcher} - closePopover={() => setDatasourceSwitcher(false)} - panelPaddingSize="none" - anchorPosition="rightUp" - > - ( - { - setDatasourceSwitcher(false); - dispatchLens(switchDatasource({ newDatasourceId: datasourceId })); - }} - > - {datasourceId} - - ))} - /> - - )} {activeDatasourceId && !datasourceIsLoading && ( { getSourceId: jest.fn(), getFilters: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }; mockDatasource.getPublicAPI.mockReturnValue(updatedPublicAPI); @@ -498,41 +499,6 @@ describe('editor_frame', () => { instance.unmount(); }); - it('should initialize other datasource on switch', async () => { - await act(async () => { - instance.find('button[data-test-subj="datasource-switch"]').simulate('click'); - }); - await act(async () => { - ( - document.querySelector( - '[data-test-subj="datasource-switch-testDatasource2"]' - ) as HTMLButtonElement - ).click(); - }); - instance.update(); - expect(mockDatasource2.initialize).toHaveBeenCalled(); - }); - - it('should call datasource render with new state on switch', async () => { - const initialState = {}; - mockDatasource2.initialize.mockReturnValue(initialState); - - instance.find('button[data-test-subj="datasource-switch"]').simulate('click'); - - await act(async () => { - ( - document.querySelector( - '[data-test-subj="datasource-switch-testDatasource2"]' - ) as HTMLButtonElement - ).click(); - }); - - expect(mockDatasource2.renderDataPanel).toHaveBeenCalledWith( - expect.any(Element), - expect.objectContaining({ state: initialState }) - ); - }); - it('should initialize other visualization on switch', async () => { switchTo('testVis2'); expect(mockVisualization2.initialize).toHaveBeenCalled(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts index f1caa66ede1a2..c9b0358b81a0b 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts @@ -4,7 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - import { Ast, fromExpression } from '@kbn/interpreter'; import { DatasourceStates } from '../../state_management'; import { Visualization, DatasourceMap, DatasourceLayers, IndexPatternMap } from '../../types'; diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts index c886c21cfa6b8..1f0f6884d9719 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts @@ -13,7 +13,6 @@ import { difference } from 'lodash'; import type { DataViewsContract, DataViewSpec } from '@kbn/data-views-plugin/public'; import { IStorageWrapper } from '@kbn/kibana-utils-plugin/public'; import { DataViewPersistableStateService } from '@kbn/data-views-plugin/common'; -import { isAnnotationsLayer } from '@kbn/visualizations-plugin/common/convert_to_lens'; import { Datasource, DatasourceLayers, @@ -51,12 +50,7 @@ function getIndexPatterns( const indexPatternIds = []; if (initialContext) { if ('isVisualizeAction' in initialContext) { - for (const { indexPatternId } of initialContext.layers) { - indexPatternIds.push(indexPatternId); - } - for (const l of initialContext.configuration.layers) { - if (isAnnotationsLayer(l)) indexPatternIds.push(l.indexPatternId); - } + indexPatternIds.push(...initialContext.indexPatternIds); } else { indexPatternIds.push(initialContext.dataViewSpec.id!); } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.test.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.test.ts index 261a84751d663..a2f36f0754708 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.test.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.test.ts @@ -570,6 +570,7 @@ describe('suggestion helpers', () => { getSourceId: jest.fn(), getFilters: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }, }, { activeId: 'testVis', state: {} }, @@ -607,6 +608,7 @@ describe('suggestion helpers', () => { getSourceId: jest.fn(), getFilters: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }, }; defaultParams[3] = { @@ -669,6 +671,7 @@ describe('suggestion helpers', () => { getSourceId: jest.fn(), getFilters: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }, }; mockVisualization1.getSuggestions.mockReturnValue([]); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts index e362af10fd1f4..ec8eb224678b6 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts @@ -199,7 +199,8 @@ export function getVisualizeFieldSuggestions({ const allSuggestions = suggestions.filter( (s) => s.visualizationId === visualizeTriggerFieldContext.type ); - return activeVisualization?.getSuggestionFromConvertToLensContext?.({ + const visualization = visualizationMap[visualizeTriggerFieldContext.type] || null; + return visualization?.getSuggestionFromConvertToLensContext?.({ suggestions: allSuggestions, context: visualizeTriggerFieldContext, }); 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 2e81f9443ff15..dc09baf01fb2a 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 @@ -534,12 +534,8 @@ function getTopSuggestion( ); }); - // We prefer unchanged or reduced suggestions when switching - // charts since that allows you to switch from A to B and back - // to A with the greatest chance of preserving your original state. return ( - suggestions.find((s) => s.changeType === 'unchanged') || - suggestions.find((s) => s.changeType === 'reduced') || + suggestions.find((s) => s.changeType === 'unchanged' || s.changeType === 'reduced') || suggestions[0] ); } 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 8bf5fae85c73d..0a6d0391c15a1 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 @@ -196,12 +196,15 @@ export const InnerWorkspacePanel = React.memo(function InnerWorkspacePanel({ const onRender$ = useCallback(() => { if (renderDeps.current) { const datasourceEvents = Object.values(renderDeps.current.datasourceMap).reduce( - (acc, datasource) => [ - ...acc, - ...(datasource.getRenderEventCounters?.( - renderDeps.current!.datasourceStates[datasource.id].state - ) ?? []), - ], + (acc, datasource) => { + if (!renderDeps.current!.datasourceStates[datasource.id]) return []; + return [ + ...acc, + ...(datasource.getRenderEventCounters?.( + renderDeps.current!.datasourceStates[datasource.id]?.state + ) ?? []), + ]; + }, [] ); let visualizationEvents: string[] = []; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx index 9acec09776207..1ce184e623e7a 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx @@ -310,15 +310,15 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ const currentIndexPattern = indexPatterns[currentIndexPatternId]; const existingFieldsForIndexPattern = existingFields[currentIndexPattern?.title]; const visualizeGeoFieldTrigger = uiActions.getTrigger(VISUALIZE_GEO_FIELD_TRIGGER); - const allFields = useMemo( - () => - visualizeGeoFieldTrigger - ? currentIndexPattern.fields - : currentIndexPattern.fields.filter( - ({ type }) => type !== 'geo_point' && type !== 'geo_shape' - ), - [currentIndexPattern.fields, visualizeGeoFieldTrigger] - ); + const allFields = useMemo(() => { + if (!currentIndexPattern) return []; + return visualizeGeoFieldTrigger + ? currentIndexPattern.fields + : currentIndexPattern.fields.filter( + ({ type }) => type !== 'geo_point' && type !== 'geo_shape' + ); + }, [currentIndexPattern, visualizeGeoFieldTrigger]); + const clearLocalState = () => setLocalState((s) => ({ ...s, nameFilter: '', typeFilter: [] })); const availableFieldTypes = uniq([ ...uniq(allFields.map(getFieldType)).filter((type) => type in fieldTypeNames), @@ -327,13 +327,13 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ ]); const fieldInfoUnavailable = - existenceFetchFailed || existenceFetchTimeout || currentIndexPattern.hasRestrictions; + existenceFetchFailed || existenceFetchTimeout || currentIndexPattern?.hasRestrictions; const editPermission = indexPatternFieldEditor.userPermissions.editIndexPattern(); const unfilteredFieldGroups: FieldGroups = useMemo(() => { const containsData = (field: IndexPatternField) => { - const overallField = currentIndexPattern.getFieldByName(field.name); + const overallField = currentIndexPattern?.getFieldByName(field.name); return ( overallField && existingFieldsForIndexPattern && @@ -503,22 +503,24 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ }, []); const refreshFieldList = useCallback(async () => { - const newlyMappedIndexPattern = await indexPatternService.loadIndexPatterns({ - patterns: [currentIndexPattern.id], - cache: {}, - onIndexPatternRefresh, - }); - indexPatternService.updateDataViewsState({ - indexPatterns: { - ...frame.dataViews.indexPatterns, - [currentIndexPattern.id]: newlyMappedIndexPattern[currentIndexPattern.id], - }, - }); + if (currentIndexPattern) { + const newlyMappedIndexPattern = await indexPatternService.loadIndexPatterns({ + patterns: [currentIndexPattern.id], + cache: {}, + onIndexPatternRefresh, + }); + indexPatternService.updateDataViewsState({ + indexPatterns: { + ...frame.dataViews.indexPatterns, + [currentIndexPattern.id]: newlyMappedIndexPattern[currentIndexPattern.id], + }, + }); + } // start a new session so all charts are refreshed data.search.session.start(); }, [ indexPatternService, - currentIndexPattern.id, + currentIndexPattern, onIndexPatternRefresh, frame.dataViews.indexPatterns, data.search.session, @@ -528,7 +530,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ () => editPermission ? async (fieldName?: string, uiAction: 'edit' | 'add' = 'edit') => { - const indexPatternInstance = await dataViews.get(currentIndexPattern.id); + const indexPatternInstance = await dataViews.get(currentIndexPattern?.id); closeFieldEditor.current = indexPatternFieldEditor.openEditor({ ctx: { dataView: indexPatternInstance, @@ -547,7 +549,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ [ editPermission, dataViews, - currentIndexPattern.id, + currentIndexPattern?.id, indexPatternFieldEditor, refreshFieldList, indexPatternService, @@ -558,7 +560,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ () => editPermission ? async (fieldName: string) => { - const indexPatternInstance = await dataViews.get(currentIndexPattern.id); + const indexPatternInstance = await dataViews.get(currentIndexPattern?.id); closeFieldEditor.current = indexPatternFieldEditor.openDeleteModal({ ctx: { dataView: indexPatternInstance, @@ -575,7 +577,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ } : undefined, [ - currentIndexPattern.id, + currentIndexPattern?.id, dataViews, editPermission, indexPatternFieldEditor, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.test.ts new file mode 100644 index 0000000000000..eb98d7411491c --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.test.ts @@ -0,0 +1,108 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + buildExpression, + ExpressionAstExpressionBuilder, + parseExpression, +} from '@kbn/expressions-plugin/common'; +import { dedupeAggs } from './dedupe_aggs'; +import { operationDefinitionMap } from './operations'; +import { OriginalColumn } from './to_expression'; + +describe('dedupeAggs', () => { + const buildMapsFromAggBuilders = (aggs: ExpressionAstExpressionBuilder[]) => { + const esAggsIdMap: Record = {}; + const aggsToIdsMap = new Map(); + aggs.forEach((builder, i) => { + const esAggsId = `col-${i}-${i}`; + esAggsIdMap[esAggsId] = [{ id: `original-${i}` } as OriginalColumn]; + aggsToIdsMap.set(builder, esAggsId); + }); + return { + esAggsIdMap, + aggsToIdsMap, + }; + }; + + it('removes duplicate aggregations', () => { + const aggs = [ + 'aggSum id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false', + 'aggSum id="1" enabled=true schema="metric" field="bytes" emptyAsNull=false', + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="hour_of_day: *"}} \n customMetric={aggTopMetrics id="2-metric" enabled=true schema="metric" field="hour_of_day" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="3" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="hour_of_day: *"}} \n customMetric={aggTopMetrics id="3-metric" enabled=true schema="metric" field="hour_of_day" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggAvg id="4" enabled=true schema="metric" field="bytes"', + 'aggAvg id="5" enabled=true schema="metric" field="bytes"', + ].map((expression) => buildExpression(parseExpression(expression))); + + const { esAggsIdMap, aggsToIdsMap } = buildMapsFromAggBuilders(aggs); + + // eslint-disable-next-line @typescript-eslint/naming-convention + const { sum, last_value, average } = operationDefinitionMap; + + const operations = [sum, last_value, average]; + + operations.forEach((op) => expect(op.getGroupByKey).toBeDefined()); + + const { esAggsIdMap: newIdMap, aggs: newAggs } = dedupeAggs( + aggs, + esAggsIdMap, + aggsToIdsMap, + operations + ); + + expect(newAggs).toHaveLength(3); + + expect(newIdMap).toMatchInlineSnapshot(` + Object { + "col-0-0": Array [ + Object { + "id": "original-0", + }, + Object { + "id": "original-1", + }, + ], + "col-2-2": Array [ + Object { + "id": "original-2", + }, + Object { + "id": "original-3", + }, + ], + "col-4-4": Array [ + Object { + "id": "original-4", + }, + Object { + "id": "original-5", + }, + ], + } + `); + }); + + it('should update any terms order-by reference', () => { + const aggs = [ + 'aggTerms id="0" enabled=true schema="segment" field="clientip" orderBy="3" order="desc" size=5 includeIsRegex=false excludeIsRegex=false otherBucket=true otherBucketLabel="Other" missingBucket=false missingBucketLabel="(missing value)"', + 'aggMedian id="1" enabled=true schema="metric" field="bytes"', + 'aggMedian id="2" enabled=true schema="metric" field="bytes"', + 'aggMedian id="3" enabled=true schema="metric" field="bytes"', + ].map((expression) => buildExpression(parseExpression(expression))); + + const { esAggsIdMap, aggsToIdsMap } = buildMapsFromAggBuilders(aggs); + + const { aggs: newAggs } = dedupeAggs(aggs, esAggsIdMap, aggsToIdsMap, [ + operationDefinitionMap.median, + ]); + + expect(newAggs).toHaveLength(2); + + expect(newAggs[0].functions[0].getArgument('orderBy')?.[0]).toBe('1'); + }); +}); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.ts b/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.ts new file mode 100644 index 0000000000000..ce5b2b0f41f23 --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dedupe_aggs.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { AggFunctionsMapping } from '@kbn/data-plugin/public'; +import { + ExpressionAstExpressionBuilder, + ExpressionAstFunctionBuilder, +} from '@kbn/expressions-plugin/common'; +import { GenericOperationDefinition } from './operations'; +import { extractAggId, OriginalColumn } from './to_expression'; + +function groupByKey(items: T[], getKey: (item: T) => string | undefined): Record { + const groups: Record = {}; + + items.forEach((item) => { + const key = getKey(item); + if (key) { + if (!(key in groups)) { + groups[key] = []; + } + groups[key].push(item); + } + }); + + return groups; +} + +/** + * Consolidates duplicate agg expression builders to increase performance + */ +export function dedupeAggs( + _aggs: ExpressionAstExpressionBuilder[], + _esAggsIdMap: Record, + aggExpressionToEsAggsIdMap: Map, + allOperations: GenericOperationDefinition[] +): { + aggs: ExpressionAstExpressionBuilder[]; + esAggsIdMap: Record; +} { + let aggs = [..._aggs]; + const esAggsIdMap = { ..._esAggsIdMap }; + + const aggsByArgs = groupByKey(aggs, (expressionBuilder) => { + for (const operation of allOperations) { + const groupKey = operation.getGroupByKey?.(expressionBuilder); + if (groupKey) { + return `${operation.type}-${groupKey}`; + } + } + }); + + const termsFuncs = aggs + .map((agg) => agg.functions[0]) + .filter((func) => func.name === 'aggTerms') as Array< + ExpressionAstFunctionBuilder + >; + + // collapse each group into a single agg expression builder + Object.values(aggsByArgs).forEach((expressionBuilders) => { + if (expressionBuilders.length <= 1) { + // don't need to optimize if there aren't more than one + return; + } + + const [firstExpressionBuilder, ...restExpressionBuilders] = expressionBuilders; + + // throw away all but the first expression builder + aggs = aggs.filter((aggBuilder) => !restExpressionBuilders.includes(aggBuilder)); + + const firstEsAggsId = aggExpressionToEsAggsIdMap.get(firstExpressionBuilder); + if (firstEsAggsId === undefined) { + throw new Error('Could not find current column ID for expression builder'); + } + + restExpressionBuilders.forEach((expressionBuilder) => { + const currentEsAggsId = aggExpressionToEsAggsIdMap.get(expressionBuilder); + if (currentEsAggsId === undefined) { + throw new Error('Could not find current column ID for expression builder'); + } + + esAggsIdMap[firstEsAggsId].push(...esAggsIdMap[currentEsAggsId]); + + delete esAggsIdMap[currentEsAggsId]; + + termsFuncs.forEach((func) => { + if (func.getArgument('orderBy')?.[0] === extractAggId(currentEsAggsId)) { + func.replaceArgument('orderBy', [extractAggId(firstEsAggsId)]); + } + }); + }); + }); + + return { aggs, esAggsIdMap }; +} diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx index fbd9a5650013d..5a975482e6250 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx @@ -20,6 +20,11 @@ import { useEuiTheme, EuiFlexGroup, EuiFlexItem, + EuiPopover, + EuiPopoverTitle, + EuiPanel, + EuiBasicTable, + EuiButtonIcon, } from '@elastic/eui'; import ReactDOM from 'react-dom'; import type { IndexPatternDimensionEditorProps } from './dimension_panel'; @@ -116,6 +121,10 @@ export function DimensionEditor(props: DimensionEditorProps) { selectedColumn && operationDefinitionMap[selectedColumn.operationType]; const [temporaryState, setTemporaryState] = useState('none'); + const [isHelpOpen, setIsHelpOpen] = useState(false); + + const onHelpClick = () => setIsHelpOpen((prevIsHelpOpen) => !prevIsHelpOpen); + const closeHelp = () => setIsHelpOpen(false); const temporaryQuickFunction = Boolean(temporaryState === quickFunctionsName); const temporaryStaticValue = Boolean(temporaryState === staticValueOperationName); @@ -596,12 +605,88 @@ export function DimensionEditor(props: DimensionEditorProps) { ...services, }; + const helpButton = ; + + const columnsSidebar = [ + { + field: 'function', + name: i18n.translate('xpack.lens.indexPattern.functionTable.functionHeader', { + defaultMessage: 'Function', + }), + width: '150px', + }, + { + field: 'description', + name: i18n.translate('xpack.lens.indexPattern.functionTable.descriptionHeader', { + defaultMessage: 'Description', + }), + }, + ]; + + const items = sideNavItems + .filter((item) => operationDefinitionMap[item.id!].quickFunctionDocumentation) + .map((item) => { + const operationDefinition = operationDefinitionMap[item.id!]!; + return { + id: item.id!, + function: operationDefinition.displayName, + description: operationDefinition.quickFunctionDocumentation!, + }; + }); + const quickFunctions = ( <> + + + + {i18n.translate('xpack.lens.indexPattern.quickFunctions.popoverTitle', { + defaultMessage: 'Quick functions', + })} + + + + + + + + {i18n.translate('xpack.lens.indexPattern.functionsLabel', { + defaultMessage: 'Functions', + })} + + + } fullWidth > { await wrapper.update(); const popoverContent = wrapper.find(EuiPopover).prop('children'); act(() => { - mountWithIntl(popoverContent as ReactElement) + mountWithIntl( + + {popoverContent as ReactElement} + + ) .find('[data-test-subj="lnsFieldListPanelEdit"]') .first() .simulate('click'); @@ -215,12 +219,45 @@ describe('IndexPattern Field Item', () => { await wrapper.update(); const popoverContent = wrapper.find(EuiPopover).prop('children'); expect( - mountWithIntl(popoverContent as ReactElement) + mountWithIntl( + + {popoverContent as ReactElement} + + ) .find('[data-test-subj="lnsFieldListPanelEdit"]') .exists() ).toBeFalsy(); }); + it('should pass add filter callback and pass result to filter manager', async () => { + const field = { + name: 'test', + displayName: 'testLabel', + type: 'string', + aggregatable: true, + searchable: true, + filterable: true, + }; + + const editFieldSpy = jest.fn(); + const wrapper = mountWithIntl( + + ); + await clickField(wrapper, field.name); + await wrapper.update(); + const popoverContent = wrapper.find(EuiPopover).prop('children'); + const instance = mountWithIntl( + + {popoverContent as ReactElement} + + ); + const onAddFilter = instance.find(FieldStats).prop('onAddFilter'); + onAddFilter!(field as DataViewField, 'abc', '+'); + expect(mockedServices.data.query.filterManager.addFilters).toHaveBeenCalledWith([ + expect.objectContaining({ query: { match_phrase: { test: 'abc' } } }), + ]); + }); + it('should request field stats every time the button is clicked', async () => { let resolveFunction: (arg: unknown) => void; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx index bae8db55a9d46..29f666a4ff6eb 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx @@ -29,7 +29,8 @@ import { Filter, Query } from '@kbn/es-query'; import { DataViewField } from '@kbn/data-views-plugin/common'; import { ChartsPluginSetup } from '@kbn/charts-plugin/public'; import { UiActionsStart } from '@kbn/ui-actions-plugin/public'; -import { FieldStats } from '@kbn/unified-field-list-plugin/public'; +import { AddFieldFilterHandler, FieldStats } from '@kbn/unified-field-list-plugin/public'; +import { generateFilters } from '@kbn/data-plugin/public'; import { DragDrop, DragDropIdentifier } from '../drag_drop'; import { DatasourceDataPanelProps, DataType } from '../types'; import { DOCUMENT_FIELD_NAME } from '../../common'; @@ -320,6 +321,21 @@ function FieldItemPopoverContents(props: FieldItemProps) { } = props; const services = useKibana().services; + const onAddFilter: AddFieldFilterHandler = useCallback( + (clickedField, values, operation) => { + const filterManager = services.data.query.filterManager; + const newFilters = generateFilters( + filterManager, + clickedField, + values, + operation, + indexPattern + ); + filterManager.addFilters(newFilters); + }, + [indexPattern, services.data.query.filterManager] + ); + const panelHeader = ( { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.test.ts index c19338dd156f0..aefb4c7327463 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.test.ts @@ -1220,138 +1220,261 @@ describe('IndexPattern Data Source', () => { expect(ast.chain[1].arguments.timeFields).not.toContain('timefield'); }); - it('should call optimizeEsAggs once per operation for which it is available', () => { - const queryBaseState: IndexPatternPrivateState = { - currentIndexPatternId: '1', - layers: { - first: { - indexPatternId: '1', - columns: { - col1: { - label: 'timestamp', - dataType: 'date', - operationType: 'date_histogram', - sourceField: 'timestamp', - isBucketed: true, - scale: 'interval', - params: { - interval: 'auto', - includeEmptyRows: true, - dropPartials: false, - }, - } as DateHistogramIndexPatternColumn, - col2: { - label: '95th percentile of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { - percentile: 95, + describe('optimizations', () => { + it('should call optimizeEsAggs once per operation for which it is available', () => { + const queryBaseState: IndexPatternPrivateState = { + currentIndexPatternId: '1', + layers: { + first: { + indexPatternId: '1', + columns: { + col1: { + label: 'timestamp', + dataType: 'date', + operationType: 'date_histogram', + sourceField: 'timestamp', + isBucketed: true, + scale: 'interval', + params: { + interval: 'auto', + includeEmptyRows: true, + dropPartials: false, + }, + } as DateHistogramIndexPatternColumn, + col2: { + label: '95th percentile of bytes', + dataType: 'number', + operationType: 'percentile', + sourceField: 'bytes', + isBucketed: false, + scale: 'ratio', + params: { + percentile: 95, + }, + } as PercentileIndexPatternColumn, + col3: { + label: '95th percentile of bytes', + dataType: 'number', + operationType: 'percentile', + sourceField: 'bytes', + isBucketed: false, + scale: 'ratio', + params: { + percentile: 95, + }, + } as PercentileIndexPatternColumn, + }, + columnOrder: ['col1', 'col2', 'col3'], + incompleteColumns: {}, + }, + }, + }; + + const optimizeMock = jest.spyOn(operationDefinitionMap.percentile, 'optimizeEsAggs'); + + indexPatternDatasource.toExpression(queryBaseState, 'first', indexPatterns); + + expect(operationDefinitionMap.percentile.optimizeEsAggs).toHaveBeenCalledTimes(1); + + optimizeMock.mockRestore(); + }); + + it('should update anticipated esAggs column IDs based on the order of the optimized agg expression builders', () => { + const queryBaseState: IndexPatternPrivateState = { + currentIndexPatternId: '1', + layers: { + first: { + indexPatternId: '1', + columns: { + col1: { + label: 'timestamp', + dataType: 'date', + operationType: 'date_histogram', + sourceField: 'timestamp', + isBucketed: true, + scale: 'interval', + params: { + interval: 'auto', + includeEmptyRows: true, + dropPartials: false, + }, + } as DateHistogramIndexPatternColumn, + col2: { + label: '95th percentile of bytes', + dataType: 'number', + operationType: 'percentile', + sourceField: 'bytes', + isBucketed: false, + scale: 'ratio', + params: { + percentile: 95, + }, + } as PercentileIndexPatternColumn, + col3: { + label: 'Count of records', + dataType: 'number', + isBucketed: false, + sourceField: '___records___', + operationType: 'count', + timeScale: 'h', }, - } as PercentileIndexPatternColumn, - col3: { - label: '95th percentile of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { - percentile: 95, + col4: { + label: 'Count of records2', + dataType: 'number', + isBucketed: false, + sourceField: 'bytes', + operationType: 'count', + timeScale: 'h', }, - } as PercentileIndexPatternColumn, + }, + columnOrder: ['col1', 'col2', 'col3', 'col4'], + incompleteColumns: {}, }, - columnOrder: ['col1', 'col2', 'col3'], - incompleteColumns: {}, }, - }, - }; + }; - const optimizeMock = jest.spyOn(operationDefinitionMap.percentile, 'optimizeEsAggs'); + const optimizeMock = jest + .spyOn(operationDefinitionMap.percentile, 'optimizeEsAggs') + .mockImplementation((aggs, esAggsIdMap) => { + // change the order of the aggregations + return { aggs: aggs.reverse(), esAggsIdMap }; + }); - indexPatternDatasource.toExpression(queryBaseState, 'first', indexPatterns); + const ast = indexPatternDatasource.toExpression( + queryBaseState, + 'first', + indexPatterns + ) as Ast; - expect(operationDefinitionMap.percentile.optimizeEsAggs).toHaveBeenCalledTimes(1); + expect(operationDefinitionMap.percentile.optimizeEsAggs).toHaveBeenCalledTimes(1); - optimizeMock.mockRestore(); - }); + const idMap = JSON.parse(ast.chain[2].arguments.idMap as unknown as string); - it('should update anticipated esAggs column IDs based on the order of the optimized agg expression builders', () => { - const queryBaseState: IndexPatternPrivateState = { - currentIndexPatternId: '1', - layers: { - first: { - indexPatternId: '1', - columns: { - col1: { - label: 'timestamp', - dataType: 'date', - operationType: 'date_histogram', - sourceField: 'timestamp', - isBucketed: true, - scale: 'interval', - params: { - interval: 'auto', - includeEmptyRows: true, - dropPartials: false, + expect(Object.keys(idMap)).toEqual(['col-0-3', 'col-1-2', 'col-2-1', 'col-3-0']); + + optimizeMock.mockRestore(); + }); + + it('should deduplicate aggs for supported operations', () => { + const queryBaseState: IndexPatternPrivateState = { + currentIndexPatternId: '1', + layers: { + first: { + indexPatternId: '1', + columns: { + col1: { + label: 'My Op', + dataType: 'string', + isBucketed: true, + operationType: 'terms', + sourceField: 'op', + params: { + size: 5, + orderBy: { + type: 'column', + columnId: 'col4', // col4 will disappear + }, + orderDirection: 'asc', + }, + } as TermsIndexPatternColumn, + col2: { + label: 'Count of records', + dataType: 'number', + isBucketed: false, + sourceField: '___records___', + operationType: 'count', + timeScale: 'h', }, - } as DateHistogramIndexPatternColumn, - col2: { - label: '95th percentile of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { - percentile: 95, + col3: { + label: 'Count of records', + dataType: 'number', + isBucketed: false, + sourceField: '___records___', + operationType: 'count', + timeScale: 'h', + }, + col4: { + label: 'Count of records', + dataType: 'number', + isBucketed: false, + sourceField: '___records___', + operationType: 'count', + timeScale: 'h', }, - } as PercentileIndexPatternColumn, - col3: { - label: 'Count of records', - dataType: 'number', - isBucketed: false, - sourceField: '___records___', - operationType: 'count', - timeScale: 'h', - }, - col4: { - label: 'Count of records2', - dataType: 'number', - isBucketed: false, - sourceField: '___records___', - operationType: 'count', - timeScale: 'h', }, + columnOrder: ['col1', 'col2', 'col3', 'col4'], + incompleteColumns: {}, }, - columnOrder: ['col1', 'col2', 'col3', 'col4'], - incompleteColumns: {}, }, - }, - }; + }; - const optimizeMock = jest - .spyOn(operationDefinitionMap.percentile, 'optimizeEsAggs') - .mockImplementation((aggs, esAggsIdMap) => { - // change the order of the aggregations - return { aggs: aggs.reverse(), esAggsIdMap }; - }); + const ast = indexPatternDatasource.toExpression( + queryBaseState, + 'first', + indexPatterns + ) as Ast; - const ast = indexPatternDatasource.toExpression( - queryBaseState, - 'first', - indexPatterns - ) as Ast; + const idMap = JSON.parse(ast.chain[2].arguments.idMap as unknown as string); - expect(operationDefinitionMap.percentile.optimizeEsAggs).toHaveBeenCalledTimes(1); + const aggs = ast.chain[1].arguments.aggs; - const idMap = JSON.parse(ast.chain[2].arguments.idMap as unknown as string); + expect(aggs).toHaveLength(2); - expect(Object.keys(idMap)).toEqual(['col-0-3', 'col-1-2', 'col-2-1', 'col-3-0']); + // orderby reference updated + expect((aggs[0] as Ast).chain[0].arguments.orderBy[0]).toBe('1'); - optimizeMock.mockRestore(); + expect(idMap).toMatchInlineSnapshot(` + Object { + "col-0-0": Array [ + Object { + "dataType": "string", + "id": "col1", + "isBucketed": true, + "label": "My Op", + "operationType": "terms", + "params": Object { + "orderBy": Object { + "columnId": "col4", + "type": "column", + }, + "orderDirection": "asc", + "size": 5, + }, + "sourceField": "op", + }, + ], + "col-1-1": Array [ + Object { + "dataType": "number", + "id": "col2", + "isBucketed": false, + "label": "Count of records", + "operationType": "count", + "sourceField": "___records___", + "timeScale": "h", + }, + Object { + "dataType": "number", + "id": "col3", + "isBucketed": false, + "label": "Count of records", + "operationType": "count", + "sourceField": "___records___", + "timeScale": "h", + }, + Object { + "dataType": "number", + "id": "col4", + "isBucketed": false, + "label": "Count of records", + "operationType": "count", + "sourceField": "___records___", + "timeScale": "h", + }, + ], + } + `); + }); }); describe('references', () => { @@ -1595,6 +1718,15 @@ describe('IndexPattern Data Source', () => { }); }); + describe('#createEmptyLayer', () => { + it('creates state with empty layers', () => { + expect(indexPatternDatasource.createEmptyLayer('index-pattern-id')).toEqual({ + currentIndexPatternId: 'index-pattern-id', + layers: {}, + }); + }); + }); + describe('#getLayers', () => { it('should list the current layers', () => { expect( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx index 1fcec0b6509bf..20d0df1358be7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx @@ -190,6 +190,13 @@ export function getIndexPatternDatasource({ }; }, + createEmptyLayer(indexPatternId: string) { + return { + currentIndexPatternId: indexPatternId, + layers: {}, + }; + }, + cloneLayer(state, layerId, newLayerId, getNewId) { return { ...state, @@ -218,7 +225,7 @@ export function getIndexPatternDatasource({ }, getLayers(state: IndexPatternPrivateState) { - return Object.keys(state.layers); + return Object.keys(state?.layers); }, removeColumn({ prevState, layerId, columnId, indexPatterns }) { @@ -314,7 +321,6 @@ export function getIndexPatternDatasource({ counts[uniqueLabel] = 0; return uniqueLabel; }; - Object.values(layers).forEach((layer) => { if (!layer.columns) { return; @@ -500,7 +506,7 @@ export function getIndexPatternDatasource({ filter: false, }; const operations = flatten( - Object.values(state.layers ?? {}).map((l) => + Object.values(state?.layers ?? {}).map((l) => Object.values(l.columns).map((c) => { if (c.timeShift) { additionalEvents.time_shift = true; @@ -568,6 +574,7 @@ export function getIndexPatternDatasource({ fields: [...new Set(fieldsPerColumn[colId] || [])], })); }, + isTextBasedLanguage: () => false, getOperationForColumnId: (columnId: string) => { if (layer && layer.columns[columnId]) { if (!isReferenced(layer, columnId)) { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx index 860c272d9ee19..382c11bda545a 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx @@ -1774,7 +1774,7 @@ describe('IndexPattern Data Source suggestions', () => { state: expect.objectContaining({ layers: { test: expect.objectContaining({ - columnOrder: ['column-id-3', 'column-id-2', 'column-id-1'], + columnOrder: ['column-id-2', 'column-id-3', 'column-id-1'], columns: { 'column-id-1': expect.objectContaining({ operationType: 'count', @@ -1804,10 +1804,10 @@ describe('IndexPattern Data Source suggestions', () => { isMultiRow: true, columns: [ expect.objectContaining({ - columnId: 'column-id-3', + columnId: 'column-id-2', }), expect.objectContaining({ - columnId: 'column-id-2', + columnId: 'column-id-3', }), expect.objectContaining({ columnId: 'column-id-1', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts index fed70d2970b1e..8503c369f4ec2 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts @@ -341,6 +341,7 @@ function createNewLayerWithMetricAggregationFromVizEditor( newLayer = insertNewColumn({ ...column, layer: newLayer, + respectOrder: true, }); } }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx index 674eac8194e41..f2c421946bafb 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx @@ -151,5 +151,13 @@ Example: Visualize the rate of bytes received over time by a memcached server: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.counterRate.documentation.quick', + { + defaultMessage: ` + The rate of change over time for an ever growing time series metric. + `, + } + ), shiftable: true, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx index 11e1da98b0ca0..67260672fa66d 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx @@ -147,5 +147,13 @@ Example: Visualize the received bytes accumulated over time: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.cumulativeSum.documentation.quick', + { + defaultMessage: ` + The sum of all values as they grow over time. + `, + } + ), shiftable: true, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx index 6873377bd437e..1d76667654cb3 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx @@ -135,5 +135,13 @@ Example: Visualize the change in bytes received over time: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.differences.documentation.quick', + { + defaultMessage: ` + The change between the values in subsequent intervals. + `, + } + ), shiftable: true, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx index 3876623b53611..0fbdd96153a0f 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx @@ -166,6 +166,14 @@ Example: Smooth a line of measurements: }, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.movingAverage.documentation.quick', + { + defaultMessage: ` + The average of a moving window of values over time. + `, + } + ), shiftable: true, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.test.ts new file mode 100644 index 0000000000000..10d26cc3dbbd2 --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.test.ts @@ -0,0 +1,111 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { buildExpression, parseExpression } from '@kbn/expressions-plugin/common'; +import { operationDefinitionMap } from '.'; + +describe('unique values function', () => { + describe('getGroupByKey', () => { + const getKey = operationDefinitionMap.unique_count.getGroupByKey!; + const expressionToKey = (expression: string) => + getKey(buildExpression(parseExpression(expression))) as string; + describe('generates unique keys based on configuration', () => { + const keys = [ + // group 1 + [ + 'aggCardinality id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false', + 'aggCardinality id="1" enabled=true schema="metric" field="bytes" emptyAsNull=false', + ], + // group 2 + [ + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggCardinality id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="3" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggCardinality id="3-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + // group 3 + [ + 'aggFilteredMetric id="4" enabled=true schema="metric" \n customBucket={aggFilter id="4-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggCardinality id="4-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="5" enabled=true schema="metric" \n customBucket={aggFilter id="5-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggCardinality id="5-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + // group 4 + [ + 'aggFilteredMetric id="6" enabled=true schema="metric" \n customBucket={aggFilter id="6-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggCardinality id="6-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="7" enabled=true schema="metric" \n customBucket={aggFilter id="7-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggCardinality id="7-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + // group 5 + [ + 'aggFilteredMetric id="8" enabled=true schema="metric" \n customBucket={aggFilter id="8-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggCardinality id="8-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="9" enabled=true schema="metric" \n customBucket={aggFilter id="9-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggCardinality id="9-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + // check emptyAsNull cases + [ + 'aggCardinality id="10" enabled=true schema="metric" field="bytes" emptyAsNull=true', + 'aggCardinality id="11" enabled=true schema="metric" field="bytes" emptyAsNull=true', + ], + [ + 'aggFilteredMetric id="12" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggCardinality id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=true}', + 'aggFilteredMetric id="13" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggCardinality id="3-metric" enabled=true schema="metric" field="bytes" emptyAsNull=true}', + ], + ].map((group) => group.map(expressionToKey)); + + it.each(keys.map((group, i) => ({ group })))('%#', ({ group: thisGroup }) => { + expect(thisGroup[0]).toEqual(thisGroup[1]); + const otherGroups = keys.filter((group) => group !== thisGroup); + for (const otherGroup of otherGroups) { + expect(thisGroup[0]).not.toEqual(otherGroup[0]); + } + }); + + it('snapshot', () => { + expect(keys).toMatchInlineSnapshot(` + Array [ + Array [ + "aggCardinality-bytes-false-undefined", + "aggCardinality-bytes-false-undefined", + ], + Array [ + "aggCardinality-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggCardinality-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + Array [ + "aggCardinality-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + "aggCardinality-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggCardinality-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + "aggCardinality-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + ], + Array [ + "aggCardinality-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + "aggCardinality-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggCardinality-bytes-true-undefined", + "aggCardinality-bytes-true-undefined", + ], + Array [ + "aggCardinality-filtered-bytes-true-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggCardinality-filtered-bytes-true-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + ] + `); + }); + }); + + it('returns undefined for aggs from different operation classes', () => { + expect( + expressionToKey( + 'aggSum id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false' + ) + ).toBeUndefined(); + expect( + expressionToKey( + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}' + ) + ).toBeUndefined(); + }); + }); +}); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx index 44474fba14dac..04b11885c016e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx @@ -26,6 +26,7 @@ import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { updateColumnParam } from '../layer_helpers'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; +import { getGroupByKey } from './get_group_by_key'; const supportedTypes = new Set([ 'string', @@ -186,6 +187,13 @@ export const cardinalityOperation: OperationDefinition< emptyAsNull: column.params?.emptyAsNull, }).toAst(); }, + getGroupByKey: (agg) => { + return getGroupByKey( + agg, + ['aggCardinality'], + [{ name: 'field' }, { name: 'emptyAsNull', transformer: (val) => String(Boolean(val)) }] + ); + }, onFieldChange: (oldColumn, field) => { return { ...oldColumn, @@ -210,4 +218,12 @@ Example: Calculate the number of different products from the "clothes" group: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.cardinality.documentation.quick', + { + defaultMessage: ` +The number of unique values for a specified number, string, date, or boolean field. + `, + } + ), }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.test.ts new file mode 100644 index 0000000000000..9f89834548837 --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { buildExpression, parseExpression } from '@kbn/expressions-plugin/common'; +import { operationDefinitionMap } from '.'; + +describe('count operation', () => { + describe('getGroupByKey', () => { + const getKey = operationDefinitionMap.count.getGroupByKey!; + const expressionToKey = (expression: string) => + getKey(buildExpression(parseExpression(expression))) as string; + + describe('generates unique keys based on configuration', () => { + const keys = [ + [ + 'aggValueCount id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false', + 'aggValueCount id="1" enabled=true schema="metric" field="bytes" emptyAsNull=false', + ], + [ + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggValueCount id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="3" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggValueCount id="3-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="4" enabled=true schema="metric" \n customBucket={aggFilter id="4-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggValueCount id="4-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="5" enabled=true schema="metric" \n customBucket={aggFilter id="5-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggValueCount id="5-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="6" enabled=true schema="metric" \n customBucket={aggFilter id="6-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggValueCount id="6-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="7" enabled=true schema="metric" \n customBucket={aggFilter id="7-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggValueCount id="7-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="8" enabled=true schema="metric" \n customBucket={aggFilter id="8-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggValueCount id="8-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="9" enabled=true schema="metric" \n customBucket={aggFilter id="9-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggValueCount id="9-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggCount id="10" enabled=true schema="metric" emptyAsNull=true', + 'aggCount id="11" enabled=true schema="metric" emptyAsNull=true', + ], + [ + 'aggCount id="10" enabled=true schema="metric" emptyAsNull=false', + 'aggCount id="11" enabled=true schema="metric" emptyAsNull=false', + ], + [ + 'aggValueCount id="12" enabled=true schema="metric" field="agent.keyword" emptyAsNull=false', + 'aggValueCount id="13" enabled=true schema="metric" field="agent.keyword" emptyAsNull=false', + ], + [ + 'aggValueCount id="12" enabled=true schema="metric" field="agent.keyword" emptyAsNull=true', + 'aggValueCount id="13" enabled=true schema="metric" field="agent.keyword" emptyAsNull=true', + ], + ].map((group) => group.map(expressionToKey)); + + it.each(keys.map((group, i) => ({ group })))('%#', ({ group: thisGroup }) => { + expect(thisGroup[0]).toEqual(thisGroup[1]); + const otherGroups = keys.filter((group) => group !== thisGroup); + for (const otherGroup of otherGroups) { + expect(thisGroup[0]).not.toEqual(otherGroup[0]); + } + }); + + it('snapshot', () => { + expect(keys).toMatchInlineSnapshot(` + Array [ + Array [ + "aggValueCount-bytes-false-undefined", + "aggValueCount-bytes-false-undefined", + ], + Array [ + "aggValueCount-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggValueCount-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + Array [ + "aggValueCount-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + "aggValueCount-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggValueCount-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + "aggValueCount-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + ], + Array [ + "aggValueCount-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + "aggValueCount-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggCount-undefined-true-undefined", + "aggCount-undefined-true-undefined", + ], + Array [ + "aggCount-undefined-false-undefined", + "aggCount-undefined-false-undefined", + ], + Array [ + "aggValueCount-agent.keyword-false-undefined", + "aggValueCount-agent.keyword-false-undefined", + ], + Array [ + "aggValueCount-agent.keyword-true-undefined", + "aggValueCount-agent.keyword-true-undefined", + ], + ] + `); + }); + }); + + it('returns undefined for aggs from different operation classes', () => { + expect( + expressionToKey( + 'aggSum id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false' + ) + ).toBeUndefined(); + expect( + expressionToKey( + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}' + ) + ).toBeUndefined(); + }); + }); +}); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx index e2eedc5a2d3c6..b911ac5394a23 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx @@ -26,6 +26,7 @@ import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { updateColumnParam } from '../layer_helpers'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; +import { getGroupByKey } from './get_group_by_key'; const countLabel = i18n.translate('xpack.lens.indexPattern.countOf', { defaultMessage: 'Count of records', @@ -206,6 +207,14 @@ export const countOperation: OperationDefinition { + return getGroupByKey( + agg, + ['aggCount', 'aggValueCount'], + [{ name: 'field' }, { name: 'emptyAsNull', transformer: (val) => String(Boolean(val)) }] + ); + }, + isTransferable: (column, newIndexPattern) => { const newField = newIndexPattern.getFieldByName(column.sourceField); @@ -239,5 +248,10 @@ To calculate the number of documents that match a specific filter, use \`count(k `, }), }, + quickFunctionDocumentation: i18n.translate('xpack.lens.indexPattern.count.documentation.quick', { + defaultMessage: ` +The total number of documents. When you provide a field, the total number of field values is counted. Use the count function for fields that have multiple values in a single document. + `, + }), shiftable: true, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx index 40b2f66b2b93d..8d6b201b2cc19 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx @@ -75,7 +75,7 @@ function getMultipleDateHistogramsErrorMessage(layer: IndexPatternLayer, columnI export const dateHistogramOperation: OperationDefinition< DateHistogramIndexPatternColumn, 'field', - { interval: string; dropPartials?: boolean } + { interval: string; dropPartials?: boolean; includeEmptyRows?: boolean } > = { type: 'date_histogram', displayName: i18n.translate('xpack.lens.indexPattern.dateHistogram', { @@ -116,7 +116,7 @@ export const dateHistogramOperation: OperationDefinition< scale: 'interval', params: { interval: columnParams?.interval ?? autoInterval, - includeEmptyRows: true, + includeEmptyRows: columnParams?.includeEmptyRows ?? true, dropPartials: Boolean(columnParams?.dropPartials), }, }; @@ -515,6 +515,14 @@ export const dateHistogramOperation: OperationDefinition< ); }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.dateHistogram.documentation.quick', + { + defaultMessage: ` +The date or date range values distributed into intervals. + `, + } + ), }; function parseInterval(currentInterval: string) { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx index da06ea8ae1bf4..b972129109e1e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx @@ -158,6 +158,14 @@ export const filtersOperation: OperationDefinition< }, getMaxPossibleNumValues: (column) => column.params.filters.length, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.filters.documentation.quick', + { + defaultMessage: ` + Divides values into predefined subsets. + `, + } + ), }; export const FilterList = ({ diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/get_group_by_key.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/get_group_by_key.ts new file mode 100644 index 0000000000000..92bcfdb2e7450 --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/get_group_by_key.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + AggFunctionsMapping, + ExpressionFunctionKql, + ExpressionFunctionLucene, +} from '@kbn/data-plugin/public'; +import { + AnyExpressionFunctionDefinition, + ExpressionAstExpressionBuilder, + ExpressionAstFunctionBuilder, +} from '@kbn/expressions-plugin/common'; +import { Primitive } from 'utility-types'; + +/** + * Computes a group-by key for an agg expression builder based on distinctive expression function arguments + */ +export const getGroupByKey = ( + agg: ExpressionAstExpressionBuilder, + aggNames: string[], + importantExpressionArgs: Array<{ name: string; transformer?: (value: Primitive) => string }> +) => { + const { + functions: [fnBuilder], + } = agg; + + const pieces = []; + + if (aggNames.includes(fnBuilder.name)) { + pieces.push(fnBuilder.name); + + importantExpressionArgs.forEach(({ name, transformer }) => { + const arg = fnBuilder.getArgument(name)?.[0]; + pieces.push(transformer ? transformer(arg) : arg); + }); + + pieces.push(fnBuilder.getArgument('timeShift')?.[0]); + } + + if (fnBuilder.name === 'aggFilteredMetric') { + const metricFnBuilder = fnBuilder.getArgument('customMetric')?.[0].functions[0] as + | ExpressionAstFunctionBuilder + | undefined; + + if (metricFnBuilder && aggNames.includes(metricFnBuilder.name)) { + pieces.push(metricFnBuilder.name); + pieces.push('filtered'); + + const aggFilterFnBuilder = ( + fnBuilder.getArgument('customBucket')?.[0] as ExpressionAstExpressionBuilder + ).functions[0] as ExpressionAstFunctionBuilder; + + importantExpressionArgs.forEach(({ name, transformer }) => { + const arg = metricFnBuilder.getArgument(name)?.[0]; + pieces.push(transformer ? transformer(arg) : arg); + }); + + pieces.push(aggFilterFnBuilder.getArgument('timeWindow')); + pieces.push(fnBuilder.getArgument('timeShift')); + + const filterExpression = aggFilterFnBuilder.getArgument('filter')?.[0] as + | ExpressionAstExpressionBuilder + | undefined; + + if (filterExpression) { + const filterFnBuilder = filterExpression.functions[0] as + | ExpressionAstFunctionBuilder + | undefined; + + pieces.push(filterFnBuilder?.name, filterFnBuilder?.getArgument('q')?.[0]); + } + } + } + + return pieces.length ? pieces.map(String).join('-') : undefined; +}; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts index 31292218078e2..6c79d314d10fa 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts @@ -364,6 +364,7 @@ interface BaseOperationDefinitionProps< description: string; section: 'elasticsearch' | 'calculation'; }; + quickFunctionDocumentation?: string; /** * React component for operation field specific behaviour */ @@ -408,6 +409,29 @@ interface BaseOperationDefinitionProps< * Title for the help component */ helpComponentTitle?: string; + + /** + * Used to remove duplicate aggregations for performance reasons. + * + * This method should return a key only if the provided agg is generated by this particular operation. + * The key should represent the important configurations of the operation, such that + * + * const column1 = ...; + * const column2 = ...; // different configuration! + * + * const agg1 = operation.toEsAggsFn(column1); + * const agg2 = operation.toEsAggsFn(column1); + * const agg3 = operation.toEsAggsFn(column2); + * + * const key1 = operation.getGroupByKey(agg1); + * const key2 = operation.getGroupByKey(agg2); + * const key3 = operation.getGroupByKey(agg3); + * + * key1 === key2 + * key1 !== key3 + */ + getGroupByKey?: (agg: ExpressionAstExpressionBuilder) => string | undefined; + /** * Optimizes EsAggs expression. Invoked only once per operation type. */ diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.test.tsx index df219c1e851be..05386492544f4 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.test.tsx @@ -21,6 +21,7 @@ import type { IndexPatternLayer } from '../../types'; import type { IndexPattern } from '../../../types'; import { TermsIndexPatternColumn } from './terms'; import { EuiSwitch, EuiSwitchEvent } from '@elastic/eui'; +import { buildExpression, parseExpression } from '@kbn/expressions-plugin/common'; const uiSettingsMock = {} as IUiSettingsClient; @@ -917,4 +918,108 @@ describe('last_value', () => { ]); }); }); + + describe('getGroupByKey', () => { + const getKey = lastValueOperation.getGroupByKey!; + const expressionToKey = (expression: string) => + getKey(buildExpression(parseExpression(expression))); + + describe('collapses duplicate aggs', () => { + const keys = [ + [ + 'aggFilteredMetric id="0" enabled=true schema="metric" \n customBucket={aggFilter id="0-filter" enabled=true schema="bucket" filter={kql q="bytes: *"}} \n customMetric={aggTopMetrics id="0-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="1" enabled=true schema="metric" \n customBucket={aggFilter id="1-filter" enabled=true schema="bucket" filter={kql q="bytes: *"}} \n customMetric={aggTopMetrics id="1-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + ], + [ + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="machine.ram: *"}} \n customMetric={aggTopMetrics id="2-metric" enabled=true schema="metric" field="machine.ram" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="3" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="machine.ram: *"}} \n customMetric={aggTopMetrics id="3-metric" enabled=true schema="metric" field="machine.ram" size=1 sortOrder="desc" sortField="timestamp"}', + ], + [ + 'aggFilteredMetric id="4" enabled=true schema="metric" \n customBucket={aggFilter id="4-filter" enabled=true schema="bucket" filter={kql q="machine.ram: *"} timeShift="1h"} \n customMetric={aggTopMetrics id="4-metric" enabled=true schema="metric" field="machine.ram" size=1 sortOrder="desc" sortField="timestamp"} timeShift="1h"', + 'aggFilteredMetric id="5" enabled=true schema="metric" \n customBucket={aggFilter id="5-filter" enabled=true schema="bucket" filter={kql q="machine.ram: *"} timeShift="1h"} \n customMetric={aggTopMetrics id="5-metric" enabled=true schema="metric" field="machine.ram" size=1 sortOrder="desc" sortField="timestamp"} timeShift="1h"', + ], + [ + 'aggFilteredMetric id="6" enabled=true schema="metric" \n customBucket={aggFilter id="6-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggTopMetrics id="6-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="7" enabled=true schema="metric" \n customBucket={aggFilter id="7-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggTopMetrics id="7-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + ], + [ + 'aggFilteredMetric id="8" enabled=true schema="metric" \n customBucket={aggFilter id="8-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggTopMetrics id="8-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="9" enabled=true schema="metric" \n customBucket={aggFilter id="9-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggTopMetrics id="9-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + ], + [ + 'aggFilteredMetric id="10" enabled=true schema="metric" \n customBucket={aggFilter id="10-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggTopMetrics id="10-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="11" enabled=true schema="metric" \n customBucket={aggFilter id="11-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggTopMetrics id="11-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + ], + [ + 'aggFilteredMetric id="12" enabled=true schema="metric" \n customBucket={aggFilter id="12-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggTopMetrics id="12-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + 'aggFilteredMetric id="13" enabled=true schema="metric" \n customBucket={aggFilter id="13-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggTopMetrics id="13-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp"}', + ], + // uses aggTopHit + [ + 'aggFilteredMetric id="14" enabled=true schema="metric" \n customBucket={aggFilter id="14-filter" enabled=true schema="bucket" filter={kql q="bytes: *"}} \n customMetric={aggTopHit id="14-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp" aggregate="concat"}', + 'aggFilteredMetric id="15" enabled=true schema="metric" \n customBucket={aggFilter id="15-filter" enabled=true schema="bucket" filter={kql q="bytes: *"}} \n customMetric={aggTopHit id="15-metric" enabled=true schema="metric" field="bytes" size=1 sortOrder="desc" sortField="timestamp" aggregate="concat"}', + ], + ].map((group) => group.map(expressionToKey)); + + it.each(keys.map((group, i) => ({ group })))('%#', ({ group: thisGroup }) => { + expect(thisGroup[0]).toEqual(thisGroup[1]); + const otherGroups = keys.filter((group) => group !== thisGroup); + for (const otherGroup of otherGroups) { + expect(thisGroup[0]).not.toEqual(otherGroup[0]); + } + }); + + it('snapshot', () => { + expect(keys).toMatchInlineSnapshot(` + Array [ + Array [ + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-bytes: *", + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-bytes: *", + ], + Array [ + "aggTopMetrics-filtered-machine.ram-timestamp-undefined-undefined-kql-machine.ram: *", + "aggTopMetrics-filtered-machine.ram-timestamp-undefined-undefined-kql-machine.ram: *", + ], + Array [ + "aggTopMetrics-filtered-machine.ram-timestamp-undefined-1h-kql-machine.ram: *", + "aggTopMetrics-filtered-machine.ram-timestamp-undefined-1h-kql-machine.ram: *", + ], + Array [ + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + Array [ + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-geo.dest: \\"AL\\" ", + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + "aggTopMetrics-filtered-bytes-timestamp-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + ], + Array [ + "aggTopMetrics-filtered-bytes-timestamp-1m-undefined-kql-geo.dest: \\"AL\\" ", + "aggTopMetrics-filtered-bytes-timestamp-1m-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggTopHit-filtered-bytes-timestamp-undefined-undefined-kql-bytes: *", + "aggTopHit-filtered-bytes-timestamp-undefined-undefined-kql-bytes: *", + ], + ] + `); + }); + }); + + it('returns undefined for aggs from different operation classes', () => { + expect( + expressionToKey( + 'aggSum id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false' + ) + ).toBeUndefined(); + expect( + expressionToKey( + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}' + ) + ).toBeUndefined(); + }); + }); }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.tsx index b7fd3a40fdbff..4206cd8109760 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/last_value.tsx @@ -33,6 +33,7 @@ import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { isScriptedField } from './terms/helpers'; import { FormRow } from './shared_components/form_row'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; +import { getGroupByKey } from './get_group_by_key'; function ofName(name: string, timeShift: string | undefined, reducedTimeRange: string | undefined) { return adjustTimeScaleLabelSuffix( @@ -258,6 +259,14 @@ export const lastValueOperation: OperationDefinition< ).toAst(); }, + getGroupByKey: (agg) => { + return getGroupByKey( + agg, + ['aggTopHit', 'aggTopMetrics'], + [{ name: 'field' }, { name: 'sortField' }] + ); + }, + isTransferable: (column, newIndexPattern) => { const newField = newIndexPattern.getFieldByName(column.sourceField); const newTimeField = newIndexPattern.getFieldByName(column.params.sortField); @@ -419,4 +428,12 @@ Example: Get the current status of server A: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.lastValue.documentation.quick', + { + defaultMessage: ` +The value of a field from the last document, ordered by the default time field of the data view. + `, + } + ), }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.test.ts new file mode 100644 index 0000000000000..b98125d0bbd2b --- /dev/null +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.test.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { buildExpression, parseExpression } from '@kbn/expressions-plugin/common'; +import { operationDefinitionMap } from '.'; + +const sumOperation = operationDefinitionMap.sum; + +describe('metrics', () => { + describe('getGroupByKey', () => { + const getKey = sumOperation.getGroupByKey!; + const expressionToKey = (expression: string) => + getKey(buildExpression(parseExpression(expression))); + + describe('should collapse filtered aggs with matching parameters', () => { + const keys = [ + [ + 'aggSum id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false', + 'aggSum id="1" enabled=true schema="metric" field="bytes" emptyAsNull=false', + ], + [ + 'aggSum id="2" enabled=true schema="metric" field="bytes" emptyAsNull=true', + 'aggSum id="3" enabled=true schema="metric" field="bytes" emptyAsNull=true', + ], + [ + 'aggSum id="4" enabled=true schema="metric" field="hour_of_day" emptyAsNull=false', + 'aggSum id="5" enabled=true schema="metric" field="hour_of_day" emptyAsNull=false', + ], + [ + 'aggSum id="6" enabled=true schema="metric" field="machine.ram" timeShift="1h" emptyAsNull=false', + 'aggSum id="7" enabled=true schema="metric" field="machine.ram" timeShift="1h" emptyAsNull=false', + ], + [ + 'aggSum id="8" enabled=true schema="metric" field="machine.ram" timeShift="2h" emptyAsNull=false', + 'aggSum id="9" enabled=true schema="metric" field="machine.ram" timeShift="2h" emptyAsNull=false', + ], + [ + 'aggFilteredMetric id="10" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=true}', + 'aggFilteredMetric id="11" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="3-metric" enabled=true schema="metric" field="bytes" emptyAsNull=true}', + ], + [ + 'aggFilteredMetric id="12" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="13" enabled=true schema="metric" \n customBucket={aggFilter id="3-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggSum id="3-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="14" enabled=true schema="metric" \n customBucket={aggFilter id="4-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggSum id="4-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="15" enabled=true schema="metric" \n customBucket={aggFilter id="5-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "}} \n customMetric={aggSum id="5-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="16" enabled=true schema="metric" \n customBucket={aggFilter id="6-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggSum id="6-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="17" enabled=true schema="metric" \n customBucket={aggFilter id="7-filter" enabled=true schema="bucket" filter={lucene q="\\"geo.dest: \\\\\\"AL\\\\\\" \\""}} \n customMetric={aggSum id="7-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + [ + 'aggFilteredMetric id="18" enabled=true schema="metric" \n customBucket={aggFilter id="8-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggSum id="8-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + 'aggFilteredMetric id="19" enabled=true schema="metric" \n customBucket={aggFilter id="9-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"AL\\" "} timeWindow="1m"} \n customMetric={aggSum id="9-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}', + ], + ].map((group) => group.map(expressionToKey)); + + it.each(keys.map((group, i) => ({ group })))('%#', ({ group: thisGroup }) => { + expect(thisGroup[0]).toEqual(thisGroup[1]); + const otherGroups = keys.filter((group) => group !== thisGroup); + for (const otherGroup of otherGroups) { + expect(thisGroup[0]).not.toEqual(otherGroup[0]); + } + }); + + it('snapshot', () => { + expect(keys).toMatchInlineSnapshot(` + Array [ + Array [ + "aggSum-bytes-false-undefined", + "aggSum-bytes-false-undefined", + ], + Array [ + "aggSum-bytes-true-undefined", + "aggSum-bytes-true-undefined", + ], + Array [ + "aggSum-hour_of_day-false-undefined", + "aggSum-hour_of_day-false-undefined", + ], + Array [ + "aggSum-machine.ram-false-1h", + "aggSum-machine.ram-false-1h", + ], + Array [ + "aggSum-machine.ram-false-2h", + "aggSum-machine.ram-false-2h", + ], + Array [ + "aggSum-filtered-bytes-true-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggSum-filtered-bytes-true-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + Array [ + "aggSum-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + "aggSum-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"GA\\" ", + ], + Array [ + "aggSum-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + "aggSum-filtered-bytes-false-undefined-undefined-kql-geo.dest: \\"AL\\" ", + ], + Array [ + "aggSum-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + "aggSum-filtered-bytes-false-undefined-undefined-lucene-\\"geo.dest: \\\\\\"AL\\\\\\" \\"", + ], + Array [ + "aggSum-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + "aggSum-filtered-bytes-false-1m-undefined-kql-geo.dest: \\"AL\\" ", + ], + ] + `); + }); + }); + + it('returns undefined for aggs from different operation classes', () => { + expect( + expressionToKey( + 'aggCardinality id="0" enabled=true schema="metric" field="bytes" emptyAsNull=false' + ) + ).toBeUndefined(); + expect( + expressionToKey( + 'aggFilteredMetric id="2" enabled=true schema="metric" \n customBucket={aggFilter id="2-filter" enabled=true schema="bucket" filter={kql q="geo.dest: \\"GA\\" "}} \n customMetric={aggCardinality id="2-metric" enabled=true schema="metric" field="bytes" emptyAsNull=false}' + ) + ).toBeUndefined(); + }); + }); +}); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx index 9b8f790e51b90..e8c8c54c1cefe 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx @@ -28,6 +28,7 @@ import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { updateColumnParam } from '../layer_helpers'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; +import { getGroupByKey } from './get_group_by_key'; type MetricColumn = FieldBasedIndexPatternColumn & { operationType: T; @@ -59,6 +60,7 @@ function buildMetricOperation>({ hideZeroOption, aggConfigParams, documentationDescription, + quickFunctionDocumentation, }: { type: T['operationType']; displayName: string; @@ -70,6 +72,7 @@ function buildMetricOperation>({ hideZeroOption?: boolean; aggConfigParams?: Record; documentationDescription?: string; + quickFunctionDocumentation?: string; }) { const labelLookup = (name: string, column?: BaseIndexPatternColumn) => { const label = ofName(name); @@ -198,6 +201,14 @@ function buildMetricOperation>({ ...aggConfigParams, }).toAst(); }, + getGroupByKey: (agg) => { + return getGroupByKey( + agg, + [typeToFn[type]], + [{ name: 'field' }, { name: 'emptyAsNull', transformer: (val) => String(Boolean(val)) }] + ); + }, + getErrorMessage: (layer, columnId, indexPattern) => combineErrorMessages([ getInvalidFieldMessage( @@ -231,6 +242,7 @@ Example: Get the {metric} of price for orders from the UK: }, }), }, + quickFunctionDocumentation, shiftable: true, } as OperationDefinition; } @@ -256,6 +268,12 @@ export const minOperation = buildMetricOperation({ defaultMessage: 'A single-value metrics aggregation that returns the minimum value among the numeric values extracted from the aggregated documents.', }), + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.min.quickFunctionDescription', + { + defaultMessage: 'The minimum value of a number field.', + } + ), supportsDate: true, }); @@ -273,6 +291,12 @@ export const maxOperation = buildMetricOperation({ defaultMessage: 'A single-value metrics aggregation that returns the maximum value among the numeric values extracted from the aggregated documents.', }), + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.max.quickFunctionDescription', + { + defaultMessage: 'The maximum value of a number field.', + } + ), supportsDate: true, }); @@ -291,6 +315,12 @@ export const averageOperation = buildMetricOperation({ defaultMessage: 'A single-value metric aggregation that computes the average of numeric values that are extracted from the aggregated documents', }), + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.avg.quickFunctionDescription', + { + defaultMessage: 'The average value of a number field.', + } + ), }); export const standardDeviationOperation = buildMetricOperation( @@ -325,6 +355,13 @@ To get the variance of price for orders from the UK, use \`square(standard_devia `, } ), + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.standardDeviation.quickFunctionDescription', + { + defaultMessage: + 'The standard deviation of the values of a number field which is the amount of variation of the fields values.', + } + ), } ); @@ -345,6 +382,12 @@ export const sumOperation = buildMetricOperation({ 'A single-value metrics aggregation that sums up numeric values that are extracted from the aggregated documents.', }), hideZeroOption: true, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.sum.quickFunctionDescription', + { + defaultMessage: 'The total amount of the values of a number field.', + } + ), }); export const medianOperation = buildMetricOperation({ @@ -362,4 +405,10 @@ export const medianOperation = buildMetricOperation({ defaultMessage: 'A single-value metrics aggregation that computes the median value that are extracted from the aggregated documents.', }), + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.median.quickFunctionDescription', + { + defaultMessage: 'The median value of a number field.', + } + ), }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.test.tsx index f72342f79bfc6..77434d7ecc7ad 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.test.tsx @@ -28,6 +28,7 @@ import { } from '@kbn/expressions-plugin/public'; import type { OriginalColumn } from '../../to_expression'; import { IndexPattern } from '../../../types'; +import faker from 'faker'; jest.mock('lodash', () => { const original = jest.requireActual('lodash'); @@ -234,7 +235,7 @@ describe('percentile', () => { const aggs = [ // group 1 makeEsAggBuilder('aggSinglePercentile', { - id: 1, + id: '1', enabled: true, schema: 'metric', field: field1, @@ -242,7 +243,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 2, + id: '2', enabled: true, schema: 'metric', field: field1, @@ -250,7 +251,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 3, + id: '3', enabled: true, schema: 'metric', field: field1, @@ -259,7 +260,7 @@ describe('percentile', () => { }), // group 2 makeEsAggBuilder('aggSinglePercentile', { - id: 4, + id: '4', enabled: true, schema: 'metric', field: field2, @@ -267,7 +268,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 5, + id: '5', enabled: true, schema: 'metric', field: field2, @@ -276,7 +277,7 @@ describe('percentile', () => { }), // group 3 makeEsAggBuilder('aggSinglePercentile', { - id: 6, + id: '6', enabled: true, schema: 'metric', field: field2, @@ -284,7 +285,7 @@ describe('percentile', () => { timeShift: timeShift1, }), makeEsAggBuilder('aggSinglePercentile', { - id: 7, + id: '7', enabled: true, schema: 'metric', field: field2, @@ -293,7 +294,7 @@ describe('percentile', () => { }), // group 4 makeEsAggBuilder('aggSinglePercentile', { - id: 8, + id: '8', enabled: true, schema: 'metric', field: field2, @@ -301,7 +302,7 @@ describe('percentile', () => { timeShift: timeShift2, }), makeEsAggBuilder('aggSinglePercentile', { - id: 9, + id: '9', enabled: true, schema: 'metric', field: field2, @@ -344,7 +345,7 @@ describe('percentile', () => { "foo", ], "id": Array [ - 1, + "1", ], "percents": Array [ 10, @@ -381,7 +382,7 @@ describe('percentile', () => { "bar", ], "id": Array [ - 4, + "4", ], "percents": Array [ 10, @@ -417,7 +418,7 @@ describe('percentile', () => { "bar", ], "id": Array [ - 6, + "6", ], "percents": Array [ 50, @@ -456,7 +457,7 @@ describe('percentile', () => { "bar", ], "id": Array [ - 8, + "8", ], "percents": Array [ 70, @@ -544,7 +545,7 @@ describe('percentile', () => { const aggs = [ // group 1 makeEsAggBuilder('aggSinglePercentile', { - id: 1, + id: '1', enabled: true, schema: 'metric', field: field1, @@ -552,7 +553,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 2, + id: '2', enabled: true, schema: 'metric', field: field1, @@ -560,7 +561,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 4, + id: '4', enabled: true, schema: 'metric', field: field2, @@ -568,7 +569,7 @@ describe('percentile', () => { timeShift: undefined, }), makeEsAggBuilder('aggSinglePercentile', { - id: 3, + id: '3', enabled: true, schema: 'metric', field: field1, @@ -609,17 +610,87 @@ describe('percentile', () => { `); }); + it('should update order-by references for any terms columns', () => { + const field1 = 'foo'; + const field2 = 'bar'; + const percentile = faker.random.number(100); + + const aggs = [ + makeEsAggBuilder('aggTerms', { + id: '1', + enabled: true, + schema: 'metric', + field: field1, + orderBy: '4', + timeShift: undefined, + }), + makeEsAggBuilder('aggTerms', { + id: '2', + enabled: true, + schema: 'metric', + field: field1, + orderBy: '6', + timeShift: undefined, + }), + makeEsAggBuilder('aggSinglePercentile', { + id: '3', + enabled: true, + schema: 'metric', + field: field1, + percentile, + timeShift: undefined, + }), + makeEsAggBuilder('aggSinglePercentile', { + id: '4', + enabled: true, + schema: 'metric', + field: field1, + percentile, + timeShift: undefined, + }), + makeEsAggBuilder('aggSinglePercentile', { + id: '5', + enabled: true, + schema: 'metric', + field: field2, + percentile, + timeShift: undefined, + }), + makeEsAggBuilder('aggSinglePercentile', { + id: '6', + enabled: true, + schema: 'metric', + field: field2, + percentile, + timeShift: undefined, + }), + ]; + + const { esAggsIdMap, aggsToIdsMap } = buildMapsFromAggBuilders(aggs); + + const { aggs: newAggs } = percentileOperation.optimizeEsAggs!( + aggs, + esAggsIdMap, + aggsToIdsMap + ); + + expect(newAggs.length).toBe(4); + + expect(newAggs[0].functions[0].getArgument('orderBy')?.[0]).toBe(`3.${percentile}`); + expect(newAggs[1].functions[0].getArgument('orderBy')?.[0]).toBe(`5.${percentile}`); + }); + it("shouldn't touch non-percentile aggs or single percentiles with no siblings", () => { const aggs = [ makeEsAggBuilder('aggSinglePercentile', { - id: 1, + id: '1', enabled: true, schema: 'metric', field: 'foo', percentile: 30, }), makeEsAggBuilder('aggMax', { - id: 1, + id: '1', enabled: true, schema: 'metric', field: 'bar', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx index 88b941b2bb7c9..ec4a3d569e7da 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx @@ -13,6 +13,7 @@ import { buildExpression, buildExpressionFunction, ExpressionAstExpressionBuilder, + ExpressionAstFunctionBuilder, } from '@kbn/expressions-plugin/public'; import { AggExpressionFunctionArgs } from '@kbn/data-plugin/common'; import { OperationDefinition } from '.'; @@ -195,6 +196,12 @@ export const percentileOperation: OperationDefinition< } }); + const termsFuncs = aggs + .map((agg) => agg.functions[0]) + .filter((func) => func.name === 'aggTerms') as Array< + ExpressionAstFunctionBuilder + >; + // collapse them into a single esAggs expression builder Object.values(percentileExpressionsByArgs).forEach((expressionBuilders) => { if (expressionBuilders.length <= 1) { @@ -224,6 +231,7 @@ export const percentileOperation: OperationDefinition< const percentileToBuilder: Record = {}; for (const builder of expressionBuilders) { const percentile = builder.functions[0].getArgument('percentile')![0] as number; + if (percentile in percentileToBuilder) { // found a duplicate percentile so let's optimize @@ -248,6 +256,13 @@ export const percentileOperation: OperationDefinition< percentileToBuilder[percentile] = builder; aggPercentilesConfig.percents!.push(percentile); } + + // update any terms order-bys + termsFuncs.forEach((func) => { + if (func.getArgument('orderBy')?.[0] === builder.functions[0].getArgument('id')?.[0]) { + func.replaceArgument('orderBy', [`${esAggsColumnId}.${percentile}`]); + } + }); } const multiPercentilesAst = buildExpressionFunction( @@ -402,4 +417,12 @@ Example: Get the number of bytes larger than 95 % of values: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.percentile.documentation.quick', + { + defaultMessage: ` + The largest value that is smaller than n percent of the values that occur in all documents. + `, + } + ), }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile_ranks.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile_ranks.tsx index 7cb8d7ea64aea..45bd05f37372f 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile_ranks.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile_ranks.tsx @@ -266,4 +266,12 @@ Example: Get the percentage of values which are below of 100: `, }), }, + quickFunctionDocumentation: i18n.translate( + 'xpack.lens.indexPattern.percentileRanks.documentation.quick', + { + defaultMessage: ` +The percentage of values that are below a specific value. For example, when a value is greater than or equal to 95% of the calculated values, the value is the 95th percentile rank. + `, + } + ), }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx index 3efbafcd572b0..52c9471aefe0e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx @@ -103,13 +103,14 @@ export const rangeOperation: OperationDefinition< defaultMessage: 'Missing field', }), buildColumn({ field }, columnParams) { + const type = columnParams?.type ?? MODES.Histogram; return { label: field.displayName, - dataType: 'number', // string for Range + dataType: type === MODES.Histogram ? 'number' : 'string', // string for Range operationType: 'range', sourceField: field.name, isBucketed: true, - scale: 'interval', // ordinal for Range + scale: type === MODES.Histogram ? 'interval' : 'ordinal', // ordinal for Range params: { includeEmptyRows: columnParams?.includeEmptyRows ?? true, type: columnParams?.type ?? MODES.Histogram, @@ -266,4 +267,9 @@ export const rangeOperation: OperationDefinition< /> ); }, + quickFunctionDocumentation: i18n.translate('xpack.lens.indexPattern.ranges.documentation.quick', { + defaultMessage: ` + Buckets values along defined numeric ranges. + `, + }), }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.test.ts index 703156418b364..c544121a935f5 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.test.ts @@ -16,11 +16,9 @@ import { getDisallowedTermsMessage, getMultiTermsScriptedFieldErrorMessage, isSortableByColumn, - computeOrderForMultiplePercentiles, } from './helpers'; import { ReferenceBasedIndexPatternColumn } from '../column_types'; import type { PercentileRanksIndexPatternColumn } from '../percentile_ranks'; -import type { PercentileIndexPatternColumn } from '../percentile'; import { MULTI_KEY_VISUAL_SEPARATOR } from './constants'; import { MovingAverageIndexPatternColumn } from '../calculations'; @@ -410,138 +408,6 @@ describe('getDisallowedTermsMessage()', () => { }); }); -describe('computeOrderForMultiplePercentiles()', () => { - it('should return null for no percentile orderColumn', () => { - expect( - computeOrderForMultiplePercentiles( - { - label: 'Percentile rank (1024.5) of bytes', - dataType: 'number', - operationType: 'percentile_rank', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { value: 1024.5 }, - } as PercentileRanksIndexPatternColumn, - getLayer(getStringBasedOperationColumn(), [ - { - label: 'Percentile rank (1024.5) of bytes', - dataType: 'number', - operationType: 'percentile_rank', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { value: 1024.5 }, - } as PercentileRanksIndexPatternColumn, - ]), - ['col1', 'col2'] - ) - ).toBeNull(); - }); - - it('should return null for single percentile', () => { - expect( - computeOrderForMultiplePercentiles( - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - getLayer(getStringBasedOperationColumn(), [ - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - ]), - ['col1', 'col2'] - ) - ).toBeNull(); - }); - - it('should return correct orderBy for multiple percentile on the same field', () => { - expect( - computeOrderForMultiplePercentiles( - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - getLayer(getStringBasedOperationColumn(), [ - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - { - label: 'Percentile 65 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 65 }, - } as PercentileIndexPatternColumn, - ]), - ['col1', 'col2', 'col3'] - ) - ).toBe('1.95'); - }); - - it('should return null for multiple percentile on different field', () => { - expect( - computeOrderForMultiplePercentiles( - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - getLayer(getStringBasedOperationColumn(), [ - { - label: 'Percentile 95 of bytes', - dataType: 'number', - operationType: 'percentile', - sourceField: 'bytes', - isBucketed: false, - scale: 'ratio', - params: { percentile: 95 }, - } as PercentileIndexPatternColumn, - { - label: 'Percentile 65 of geo', - dataType: 'number', - operationType: 'percentile', - sourceField: 'geo', - isBucketed: false, - scale: 'ratio', - params: { percentile: 65 }, - } as PercentileIndexPatternColumn, - ]), - ['col1', 'col2', 'col3'] - ) - ).toBeNull(); - }); -}); - describe('isSortableByColumn()', () => { it('should sort by the given column', () => { expect( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.ts index 7139a8effd4ca..77d52664c0e54 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/helpers.ts @@ -21,7 +21,6 @@ import type { FiltersIndexPatternColumn } from '..'; import type { TermsIndexPatternColumn } from './types'; import type { LastValueIndexPatternColumn } from '../last_value'; import type { PercentileRanksIndexPatternColumn } from '../percentile_ranks'; -import type { PercentileIndexPatternColumn } from '../percentile'; import type { IndexPatternLayer } from '../../../types'; import { MULTI_KEY_VISUAL_SEPARATOR, supportedTypes } from './constants'; @@ -241,31 +240,6 @@ export function isPercentileRankSortable(column: GenericIndexPatternColumn) { ); } -export function computeOrderForMultiplePercentiles( - column: GenericIndexPatternColumn, - layer: IndexPatternLayer, - orderedColumnIds: string[] -) { - // compute the percentiles orderBy correctly for multiple percentiles - if (column.operationType === 'percentile') { - const percentileColumns = []; - for (const [key, value] of Object.entries(layer.columns)) { - if ( - value.operationType === 'percentile' && - (value as PercentileIndexPatternColumn).sourceField === - (column as PercentileIndexPatternColumn).sourceField - ) { - percentileColumns.push(key); - } - } - if (percentileColumns.length > 1) { - const parentColumn = String(orderedColumnIds.indexOf(percentileColumns[0])); - return `${parentColumn}.${(column as PercentileIndexPatternColumn).params?.percentile}`; - } - } - return null; -} - export function isSortableByColumn(layer: IndexPatternLayer, columnId: string) { const column = layer.columns[columnId]; return ( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/index.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/index.tsx index 0427e40f24ac6..1f4b4846906d4 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/index.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/index.tsx @@ -49,7 +49,6 @@ import { getFieldsByValidationState, isSortableByColumn, isPercentileRankSortable, - computeOrderForMultiplePercentiles, } from './helpers'; import { DEFAULT_MAX_DOC_COUNT, @@ -240,6 +239,10 @@ export const termsOperation: OperationDefinition< otherBucket: (columnParams?.otherBucket ?? true) && !indexPattern.hasRestrictions, missingBucket: columnParams?.missingBucket ?? false, parentFormat: columnParams?.parentFormat ?? { id: 'terms' }, + include: columnParams?.include ?? [], + exclude: columnParams?.exclude ?? [], + includeIsRegex: columnParams?.includeIsRegex ?? false, + excludeIsRegex: columnParams?.excludeIsRegex ?? false, secondaryFields: columnParams?.secondaryFields, }, }; @@ -262,7 +265,7 @@ export const termsOperation: OperationDefinition< max_doc_count: column.params.orderBy.maxDocCount, }).toAst(); } - let orderBy: string = '_key'; + let orderBy = '_key'; if (column.params?.orderBy.type === 'column') { const orderColumn = layer.columns[column.params.orderBy.columnId]; @@ -271,14 +274,6 @@ export const termsOperation: OperationDefinition< if (!isPercentileRankSortable(orderColumn)) { orderBy = '_key'; } - - const orderByMultiplePercentiles = computeOrderForMultiplePercentiles( - orderColumn, - layer, - orderedColumnIds - ); - - orderBy = orderByMultiplePercentiles ?? orderBy; } // To get more accurate results, we set shard_size to a minimum of 1000 @@ -562,6 +557,11 @@ export const termsOperation: OperationDefinition< ); }, + quickFunctionDocumentation: i18n.translate('xpack.lens.indexPattern.terms.documentation.quick', { + defaultMessage: ` +The top values of a specified field ranked by the chosen metric. + `, + }), paramEditor: function ParamEditor({ layer, paramEditorUpdater, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/terms.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/terms.test.tsx index 8c3b7f90d57d3..584498189fd06 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/terms.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms/terms.test.tsx @@ -350,49 +350,6 @@ describe('terms', () => { ); }); - it('should reflect correct orderBy for multiple percentiles', () => { - const newLayer = { - ...layer, - columns: { - ...layer.columns, - col2: { - ...layer.columns.col2, - operationType: 'percentile', - params: { - percentile: 95, - }, - }, - col3: { - ...layer.columns.col2, - operationType: 'percentile', - params: { - percentile: 65, - }, - }, - }, - }; - const termsColumn = layer.columns.col1 as TermsIndexPatternColumn; - const esAggsFn = termsOperation.toEsAggsFn( - { - ...termsColumn, - params: { ...termsColumn.params, orderBy: { type: 'column', columnId: 'col3' } }, - }, - 'col1', - {} as IndexPattern, - newLayer, - uiSettingsMock, - ['col1', 'col2', 'col3'] - ); - expect(esAggsFn).toEqual( - expect.objectContaining({ - function: 'aggTerms', - arguments: expect.objectContaining({ - orderBy: ['1.65'], - }), - }) - ); - }); - it('should not enable missing bucket if other bucket is not set', () => { const termsColumn = layer.columns.col1 as TermsIndexPatternColumn; const esAggsFn = termsOperation.toEsAggsFn( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts index 2d8b41ce866b4..b3f1b3bc7d5f3 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts @@ -68,6 +68,7 @@ interface ColumnChange { columnParams?: Record; initialParams?: { params: Record }; // TODO: bind this to the op parameter references?: Array>; + respectOrder?: boolean; } interface ColumnCopy { @@ -362,6 +363,7 @@ export function insertNewColumn({ columnParams, initialParams, references, + respectOrder, }: ColumnChange): IndexPatternLayer { const operationDefinition = operationDefinitionMap[op]; @@ -394,7 +396,14 @@ export function insertNewColumn({ : operationDefinition.buildColumn({ ...baseOptions, layer }); return updateDefaultLabels( - addOperationFn(layer, buildColumnFn, columnId, visualizationGroups, targetGroup), + addOperationFn( + layer, + buildColumnFn, + columnId, + visualizationGroups, + targetGroup, + respectOrder + ), indexPattern ); } @@ -445,7 +454,14 @@ export function insertNewColumn({ ) : operationDefinition.buildColumn({ ...baseOptions, layer: tempLayer, referenceIds }); return updateDefaultLabels( - addOperationFn(tempLayer, buildColumnFn, columnId, visualizationGroups, targetGroup), + addOperationFn( + tempLayer, + buildColumnFn, + columnId, + visualizationGroups, + targetGroup, + respectOrder + ), indexPattern ); } @@ -468,7 +484,8 @@ export function insertNewColumn({ operationDefinition.buildColumn({ ...baseOptions, layer, field: invalidField }), columnId, visualizationGroups, - targetGroup + targetGroup, + respectOrder ), indexPattern ); @@ -508,7 +525,7 @@ export function insertNewColumn({ const isBucketed = Boolean(possibleOperation.isBucketed); const addOperationFn = isBucketed ? addBucket : addMetric; return updateDefaultLabels( - addOperationFn(layer, newColumn, columnId, visualizationGroups, targetGroup), + addOperationFn(layer, newColumn, columnId, visualizationGroups, targetGroup, respectOrder), indexPattern ); } @@ -1154,7 +1171,8 @@ function addBucket( column: BaseIndexPatternColumn, addedColumnId: string, visualizationGroups: VisualizationDimensionGroupConfig[], - targetGroup?: string + targetGroup?: string, + respectOrder?: boolean ): IndexPatternLayer { const [buckets, metrics] = partition( layer.columnOrder, @@ -1166,7 +1184,7 @@ function addBucket( ); let updatedColumnOrder: string[] = []; - if (oldDateHistogramIndex > -1 && column.operationType === 'terms') { + if (oldDateHistogramIndex > -1 && column.operationType === 'terms' && !respectOrder) { // Insert the new terms bucket above the first date histogram updatedColumnOrder = [ ...buckets.slice(0, oldDateHistogramIndex), diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts index bf816e5891486..72cb2a2ab729e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts @@ -27,6 +27,7 @@ import { DateHistogramIndexPatternColumn, RangeIndexPatternColumn } from './oper import { FormattedIndexPatternColumn } from './operations/definitions/column_types'; import { isColumnFormatted, isColumnOfType } from './operations/definitions/helpers'; import type { IndexPattern, IndexPatternMap } from '../types'; +import { dedupeAggs } from './dedupe_aggs'; export type OriginalColumn = { id: string } & GenericIndexPatternColumn; @@ -40,7 +41,7 @@ declare global { } // esAggs column ID manipulation functions -const extractEsAggId = (id: string) => id.split('.')[0].split('-')[2]; +export const extractAggId = (id: string) => id.split('.')[0].split('-')[2]; const updatePositionIndex = (currentId: string, newIndex: number) => { const [fullId, percentile] = currentId.split('.'); const idParts = fullId.split('-'); @@ -214,10 +215,18 @@ function getExpressionForLayer( ); } - uniq(esAggEntries.map(([_, column]) => column.operationType)).forEach((type) => { - const optimizeAggs = operationDefinitionMap[type].optimizeEsAggs?.bind( - operationDefinitionMap[type] - ); + const allOperations = uniq( + esAggEntries.map(([_, column]) => operationDefinitionMap[column.operationType]) + ); + + // De-duplicate aggs for supported operations + const dedupedResult = dedupeAggs(aggs, esAggsIdMap, aggExpressionToEsAggsIdMap, allOperations); + aggs = dedupedResult.aggs; + esAggsIdMap = dedupedResult.esAggsIdMap; + + // Apply any operation-specific custom optimizations + allOperations.forEach((operation) => { + const optimizeAggs = operation.optimizeEsAggs?.bind(operation); if (optimizeAggs) { const { aggs: newAggs, esAggsIdMap: newIdMap } = optimizeAggs( aggs, @@ -257,7 +266,7 @@ function getExpressionForLayer( const esAggsIds = Object.keys(esAggsIdMap); aggs.forEach((builder) => { const esAggId = builder.functions[0].getArgument('id')?.[0]; - const matchingEsAggColumnIds = esAggsIds.filter((id) => extractEsAggId(id) === esAggId); + const matchingEsAggColumnIds = esAggsIds.filter((id) => extractAggId(id) === esAggId); matchingEsAggColumnIds.forEach((currentId) => { const currentColumn = esAggsIdMap[currentId][0]; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/utils.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/utils.tsx index 2cb1ba164d572..77a359729a5e0 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/utils.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/utils.tsx @@ -194,7 +194,7 @@ export function getTSDBRollupWarningMessages( ).map((label) => i18n.translate('xpack.lens.indexPattern.tsdbRollupWarning', { defaultMessage: - '"{label}" does not work for all indices in the selected data view because it\'s using a function which is not supported on rolled up data. Please edit the visualization to use another function or change the time range.', + '{label} uses a function that is unsupported by rolled up data. Select a different function or change the time range.', values: { label, }, diff --git a/x-pack/plugins/lens/public/mocks/data_plugin_mock.ts b/x-pack/plugins/lens/public/mocks/data_plugin_mock.ts index 6939a03300dbb..db7ab00de22e3 100644 --- a/x-pack/plugins/lens/public/mocks/data_plugin_mock.ts +++ b/x-pack/plugins/lens/public/mocks/data_plugin_mock.ts @@ -129,6 +129,7 @@ export function mockDataPlugin( get: jest.fn().mockImplementation((id) => Promise.resolve({ id, isTimeBased: () => true })), }, dataViews: { + getIds: jest.fn().mockImplementation(jest.fn(async () => [])), get: jest.fn().mockImplementation((id) => Promise.resolve({ id, diff --git a/x-pack/plugins/lens/public/mocks/datasource_mock.ts b/x-pack/plugins/lens/public/mocks/datasource_mock.ts index de6f9342fd58b..3d169b643c2ce 100644 --- a/x-pack/plugins/lens/public/mocks/datasource_mock.ts +++ b/x-pack/plugins/lens/public/mocks/datasource_mock.ts @@ -20,6 +20,7 @@ export function createMockDatasource(id: string): DatasourceMock { getSourceId: jest.fn(), getFilters: jest.fn(), getMaxPossibleNumValues: jest.fn(), + isTextBasedLanguage: jest.fn(() => false), }; return { @@ -52,6 +53,7 @@ export function createMockDatasource(id: string): DatasourceMock { renderDimensionEditor: jest.fn(), getDropProps: jest.fn(), onDrop: jest.fn(), + createEmptyLayer: jest.fn(), // this is an additional property which doesn't exist on real datasources // but can be used to validate whether specific API mock functions are called diff --git a/x-pack/plugins/lens/public/mocks/services_mock.tsx b/x-pack/plugins/lens/public/mocks/services_mock.tsx index c97bfbb9373f0..81aa4e0617931 100644 --- a/x-pack/plugins/lens/public/mocks/services_mock.tsx +++ b/x-pack/plugins/lens/public/mocks/services_mock.tsx @@ -104,9 +104,11 @@ export function makeDefaultServices( const navigationStartMock = navigationPluginMock.createStartContract(); - jest.spyOn(navigationStartMock.ui.TopNavMenu.prototype, 'constructor').mockImplementation(() => { - return
; - }); + jest + .spyOn(navigationStartMock.ui.AggregateQueryTopNavMenu.prototype, 'constructor') + .mockImplementation(() => { + return
; + }); function makeAttributeService(): LensAttributeService { const attributeServiceMock = mockAttributeService< diff --git a/x-pack/plugins/lens/public/plugin.ts b/x-pack/plugins/lens/public/plugin.ts index 44307bad11b8e..6019f566e0ba6 100644 --- a/x-pack/plugins/lens/public/plugin.ts +++ b/x-pack/plugins/lens/public/plugin.ts @@ -41,7 +41,10 @@ import { ACTION_VISUALIZE_FIELD, VISUALIZE_FIELD_TRIGGER, } from '@kbn/ui-actions-plugin/public'; -import { VISUALIZE_EDITOR_TRIGGER } from '@kbn/visualizations-plugin/public'; +import { + VISUALIZE_EDITOR_TRIGGER, + AGG_BASED_VISUALIZATION_TRIGGER, +} from '@kbn/visualizations-plugin/public'; import { createStartServicesGetter } from '@kbn/kibana-utils-plugin/public'; import type { DiscoverSetup, DiscoverStart } from '@kbn/discover-plugin/public'; import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; @@ -53,6 +56,8 @@ import type { IndexPatternDatasourceSetupPlugins, FormulaPublicApi, } from './indexpattern_datasource'; +import type { TextBasedLanguagesDatasource as TextBasedLanguagesDatasourceType } from './text_based_languages_datasource'; + import type { XyVisualization as XyVisualizationType, XyVisualizationPluginSetupPlugins, @@ -85,6 +90,7 @@ import { getLensAliasConfig } from './vis_type_alias'; import { createOpenInDiscoverAction } from './trigger_actions/open_in_discover_action'; import { visualizeFieldAction } from './trigger_actions/visualize_field_actions'; import { visualizeTSVBAction } from './trigger_actions/visualize_tsvb_actions'; +import { visualizeAggBasedVisAction } from './trigger_actions/visualize_agg_based_vis_actions'; import type { LensEmbeddableInput } from './embeddable'; import { EmbeddableFactory, LensEmbeddableStartServices } from './embeddable/embeddable_factory'; @@ -226,6 +232,7 @@ export class LensPlugin { private editorFrameSetup: EditorFrameSetup | undefined; private queuedVisualizations: Array Promise)> = []; private indexpatternDatasource: IndexPatternDatasourceType | undefined; + private textBasedLanguagesDatasource: TextBasedLanguagesDatasourceType | undefined; private xyVisualization: XyVisualizationType | undefined; private legacyMetricVisualization: LegacyMetricVisualizationType | undefined; private metricVisualization: MetricVisualizationType | undefined; @@ -422,10 +429,12 @@ export class LensPlugin { PieVisualization, HeatmapVisualization, GaugeVisualization, + TextBasedLanguagesDatasource, } = await import('./async_services'); this.datatableVisualization = new DatatableVisualization(); this.editorFrameService = new EditorFrameService(); this.indexpatternDatasource = new IndexPatternDatasource(); + this.textBasedLanguagesDatasource = new TextBasedLanguagesDatasource(); this.xyVisualization = new XyVisualization(); this.legacyMetricVisualization = new LegacyMetricVisualization(); this.metricVisualization = new MetricVisualization(); @@ -449,6 +458,7 @@ export class LensPlugin { eventAnnotation, }; this.indexpatternDatasource.setup(core, dependencies); + this.textBasedLanguagesDatasource.setup(core, dependencies); this.xyVisualization.setup(core, dependencies); this.datatableVisualization.setup(core, dependencies); this.legacyMetricVisualization.setup(core, dependencies); @@ -480,6 +490,11 @@ export class LensPlugin { visualizeTSVBAction(core.application) ); + startDependencies.uiActions.addTriggerAction( + AGG_BASED_VISUALIZATION_TRIGGER, + visualizeAggBasedVisAction(core.application) + ); + startDependencies.uiActions.addTriggerAction( CONTEXT_MENU_TRIGGER, createOpenInDiscoverAction( diff --git a/x-pack/plugins/lens/public/shared_components/dataview_picker/dataview_picker.tsx b/x-pack/plugins/lens/public/shared_components/dataview_picker/dataview_picker.tsx index b66a5f1d76545..35c0215a35c53 100644 --- a/x-pack/plugins/lens/public/shared_components/dataview_picker/dataview_picker.tsx +++ b/x-pack/plugins/lens/public/shared_components/dataview_picker/dataview_picker.tsx @@ -15,6 +15,7 @@ import { IndexPatternRef } from '../../types'; export type ChangeIndexPatternTriggerProps = ToolbarButtonProps & { label: string; title?: string; + isDisabled?: boolean; }; export function ChangeIndexPattern({ diff --git a/x-pack/plugins/lens/public/state_management/index.ts b/x-pack/plugins/lens/public/state_management/index.ts index 91481cd58bb0c..725c68e7a1429 100644 --- a/x-pack/plugins/lens/public/state_management/index.ts +++ b/x-pack/plugins/lens/public/state_management/index.ts @@ -34,6 +34,7 @@ export const { rollbackSuggestion, submitSuggestion, switchDatasource, + switchAndCleanDatasource, updateIndexPatterns, setToggleFullscreen, initEmpty, diff --git a/x-pack/plugins/lens/public/state_management/lens_slice.test.ts b/x-pack/plugins/lens/public/state_management/lens_slice.test.ts index fba5c9c9abd54..fc536b30ddac6 100644 --- a/x-pack/plugins/lens/public/state_management/lens_slice.test.ts +++ b/x-pack/plugins/lens/public/state_management/lens_slice.test.ts @@ -9,6 +9,7 @@ import { EnhancedStore } from '@reduxjs/toolkit'; import type { Query } from '@kbn/es-query'; import { switchDatasource, + switchAndCleanDatasource, switchVisualization, setState, updateState, @@ -210,6 +211,57 @@ describe('lensSlice', () => { ); }); + describe('switching to a new datasource and modify the state', () => { + it('should switch active datasource and initialize new state', () => { + store.dispatch( + switchAndCleanDatasource({ + newDatasourceId: 'testDatasource2', + visualizationId: 'testVis', + currentIndexPatternId: 'testIndexPatternId', + }) + ); + expect(store.getState().lens.activeDatasourceId).toEqual('testDatasource2'); + expect(store.getState().lens.datasourceStates.testDatasource2.isLoading).toEqual(false); + expect(store.getState().lens.visualization.activeId).toEqual('testVis'); + }); + + it('should should switch active datasource and clean the datasource state', () => { + const datasource2State = { + layers: {}, + }; + const { store: customStore } = makeLensStore({ + preloadedState: { + datasourceStates: { + testDatasource: { + state: {}, + isLoading: false, + }, + testDatasource2: { + state: datasource2State, + isLoading: false, + }, + }, + }, + }); + + customStore.dispatch( + switchAndCleanDatasource({ + newDatasourceId: 'testDatasource2', + visualizationId: 'testVis', + currentIndexPatternId: 'testIndexPatternId', + }) + ); + + expect(customStore.getState().lens.activeDatasourceId).toEqual('testDatasource2'); + expect(customStore.getState().lens.datasourceStates.testDatasource2.isLoading).toEqual( + false + ); + expect(customStore.getState().lens.datasourceStates.testDatasource2.state).toStrictEqual( + {} + ); + }); + }); + describe('adding or removing layer', () => { const testDatasource = (datasourceId: string) => { return { diff --git a/x-pack/plugins/lens/public/state_management/lens_slice.ts b/x-pack/plugins/lens/public/state_management/lens_slice.ts index b73d1f12ca868..725c60bfc22cb 100644 --- a/x-pack/plugins/lens/public/state_management/lens_slice.ts +++ b/x-pack/plugins/lens/public/state_management/lens_slice.ts @@ -57,10 +57,12 @@ export const getPreloadedState = ({ const initialDatasourceId = getInitialDatasourceId(datasourceMap); const datasourceStates: LensAppState['datasourceStates'] = {}; if (initialDatasourceId) { - datasourceStates[initialDatasourceId] = { - state: null, - isLoading: true, - }; + Object.keys(datasourceMap).forEach((datasourceId) => { + datasourceStates[datasourceId] = { + state: null, + isLoading: true, + }; + }); } const state = { @@ -130,6 +132,11 @@ export const submitSuggestion = createAction('lens/submitSuggestion'); export const switchDatasource = createAction<{ newDatasourceId: string; }>('lens/switchDatasource'); +export const switchAndCleanDatasource = createAction<{ + newDatasourceId: string; + visualizationId: string | null; + currentIndexPatternId?: string; +}>('lens/switchAndCleanDatasource'); export const navigateAway = createAction('lens/navigateAway'); export const loadInitial = createAction<{ initialInput?: LensEmbeddableInput; @@ -211,6 +218,7 @@ export const lensActions = { setToggleFullscreen, submitSuggestion, switchDatasource, + switchAndCleanDatasource, navigateAway, loadInitial, initEmpty, @@ -359,9 +367,11 @@ export const makeLensReducer = (storeDeps: LensStoreDeps) => { const datasource = datasourceMap[datasourceId!]; return { ...datasourceState, - state: isOnlyLayer - ? datasource.clearLayer(datasourceState.state, layerId) - : datasource.removeLayer(datasourceState.state, layerId), + ...(datasourceId === state.activeDatasourceId && { + state: isOnlyLayer + ? datasource.clearLayer(datasourceState.state, layerId) + : datasource.removeLayer(datasourceState.state, layerId), + }), }; } ); @@ -663,6 +673,55 @@ export const makeLensReducer = (storeDeps: LensStoreDeps) => { activeDatasourceId: payload.newDatasourceId, }; }, + [switchAndCleanDatasource.type]: ( + state, + { + payload, + }: { + payload: { + newDatasourceId: string; + visualizationId?: string; + currentIndexPatternId?: string; + }; + } + ) => { + const activeVisualization = + payload.visualizationId && visualizationMap[payload.visualizationId]; + const visualization = state.visualization; + let newVizState = visualization.state; + const ids: string[] = []; + if (activeVisualization && activeVisualization.getLayerIds) { + const layerIds = activeVisualization.getLayerIds(visualization.state); + ids.push(...Object.values(layerIds)); + newVizState = activeVisualization.initialize(() => ids[0]); + } + const currentVizId = ids[0]; + + const datasourceState = current(state).datasourceStates[payload.newDatasourceId] + ? current(state).datasourceStates[payload.newDatasourceId]?.state + : datasourceMap[payload.newDatasourceId].createEmptyLayer( + payload.currentIndexPatternId ?? '' + ); + const updatedState = datasourceMap[payload.newDatasourceId].insertLayer( + datasourceState, + currentVizId + ); + + return { + ...state, + datasourceStates: { + [payload.newDatasourceId]: { + state: updatedState, + isLoading: false, + }, + }, + activeDatasourceId: payload.newDatasourceId, + visualization: { + ...visualization, + state: newVizState, + }, + }; + }, [navigateAway.type]: (state) => state, [loadInitial.type]: ( state, diff --git a/x-pack/plugins/lens/public/state_management/types.ts b/x-pack/plugins/lens/public/state_management/types.ts index ceae38967c77d..9399506f5fca1 100644 --- a/x-pack/plugins/lens/public/state_management/types.ts +++ b/x-pack/plugins/lens/public/state_management/types.ts @@ -7,7 +7,7 @@ import { VisualizeFieldContext } from '@kbn/ui-actions-plugin/public'; import { EmbeddableEditorState } from '@kbn/embeddable-plugin/public'; -import { Filter, Query } from '@kbn/es-query'; +import type { Filter, Query } from '@kbn/es-query'; import { SavedQuery } from '@kbn/data-plugin/public'; import { Document } from '../persistence'; diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.test.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.test.tsx new file mode 100644 index 0000000000000..51ba02c1cdc6f --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.test.tsx @@ -0,0 +1,237 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import ReactDOM from 'react-dom'; +import { act } from 'react-dom/test-utils'; +import type { Query } from '@kbn/es-query'; + +import { dataPluginMock } from '@kbn/data-plugin/public/mocks'; +import { expressionsPluginMock } from '@kbn/expressions-plugin/public/mocks'; +import { + dataViewPluginMocks, + Start as DataViewPublicStart, +} from '@kbn/data-views-plugin/public/mocks'; +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; +import { FieldButton } from '@kbn/react-field'; + +import { type TextBasedLanguagesDataPanelProps, TextBasedLanguagesDataPanel } from './datapanel'; + +import { coreMock } from '@kbn/core/public/mocks'; +import type { TextBasedLanguagesPrivateState } from './types'; +import { mountWithIntl } from '@kbn/test-jest-helpers'; + +import { uiActionsPluginMock } from '@kbn/ui-actions-plugin/public/mocks'; +import { createIndexPatternServiceMock } from '../mocks/data_views_service_mock'; +import { createMockFramePublicAPI } from '../mocks'; +import { createMockedDragDropContext } from './mocks'; +import { DataViewsState } from '../state_management'; +import { ExistingFieldsMap, IndexPattern } from '../types'; + +const fieldsFromQuery = [ + { + name: 'timestamp', + id: 'timestamp', + meta: { + type: 'date', + }, + }, + { + name: 'bytes', + id: 'bytes', + meta: { + type: 'number', + }, + }, + { + name: 'memory', + id: 'memory', + meta: { + type: 'number', + }, + }, +] as DatatableColumn[]; + +const fieldsOne = [ + { + name: 'timestamp', + displayName: 'timestampLabel', + type: 'date', + aggregatable: true, + searchable: true, + }, + { + name: 'bytes', + displayName: 'bytes', + type: 'number', + aggregatable: true, + searchable: true, + }, + { + name: 'memory', + displayName: 'amemory', + type: 'number', + aggregatable: true, + searchable: true, + }, + { + name: 'unsupported', + displayName: 'unsupported', + type: 'geo', + aggregatable: true, + searchable: true, + }, + { + name: 'source', + displayName: 'source', + type: 'string', + aggregatable: true, + searchable: true, + }, + { + name: 'client', + displayName: 'client', + type: 'ip', + aggregatable: true, + searchable: true, + }, +]; + +function getExistingFields(indexPatterns: Record) { + const existingFields: ExistingFieldsMap = {}; + for (const { title, fields } of Object.values(indexPatterns)) { + const fieldsMap: Record = {}; + for (const { displayName, name } of fields) { + fieldsMap[displayName ?? name] = true; + } + existingFields[title] = fieldsMap; + } + return existingFields; +} + +const initialState: TextBasedLanguagesPrivateState = { + layers: { + first: { + index: '1', + columns: [], + allColumns: [], + query: { sql: 'SELECT * FROM foo' }, + }, + }, + indexPatternRefs: [ + { id: '1', title: 'my-fake-index-pattern' }, + { id: '2', title: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern' }, + ], + fieldList: fieldsFromQuery, +}; + +function getFrameAPIMock({ indexPatterns, existingFields, ...rest }: Partial = {}) { + const frameAPI = createMockFramePublicAPI(); + const defaultIndexPatterns = { + '1': { + id: '1', + title: 'idx1', + timeFieldName: 'timestamp', + hasRestrictions: false, + fields: fieldsOne, + getFieldByName: jest.fn(), + isPersisted: true, + spec: {}, + }, + }; + return { + ...frameAPI, + dataViews: { + ...frameAPI.dataViews, + indexPatterns: indexPatterns ?? defaultIndexPatterns, + existingFields: existingFields ?? getExistingFields(indexPatterns ?? defaultIndexPatterns), + isFirstExistenceFetch: false, + ...rest, + }, + }; +} + +// @ts-expect-error Portal mocks are notoriously difficult to type +ReactDOM.createPortal = jest.fn((element) => element); + +describe('TextBased Query Languages Data Panel', () => { + let core: ReturnType; + let dataViews: DataViewPublicStart; + + let defaultProps: TextBasedLanguagesDataPanelProps; + const dataViewsMock = dataViewPluginMocks.createStartContract(); + beforeEach(() => { + core = coreMock.createStart(); + dataViews = dataViewPluginMocks.createStartContract(); + defaultProps = { + data: dataPluginMock.createStartContract(), + expressions: expressionsPluginMock.createStartContract(), + dataViews: { + ...dataViewsMock, + getIdsWithTitle: jest.fn().mockReturnValue( + Promise.resolve([ + { id: '1', title: 'my-fake-index-pattern' }, + { id: '2', title: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern' }, + ]) + ), + }, + dragDropContext: createMockedDragDropContext(), + core, + dateRange: { + fromDate: 'now-7d', + toDate: 'now', + }, + query: { sql: 'SELECT * FROM my-fake-index-pattern' } as unknown as Query, + filters: [], + showNoDataPopover: jest.fn(), + dropOntoWorkspace: jest.fn(), + hasSuggestionForField: jest.fn(() => false), + uiActions: uiActionsPluginMock.createStartContract(), + indexPatternService: createIndexPatternServiceMock({ core, dataViews }), + frame: getFrameAPIMock(), + state: initialState, + setState: jest.fn(), + onChangeIndexPattern: jest.fn(), + }; + }); + + it('should render a search box', async () => { + const wrapper = mountWithIntl(); + expect(wrapper.find('[data-test-subj="lnsTextBasedLangugesFieldSearch"]').length).toEqual(1); + }); + + it('should list all supported fields in the pattern', async () => { + const wrapper = mountWithIntl(); + expect( + wrapper + .find('[data-test-subj="lnsTextBasedLanguagesPanelFields"]') + .find(FieldButton) + .map((fieldItem) => fieldItem.prop('fieldName')) + ).toEqual(['timestamp', 'bytes', 'memory']); + }); + + it('should list all supported fields in the pattern that match the search input', async () => { + const wrapper = mountWithIntl(); + const searchBox = wrapper.find('[data-test-subj="lnsTextBasedLangugesFieldSearch"]'); + + act(() => { + searchBox.prop('onChange')!({ + target: { value: 'mem' }, + } as React.ChangeEvent); + }); + + wrapper.update(); + expect( + wrapper + .find('[data-test-subj="lnsTextBasedLanguagesPanelFields"]') + .find(FieldButton) + .map((fieldItem) => fieldItem.prop('fieldName')) + ).toEqual(['memory']); + }); +}); diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.tsx new file mode 100644 index 0000000000000..9e15db381549d --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/datapanel.tsx @@ -0,0 +1,167 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useState, useEffect, useMemo } from 'react'; +import { EuiFlexGroup, EuiFlexItem, EuiFormControlLayout, htmlIdGenerator } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import usePrevious from 'react-use/lib/usePrevious'; +import { isEqual } from 'lodash'; +import { DataPublicPluginStart } from '@kbn/data-plugin/public'; +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; + +import { isOfAggregateQueryType } from '@kbn/es-query'; +import { ExpressionsStart } from '@kbn/expressions-plugin/public'; +import { FieldButton } from '@kbn/react-field'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { DatasourceDataPanelProps, DataType } from '../types'; +import type { TextBasedLanguagesPrivateState } from './types'; +import { getStateFromAggregateQuery } from './utils'; +import { DragDrop } from '../drag_drop'; +import { LensFieldIcon } from '../shared_components'; +import { ChildDragDropProvider } from '../drag_drop'; + +export type TextBasedLanguagesDataPanelProps = + DatasourceDataPanelProps & { + data: DataPublicPluginStart; + expressions: ExpressionsStart; + dataViews: DataViewsPublicPluginStart; + }; +const htmlId = htmlIdGenerator('datapanel-text-based-languages'); +const fieldSearchDescriptionId = htmlId(); + +export function TextBasedLanguagesDataPanel({ + setState, + state, + dragDropContext, + core, + data, + query, + filters, + dateRange, + expressions, + dataViews, +}: TextBasedLanguagesDataPanelProps) { + const prevQuery = usePrevious(query); + const [localState, setLocalState] = useState({ nameFilter: '' }); + const clearLocalState = () => setLocalState((s) => ({ ...s, nameFilter: '' })); + useEffect(() => { + async function fetchData() { + if (query && isOfAggregateQueryType(query) && !isEqual(query, prevQuery)) { + const stateFromQuery = await getStateFromAggregateQuery( + state, + query, + dataViews, + data, + expressions + ); + + setState(stateFromQuery); + } + } + fetchData(); + }, [data, dataViews, expressions, prevQuery, query, setState, state]); + + const { fieldList } = state; + const filteredFields = useMemo(() => { + return fieldList.filter((field) => { + if ( + localState.nameFilter && + !field.name.toLowerCase().includes(localState.nameFilter.toLowerCase()) + ) { + return false; + } + return true; + }); + }, [fieldList, localState.nameFilter]); + + return ( + + + + + { + clearLocalState(); + }, + }} + > + { + setLocalState({ ...localState, nameFilter: e.target.value }); + }} + aria-label={i18n.translate('xpack.lens.indexPatterns.filterByNameLabel', { + defaultMessage: 'Search field names', + description: 'Search the list of fields in the data view for the provided text', + })} + aria-describedby={fieldSearchDescriptionId} + /> + + + +
+
+
    + {filteredFields.length > 0 && + filteredFields.map((field, index) => ( +
  • + + {}} + fieldIcon={} + fieldName={field?.name} + /> + +
  • + ))} +
+
+
+
+
+
+
+ ); +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/fetch_data_from_aggregate_query.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/fetch_data_from_aggregate_query.ts new file mode 100644 index 0000000000000..b41289d11e8fb --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/fetch_data_from_aggregate_query.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { pluck } from 'rxjs/operators'; +import { lastValueFrom } from 'rxjs'; +import { Query, AggregateQuery, Filter } from '@kbn/es-query'; +import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; +import type { ExpressionsStart } from '@kbn/expressions-plugin/public'; +import type { Datatable } from '@kbn/expressions-plugin/public'; +import type { DataViewsContract } from '@kbn/data-views-plugin/common'; +import { textBasedQueryStateToAstWithValidation } from '@kbn/data-plugin/common'; + +interface TextBasedLanguagesErrorResponse { + error: { + message: string; + }; + type: 'error'; +} + +export function fetchDataFromAggregateQuery( + query: Query | AggregateQuery, + dataViewsService: DataViewsContract, + data: DataPublicPluginStart, + expressions: ExpressionsStart, + filters?: Filter[], + inputQuery?: Query +) { + const timeRange = data.query.timefilter.timefilter.getTime(); + return textBasedQueryStateToAstWithValidation({ + filters, + query, + time: timeRange, + dataViewsService, + inputQuery, + }) + .then((ast) => { + if (ast) { + const execution = expressions.run(ast, null); + let finalData: Datatable; + let error: string | undefined; + execution.pipe(pluck('result')).subscribe((resp) => { + const response = resp as Datatable | TextBasedLanguagesErrorResponse; + if (response.type === 'error') { + error = response.error.message; + } else { + finalData = response; + } + }); + return lastValueFrom(execution).then(() => { + if (error) { + throw new Error(error); + } else { + return finalData; + } + }); + } + return undefined; + }) + .catch((err) => { + throw new Error(err.message); + }); +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.test.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.test.tsx new file mode 100644 index 0000000000000..f1051f3b8f61d --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.test.tsx @@ -0,0 +1,111 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; + +import { FieldPicker, FieldOptionValue } from '../shared_components/field_picker'; + +import { FieldSelect, FieldSelectProps } from './field_select'; +import { shallowWithIntl as shallow } from '@kbn/test-jest-helpers'; + +const fields = [ + { + name: 'timestamp', + id: 'timestamp', + meta: { + type: 'date', + }, + }, + { + name: 'bytes', + id: 'bytes', + meta: { + type: 'number', + }, + }, + { + name: 'memory', + id: 'memory', + meta: { + type: 'number', + }, + }, +] as DatatableColumn[]; + +describe('Layer Data Panel', () => { + let defaultProps: FieldSelectProps; + + beforeEach(() => { + defaultProps = { + selectedField: { + fieldName: 'bytes', + columnId: 'bytes', + meta: { + type: 'number', + }, + }, + existingFields: fields, + onChoose: jest.fn(), + }; + }); + + it('should display the selected field if given', () => { + const instance = shallow(); + expect(instance.find(FieldPicker).prop('selectedOptions')).toStrictEqual([ + { + label: 'bytes', + value: { + type: 'field', + field: 'bytes', + dataType: 'number', + }, + }, + ]); + }); + + it('should pass the fields with the correct format', () => { + const instance = shallow(); + expect(instance.find(FieldPicker).prop('options')).toStrictEqual([ + { + label: 'Available fields', + options: [ + { + compatible: true, + exists: true, + label: 'timestamp', + value: { + type: 'field' as FieldOptionValue['type'], + field: 'timestamp', + dataType: 'date', + }, + }, + { + compatible: true, + exists: true, + label: 'bytes', + value: { + type: 'field' as FieldOptionValue['type'], + field: 'bytes', + dataType: 'number', + }, + }, + { + compatible: true, + exists: true, + label: 'memory', + value: { + type: 'field' as FieldOptionValue['type'], + field: 'memory', + dataType: 'number', + }, + }, + ], + }, + ]); + }); +}); diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.tsx new file mode 100644 index 0000000000000..63153bc87d59e --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/field_select.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useMemo } from 'react'; +import { EuiComboBoxOptionOption, EuiComboBoxProps } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; +import { FieldPicker, FieldOptionValue, FieldOption } from '../shared_components/field_picker'; +import type { TextBasedLanguagesLayerColumn } from './types'; +import type { DataType } from '../types'; + +export interface FieldSelectProps extends EuiComboBoxProps { + selectedField?: TextBasedLanguagesLayerColumn; + onChoose: (choice: FieldOptionValue) => void; + existingFields: DatatableColumn[]; +} + +export function FieldSelect({ + selectedField, + onChoose, + existingFields, + ['data-test-subj']: dataTestSub, +}: FieldSelectProps) { + const memoizedFieldOptions = useMemo(() => { + const availableFields = existingFields.map((field) => { + const dataType = field?.meta?.type as DataType; + return { + compatible: true, + exists: true, + label: field.name, + value: { + type: 'field' as FieldOptionValue['type'], + field: field.name, + dataType, + }, + }; + }); + return [ + { + label: i18n.translate('xpack.lens.indexPattern.availableFieldsLabel', { + defaultMessage: 'Available fields', + }), + options: availableFields, + }, + ]; + }, [existingFields]); + + return ( + + selectedOptions={ + selectedField + ? ([ + { + label: selectedField.fieldName, + value: { + type: 'field', + field: selectedField.fieldName, + dataType: selectedField?.meta?.type, + }, + }, + ] as unknown as Array>) + : [] + } + options={memoizedFieldOptions as Array>} + onChoose={(choice) => { + if (choice && choice.field !== selectedField?.fieldName) { + onChoose(choice); + } + }} + fieldIsInvalid={false} + data-test-subj={dataTestSub ?? 'text-based-dimension-field'} + /> + ); +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/index.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/index.ts new file mode 100644 index 0000000000000..b2cffc5659dbf --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/index.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { CoreSetup } from '@kbn/core/public'; +import { Storage } from '@kbn/kibana-utils-plugin/public'; +import { ExpressionsStart } from '@kbn/expressions-plugin/public'; +import { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public'; +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import { EditorFrameSetup } from '../types'; + +export interface TextBasedLanguageSetupPlugins { + data: DataPublicPluginSetup; + editorFrame: EditorFrameSetup; +} + +export interface TextBasedLanguageStartPlugins { + data: DataPublicPluginStart; + dataViews: DataViewsPublicPluginStart; + expressions: ExpressionsStart; +} + +export class TextBasedLanguagesDatasource { + constructor() {} + + setup( + core: CoreSetup, + { editorFrame }: TextBasedLanguageSetupPlugins + ) { + editorFrame.registerDatasource(async () => { + const { getTextBasedLanguagesDatasource } = await import('../async_services'); + const [coreStart, { data, dataViews, expressions }] = await core.getStartServices(); + + return getTextBasedLanguagesDatasource({ + core: coreStart, + storage: new Storage(localStorage), + data, + dataViews, + expressions, + }); + }); + } +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.test.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.test.tsx new file mode 100644 index 0000000000000..7a3bf25b5e9e6 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.test.tsx @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; +import { TextBasedLanguagesPrivateState } from './types'; +import type { DataViewsState } from '../state_management/types'; + +import { TextBasedLanguageLayerPanelProps, LayerPanel } from './layerpanel'; +import { shallowWithIntl as shallow } from '@kbn/test-jest-helpers'; +import { ChangeIndexPattern } from '../shared_components/dataview_picker/dataview_picker'; + +const fields = [ + { + name: 'timestamp', + id: 'timestamp', + meta: { + type: 'date', + }, + }, + { + name: 'bytes', + id: 'bytes', + meta: { + type: 'number', + }, + }, + { + name: 'memory', + id: 'memory', + meta: { + type: 'number', + }, + }, +] as DatatableColumn[]; + +const initialState: TextBasedLanguagesPrivateState = { + layers: { + first: { + index: '1', + columns: [], + allColumns: [], + query: { sql: 'SELECT * FROM foo' }, + }, + }, + indexPatternRefs: [ + { id: '1', title: 'my-fake-index-pattern' }, + { id: '2', title: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern' }, + ], + fieldList: fields, +}; +describe('Layer Data Panel', () => { + let defaultProps: TextBasedLanguageLayerPanelProps; + + beforeEach(() => { + defaultProps = { + layerId: 'first', + state: initialState, + onChangeIndexPattern: jest.fn(), + dataViews: { + indexPatternRefs: [ + { id: '1', title: 'my-fake-index-pattern', name: 'My fake index pattern' }, + { id: '2', title: 'my-fake-restricted-pattern', name: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern', name: 'my-compatible-pattern' }, + ], + existingFields: {}, + isFirstExistenceFetch: false, + indexPatterns: {}, + } as DataViewsState, + }; + }); + + it('should display the selected dataview but disabled', () => { + const instance = shallow(); + expect(instance.find(ChangeIndexPattern).prop('trigger')).toStrictEqual({ + fontWeight: 'normal', + isDisabled: true, + label: 'My fake index pattern', + size: 's', + title: 'my-fake-index-pattern', + }); + }); +}); diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.tsx new file mode 100644 index 0000000000000..8f8e4a91242b1 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/layerpanel.tsx @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { I18nProvider } from '@kbn/i18n-react'; +import { i18n } from '@kbn/i18n'; +import { DatasourceLayerPanelProps } from '../types'; +import { TextBasedLanguagesPrivateState } from './types'; +import { ChangeIndexPattern } from '../shared_components/dataview_picker/dataview_picker'; + +export interface TextBasedLanguageLayerPanelProps + extends DatasourceLayerPanelProps { + state: TextBasedLanguagesPrivateState; +} + +export function LayerPanel({ state, layerId, dataViews }: TextBasedLanguageLayerPanelProps) { + const layer = state.layers[layerId]; + const dataView = dataViews.indexPatternRefs.find((ref) => ref.id === layer.index); + const notFoundTitleLabel = i18n.translate('xpack.lens.layerPanel.missingDataView', { + defaultMessage: 'Data view not found', + }); + return ( + + {}} + /> + + ); +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/mocks.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/mocks.ts new file mode 100644 index 0000000000000..adca02ab2299d --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/mocks.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DragContextState } from '../drag_drop'; + +export function createMockedDragDropContext(): jest.Mocked { + return { + dragging: undefined, + setDragging: jest.fn(), + activeDropTarget: undefined, + setActiveDropTarget: jest.fn(), + keyboardMode: false, + setKeyboardMode: jest.fn(), + setA11yMessage: jest.fn(), + dropTargetsByOrder: undefined, + registerDropTarget: jest.fn(), + }; +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.test.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.test.ts new file mode 100644 index 0000000000000..c2238bfd9fef1 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.test.ts @@ -0,0 +1,595 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { coreMock } from '@kbn/core/public/mocks'; +import { IStorageWrapper } from '@kbn/kibana-utils-plugin/public'; +import { expressionsPluginMock } from '@kbn/expressions-plugin/public/mocks'; +import { TextBasedLanguagesPersistedState, TextBasedLanguagesPrivateState } from './types'; +import { dataPluginMock } from '@kbn/data-plugin/public/mocks'; +import { dataViewPluginMocks } from '@kbn/data-views-plugin/public/mocks'; +import { getTextBasedLanguagesDatasource } from './text_based_languages'; +import { DatasourcePublicAPI, Datasource } from '../types'; + +jest.mock('../id_generator'); + +const fieldsOne = [ + { + name: 'timestamp', + displayName: 'timestampLabel', + type: 'date', + aggregatable: true, + searchable: true, + }, + { + name: 'start_date', + displayName: 'start_date', + type: 'date', + aggregatable: true, + searchable: true, + }, + { + name: 'bytes', + displayName: 'bytes', + type: 'number', + aggregatable: true, + searchable: true, + }, + { + name: 'memory', + displayName: 'memory', + type: 'number', + aggregatable: true, + searchable: true, + }, + { + name: 'source', + displayName: 'source', + type: 'string', + aggregatable: true, + searchable: true, + }, + { + name: 'dest', + displayName: 'dest', + type: 'string', + aggregatable: true, + searchable: true, + }, +]; + +const expectedIndexPatterns = { + 1: { + id: '1', + title: 'foo', + timeFieldName: 'timestamp', + hasRestrictions: false, + fields: fieldsOne, + getFieldByName: jest.fn(), + spec: {}, + isPersisted: true, + }, +}; + +const indexPatterns = expectedIndexPatterns; + +describe('IndexPattern Data Source', () => { + let baseState: TextBasedLanguagesPrivateState; + let textBasedLanguagesDatasource: Datasource< + TextBasedLanguagesPrivateState, + TextBasedLanguagesPersistedState + >; + + beforeEach(() => { + textBasedLanguagesDatasource = getTextBasedLanguagesDatasource({ + storage: {} as IStorageWrapper, + core: coreMock.createStart(), + data: dataPluginMock.createStartContract(), + dataViews: dataViewPluginMocks.createStartContract(), + expressions: expressionsPluginMock.createStartContract(), + }); + + baseState = { + layers: { + a: { + columns: [ + { + columnId: 'col1', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'col1', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + ], + index: 'foo', + query: { sql: 'SELECT * FROM foo' }, + }, + }, + } as unknown as TextBasedLanguagesPrivateState; + }); + + describe('uniqueLabels', () => { + it('appends a suffix to duplicates', () => { + const map = textBasedLanguagesDatasource.uniqueLabels({ + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Foo', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Foo', + meta: { + type: 'number', + }, + }, + ], + index: 'foo', + }, + }, + } as unknown as TextBasedLanguagesPrivateState); + + expect(map).toMatchInlineSnapshot(` + Object { + "a": "Foo", + "b": "Foo [1]", + } + `); + }); + }); + + describe('#getPersistedState', () => { + it('should persist from saved state', async () => { + expect(textBasedLanguagesDatasource.getPersistableState(baseState)).toEqual({ + state: baseState, + savedObjectReferences: [ + { name: 'textBasedLanguages-datasource-layer-a', type: 'index-pattern', id: 'foo' }, + ], + }); + }); + }); + + describe('#insertLayer', () => { + it('should insert an empty layer into the previous state', () => { + expect(textBasedLanguagesDatasource.insertLayer(baseState, 'newLayer')).toEqual({ + ...baseState, + layers: { + ...baseState.layers, + newLayer: { + index: 'foo', + query: { sql: 'SELECT * FROM foo' }, + allColumns: [ + { + columnId: 'col1', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + ], + columns: [], + }, + }, + }); + }); + }); + + describe('#removeLayer', () => { + it('should remove a layer', () => { + expect(textBasedLanguagesDatasource.removeLayer(baseState, 'a')).toEqual({ + ...baseState, + layers: { + a: { + columns: [], + allColumns: [ + { + columnId: 'col1', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + ], + query: { sql: 'SELECT * FROM foo' }, + index: 'foo', + }, + }, + }); + }); + }); + + describe('#createEmptyLayer', () => { + it('creates state with empty layers', () => { + expect(textBasedLanguagesDatasource.createEmptyLayer('index-pattern-id')).toEqual({ + fieldList: [], + layers: {}, + indexPatternRefs: [], + }); + }); + }); + + describe('#getLayers', () => { + it('should list the current layers', () => { + expect( + textBasedLanguagesDatasource.getLayers({ + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + query: { sql: 'SELECT * FROM foo' }, + index: 'foo', + }, + }, + } as unknown as TextBasedLanguagesPrivateState) + ).toEqual(['a']); + }); + }); + + describe('#getErrorMessages', () => { + it('should use the results of getErrorMessages directly when single layer', () => { + const state = { + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + errors: [new Error('error 1'), new Error('error 2')], + query: { sql: 'SELECT * FROM foo' }, + index: 'foo', + }, + }, + } as unknown as TextBasedLanguagesPrivateState; + expect(textBasedLanguagesDatasource.getErrorMessages(state, indexPatterns)).toEqual([ + { longMessage: 'error 1', shortMessage: 'error 1' }, + { longMessage: 'error 2', shortMessage: 'error 2' }, + ]); + }); + }); + + describe('#isTimeBased', () => { + it('should return true if timefield name exists on the dataview', () => { + const state = { + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + query: { sql: 'SELECT * FROM foo' }, + index: '1', + }, + }, + } as unknown as TextBasedLanguagesPrivateState; + expect( + textBasedLanguagesDatasource.isTimeBased(state, { + ...indexPatterns, + }) + ).toEqual(true); + }); + it('should return false if timefield name not exists on the selected dataview', () => { + const state = { + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + query: { sql: 'SELECT * FROM foo' }, + index: '1', + }, + }, + } as unknown as TextBasedLanguagesPrivateState; + expect( + textBasedLanguagesDatasource.isTimeBased(state, { + ...indexPatterns, + '1': { ...indexPatterns['1'], timeFieldName: undefined }, + }) + ).toEqual(false); + }); + }); + + describe('#toExpression', () => { + it('should generate an empty expression when no columns are selected', async () => { + const state = textBasedLanguagesDatasource.initialize(); + expect(textBasedLanguagesDatasource.toExpression(state, 'first', indexPatterns)).toEqual( + null + ); + }); + + it('should generate an expression for an SQL query', async () => { + const queryBaseState = { + layers: { + a: { + columns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + allColumns: [ + { + columnId: 'a', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'b', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + query: { sql: 'SELECT * FROM foo' }, + index: '1', + }, + }, + indexPatternRefs: [ + { id: '1', title: 'foo' }, + { id: '2', title: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern' }, + ], + } as unknown as TextBasedLanguagesPrivateState; + + expect(textBasedLanguagesDatasource.toExpression(queryBaseState, 'a', indexPatterns)) + .toMatchInlineSnapshot(` + Object { + "chain": Array [ + Object { + "arguments": Object {}, + "function": "kibana", + "type": "function", + }, + Object { + "arguments": Object {}, + "function": "kibana_context", + "type": "function", + }, + Object { + "arguments": Object { + "query": Array [ + "SELECT * FROM foo", + ], + }, + "function": "essql", + "type": "function", + }, + Object { + "arguments": Object { + "idMap": Array [ + "{\\"Test 1\\":[{\\"id\\":\\"a\\",\\"label\\":\\"Test 1\\"}],\\"Test 2\\":[{\\"id\\":\\"b\\",\\"label\\":\\"Test 2\\"}]}", + ], + }, + "function": "lens_map_to_columns", + "type": "function", + }, + ], + "type": "expression", + } + `); + }); + }); + + describe('#getPublicAPI', () => { + let publicAPI: DatasourcePublicAPI; + + beforeEach(async () => { + publicAPI = textBasedLanguagesDatasource.getPublicAPI({ + state: baseState, + layerId: 'a', + indexPatterns, + }); + }); + + describe('getTableSpec', () => { + it('should include col1', () => { + expect(publicAPI.getTableSpec()).toEqual([expect.objectContaining({ columnId: 'col1' })]); + }); + + it('should include fields prop for each column', () => { + expect(publicAPI.getTableSpec()).toEqual([expect.objectContaining({ fields: ['Test 1'] })]); + }); + + it('should collect all fields ', () => { + const state = { + layers: { + a: { + columns: [ + { + columnId: 'col1', + fieldName: 'Test 1', + meta: { + type: 'number', + }, + }, + { + columnId: 'col2', + fieldName: 'Test 2', + meta: { + type: 'number', + }, + }, + ], + index: 'foo', + }, + }, + } as unknown as TextBasedLanguagesPrivateState; + + publicAPI = textBasedLanguagesDatasource.getPublicAPI({ + state, + layerId: 'a', + indexPatterns, + }); + expect(publicAPI.getTableSpec()).toEqual([ + { columnId: 'col1', fields: ['Test 1'] }, + { columnId: 'col2', fields: ['Test 2'] }, + ]); + }); + }); + + describe('getOperationForColumnId', () => { + it('should get an operation for col1', () => { + expect(publicAPI.getOperationForColumnId('col1')).toEqual({ + label: 'Test 1', + dataType: 'number', + isBucketed: false, + hasTimeShift: false, + }); + }); + + it('should return null for non-existant columns', () => { + expect(publicAPI.getOperationForColumnId('col2')).toBe(null); + }); + }); + + describe('getSourceId', () => { + it('should basically return the datasource internal id', () => { + expect(publicAPI.getSourceId()).toEqual('foo'); + }); + }); + }); +}); diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.tsx b/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.tsx new file mode 100644 index 0000000000000..5a03500c76fbf --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/text_based_languages.tsx @@ -0,0 +1,587 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { render } from 'react-dom'; +import { I18nProvider } from '@kbn/i18n-react'; +import { CoreStart } from '@kbn/core/public'; +import { i18n } from '@kbn/i18n'; +import { IStorageWrapper } from '@kbn/kibana-utils-plugin/public'; +import type { AggregateQuery } from '@kbn/es-query'; +import type { SavedObjectReference } from '@kbn/core/public'; +import { EuiButtonEmpty, EuiFormRow } from '@elastic/eui'; +import type { ExpressionsStart } from '@kbn/expressions-plugin/public'; +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import { DataPublicPluginStart } from '@kbn/data-plugin/public'; +import { + DatasourceDimensionEditorProps, + DatasourceDataPanelProps, + DatasourceLayerPanelProps, + PublicAPIProps, + DataType, + TableChangeType, + DatasourceDimensionTriggerProps, +} from '../types'; +import { generateId } from '../id_generator'; +import { toExpression } from './to_expression'; +import { TextBasedLanguagesDataPanel } from './datapanel'; +import type { + TextBasedLanguagesPrivateState, + TextBasedLanguagesPersistedState, + TextBasedLanguagesLayerColumn, + TextBasedLanguageField, +} from './types'; +import { FieldSelect } from './field_select'; +import { Datasource } from '../types'; +import { LayerPanel } from './layerpanel'; + +function getLayerReferenceName(layerId: string) { + return `textBasedLanguages-datasource-layer-${layerId}`; +} + +export function getTextBasedLanguagesDatasource({ + core, + storage, + data, + expressions, + dataViews, +}: { + core: CoreStart; + storage: IStorageWrapper; + data: DataPublicPluginStart; + expressions: ExpressionsStart; + dataViews: DataViewsPublicPluginStart; +}) { + const getSuggestionsForState = (state: TextBasedLanguagesPrivateState) => { + return Object.entries(state.layers)?.map(([id, layer]) => { + return { + state: { + ...state, + }, + table: { + changeType: 'unchanged' as TableChangeType, + isMultiRow: false, + layerId: id, + columns: + layer.columns?.map((f) => { + return { + columnId: f.columnId, + operation: { + dataType: f?.meta?.type as DataType, + label: f.fieldName, + isBucketed: Boolean(f?.meta?.type !== 'number'), + }, + }; + }) ?? [], + }, + keptLayerIds: [id], + }; + }); + }; + const TextBasedLanguagesDatasource: Datasource< + TextBasedLanguagesPrivateState, + TextBasedLanguagesPersistedState + > = { + id: 'textBasedLanguages', + + checkIntegrity: () => { + return []; + }, + getErrorMessages: (state) => { + const errors: Error[] = []; + + Object.values(state.layers).forEach((layer) => { + if (layer.errors && layer.errors.length > 0) { + errors.push(...layer.errors); + } + }); + return errors.map((err) => { + return { + shortMessage: err.message, + longMessage: err.message, + }; + }); + }, + getUnifiedSearchErrors: (state) => { + const errors: Error[] = []; + + Object.values(state.layers).forEach((layer) => { + if (layer.errors && layer.errors.length > 0) { + errors.push(...layer.errors); + } + }); + return errors; + }, + initialize( + state?: TextBasedLanguagesPersistedState, + savedObjectReferences?, + context?, + indexPatternRefs?, + indexPatterns? + ) { + const patterns = indexPatterns ? Object.values(indexPatterns) : []; + const refs = patterns.map((p) => { + return { + id: p.id, + title: p.title, + timeField: p.timeFieldName, + }; + }); + + const initState = state || { layers: {} }; + return { + ...initState, + fieldList: [], + indexPatternRefs: refs, + }; + }, + onRefreshIndexPattern() {}, + + getUsedDataViews: (state) => { + return Object.values(state.layers).map(({ index }) => index); + }, + + getPersistableState({ layers }: TextBasedLanguagesPrivateState) { + const savedObjectReferences: SavedObjectReference[] = []; + Object.entries(layers).forEach(([layerId, { index, ...persistableLayer }]) => { + if (index) { + savedObjectReferences.push({ + type: 'index-pattern', + id: index, + name: getLayerReferenceName(layerId), + }); + } + }); + return { state: { layers }, savedObjectReferences }; + }, + isValidColumn(state, indexPatterns, layerId, columnId) { + const layer = state.layers[layerId]; + const column = layer.columns.find((c) => c.columnId === columnId); + const indexPattern = indexPatterns[layer.index]; + if (!column || !indexPattern) return false; + return true; + }, + insertLayer(state: TextBasedLanguagesPrivateState, newLayerId: string) { + const layer = Object.values(state?.layers)?.[0]; + const query = layer?.query; + const columns = layer?.allColumns ?? []; + const index = + layer?.index ?? + (JSON.parse(localStorage.getItem('lens-settings') || '{}').indexPatternId || + state.indexPatternRefs[0].id); + return { + ...state, + layers: { + ...state.layers, + [newLayerId]: blankLayer(index, query, columns), + }, + }; + }, + createEmptyLayer() { + return { + indexPatternRefs: [], + layers: {}, + fieldList: [], + }; + }, + + cloneLayer(state, layerId, newLayerId, getNewId) { + return { + ...state, + }; + }, + + removeLayer(state: TextBasedLanguagesPrivateState, layerId: string) { + const newLayers = { + ...state.layers, + [layerId]: { + ...state.layers[layerId], + columns: [], + }, + }; + + return { + ...state, + layers: newLayers, + fieldList: state.fieldList, + }; + }, + + clearLayer(state: TextBasedLanguagesPrivateState, layerId: string) { + return { + ...state, + layers: { + ...state.layers, + [layerId]: { ...state.layers[layerId], columns: [] }, + }, + }; + }, + + getLayers(state: TextBasedLanguagesPrivateState) { + return state && state.layers ? Object.keys(state?.layers) : []; + }, + getCurrentIndexPatternId(state: TextBasedLanguagesPrivateState) { + const layers = Object.values(state.layers); + return layers?.[0]?.index; + }, + isTimeBased: (state, indexPatterns) => { + if (!state) return false; + const { layers } = state; + return ( + Boolean(layers) && + Object.values(layers).some((layer) => { + return Boolean(indexPatterns[layer.index]?.timeFieldName); + }) + ); + }, + getUsedDataView: (state: TextBasedLanguagesPrivateState, layerId: string) => { + return state.layers[layerId].index; + }, + + removeColumn({ prevState, layerId, columnId }) { + return { + ...prevState, + layers: { + ...prevState.layers, + [layerId]: { + ...prevState.layers[layerId], + columns: prevState.layers[layerId].columns.filter((col) => col.columnId !== columnId), + }, + }, + }; + }, + + toExpression: (state, layerId, indexPatterns) => { + return toExpression(state, layerId); + }, + + renderDataPanel( + domElement: Element, + props: DatasourceDataPanelProps + ) { + render( + + + , + domElement + ); + }, + + renderDimensionTrigger: ( + domElement: Element, + props: DatasourceDimensionTriggerProps + ) => { + const columnLabelMap = TextBasedLanguagesDatasource.uniqueLabels(props.state); + const layer = props.state.layers[props.layerId]; + const selectedField = layer?.allColumns?.find((column) => column.columnId === props.columnId); + let customLabel: string | undefined = columnLabelMap[props.columnId]; + if (!customLabel) { + customLabel = selectedField?.fieldName; + } + + const columnExists = props.state.fieldList.some((f) => f.name === selectedField?.fieldName); + + render( + {}}> + {customLabel ?? + i18n.translate('xpack.lens.textBasedLanguages.missingField', { + defaultMessage: 'Missing field', + })} + , + domElement + ); + }, + + getRenderEventCounters(state: TextBasedLanguagesPrivateState): string[] { + return []; + }, + + renderDimensionEditor: ( + domElement: Element, + props: DatasourceDimensionEditorProps + ) => { + const fields = props.state.fieldList; + const selectedField = props.state.layers[props.layerId]?.allColumns?.find( + (column) => column.columnId === props.columnId + ); + render( + + { + const meta = fields.find((f) => f.name === choice.field)?.meta; + const newColumn = { + columnId: props.columnId, + fieldName: choice.field, + meta, + }; + return props.setState( + !selectedField + ? { + ...props.state, + layers: { + ...props.state.layers, + [props.layerId]: { + ...props.state.layers[props.layerId], + columns: [...props.state.layers[props.layerId].columns, newColumn], + allColumns: [...props.state.layers[props.layerId].allColumns, newColumn], + }, + }, + } + : { + ...props.state, + layers: { + ...props.state.layers, + [props.layerId]: { + ...props.state.layers[props.layerId], + columns: props.state.layers[props.layerId].columns.map((col) => + col.columnId !== props.columnId + ? col + : { ...col, fieldName: choice.field } + ), + allColumns: props.state.layers[props.layerId].allColumns.map((col) => + col.columnId !== props.columnId + ? col + : { ...col, fieldName: choice.field } + ), + }, + }, + } + ); + }} + /> + , + domElement + ); + }, + + renderLayerPanel: ( + domElement: Element, + props: DatasourceLayerPanelProps + ) => { + render( + + + , + domElement + ); + }, + + uniqueLabels(state: TextBasedLanguagesPrivateState) { + const layers = state.layers; + const columnLabelMap = {} as Record; + const counts = {} as Record; + + const makeUnique = (label: string) => { + let uniqueLabel = label; + + while (counts[uniqueLabel] >= 0) { + const num = ++counts[uniqueLabel]; + uniqueLabel = i18n.translate('xpack.lens.indexPattern.uniqueLabel', { + defaultMessage: '{label} [{num}]', + values: { label, num }, + }); + } + + counts[uniqueLabel] = 0; + return uniqueLabel; + }; + Object.values(layers).forEach((layer) => { + if (!layer.columns) { + return; + } + Object.values(layer.columns).forEach((column) => { + columnLabelMap[column.columnId] = makeUnique(column.fieldName); + }); + }); + + return columnLabelMap; + }, + + getDropProps: (props) => { + const { source } = props; + if (!source) { + return; + } + const label = source.field as string; + return { dropTypes: ['field_add'], nextLabel: label }; + }, + + onDrop: (props) => { + const { dropType, state, source, target } = props; + const { layers } = state; + + if (dropType === 'field_add') { + Object.keys(layers).forEach((layerId) => { + const currentLayer = layers[layerId]; + const field = currentLayer.allColumns.find((f) => f.columnId === source.id); + const newColumn = { + columnId: target.columnId, + fieldName: field?.fieldName ?? '', + meta: field?.meta, + }; + const columns = currentLayer.columns.filter((c) => c.columnId !== target.columnId); + columns.push(newColumn); + + const allColumns = currentLayer.allColumns.filter((c) => c.columnId !== target.columnId); + allColumns.push(newColumn); + + props.setState({ + ...props.state, + layers: { + ...props.state.layers, + [layerId]: { + ...props.state.layers[layerId], + columns, + allColumns, + }, + }, + }); + }); + return true; + } + return false; + }, + + getPublicAPI({ state, layerId }: PublicAPIProps) { + return { + datasourceId: 'textBasedLanguages', + + getTableSpec: () => { + return ( + state.layers[layerId]?.columns?.map((column) => ({ + columnId: column.columnId, + fields: [column.fieldName], + })) || [] + ); + }, + getOperationForColumnId: (columnId: string) => { + const layer = state.layers[layerId]; + const column = layer?.allColumns?.find((c) => c.columnId === columnId); + const columnLabelMap = TextBasedLanguagesDatasource.uniqueLabels(state); + + if (column) { + return { + dataType: column?.meta?.type as DataType, + label: columnLabelMap[columnId] ?? column?.fieldName, + isBucketed: Boolean(column?.meta?.type !== 'number'), + hasTimeShift: false, + }; + } + return null; + }, + getVisualDefaults: () => ({}), + isTextBasedLanguage: () => true, + getMaxPossibleNumValues: (columnId) => { + return null; + }, + getSourceId: () => { + const layer = state.layers[layerId]; + return layer.index; + }, + getFilters: () => { + return { + enabled: { + kuery: [], + lucene: [], + }, + disabled: { + kuery: [], + lucene: [], + }, + }; + }, + }; + }, + getDatasourceSuggestionsForField(state, draggedField) { + const field = state.fieldList.find( + (f) => f.id === (draggedField as TextBasedLanguageField).id + ); + if (!field) return []; + return Object.entries(state.layers)?.map(([id, layer]) => { + const newId = generateId(); + const newColumn = { + columnId: newId, + fieldName: field?.name ?? '', + meta: field?.meta, + }; + return { + state: { + ...state, + layers: { + ...state.layers, + [id]: { + ...state.layers[id], + columns: [...layer.columns, newColumn], + allColumns: [...layer.allColumns, newColumn], + }, + }, + }, + table: { + changeType: 'initial' as TableChangeType, + isMultiRow: false, + layerId: id, + columns: [ + ...layer.columns?.map((f) => { + return { + columnId: f.columnId, + operation: { + dataType: f?.meta?.type as DataType, + label: f.fieldName, + isBucketed: Boolean(f?.meta?.type !== 'number'), + }, + }; + }), + { + columnId: newId, + operation: { + dataType: field?.meta?.type as DataType, + label: field?.name ?? '', + isBucketed: Boolean(field?.meta?.type !== 'number'), + }, + }, + ], + }, + keptLayerIds: [id], + }; + }); + return []; + }, + getDatasourceSuggestionsForVisualizeField: getSuggestionsForState, + getDatasourceSuggestionsFromCurrentState: getSuggestionsForState, + getDatasourceSuggestionsForVisualizeCharts: getSuggestionsForState, + isEqual: () => true, + }; + + return TextBasedLanguagesDatasource; +} + +function blankLayer( + index: string, + query?: AggregateQuery, + columns?: TextBasedLanguagesLayerColumn[] +) { + return { + index, + query, + columns: [], + allColumns: columns ?? [], + }; +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/to_expression.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/to_expression.ts new file mode 100644 index 0000000000000..aa7a264673a3e --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/to_expression.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Ast } from '@kbn/interpreter'; +import { textBasedQueryStateToExpressionAst } from '@kbn/data-plugin/common'; +import type { OriginalColumn } from '../../common/types'; +import { TextBasedLanguagesPrivateState, TextBasedLanguagesLayer, IndexPatternRef } from './types'; + +function getExpressionForLayer( + layer: TextBasedLanguagesLayer, + refs: IndexPatternRef[] +): Ast | null { + if (!layer.columns || layer.columns?.length === 0) { + return null; + } + + let idMapper: Record = {}; + layer.columns.forEach((col) => { + if (idMapper[col.fieldName]) { + idMapper[col.fieldName].push({ + id: col.columnId, + label: col.fieldName, + } as OriginalColumn); + } else { + idMapper = { + ...idMapper, + [col.fieldName]: [ + { + id: col.columnId, + label: col.fieldName, + } as OriginalColumn, + ], + }; + } + }); + const timeFieldName = refs.find((r) => r.id === layer.index)?.timeField; + const textBasedQueryToAst = textBasedQueryStateToExpressionAst({ + query: layer.query, + timeFieldName, + }); + + textBasedQueryToAst.chain.push({ + type: 'function', + function: 'lens_map_to_columns', + arguments: { + idMap: [JSON.stringify(idMapper)], + }, + }); + return textBasedQueryToAst; +} + +export function toExpression(state: TextBasedLanguagesPrivateState, layerId: string) { + if (state.layers[layerId]) { + return getExpressionForLayer(state.layers[layerId], state.indexPatternRefs); + } + + return null; +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/types.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/types.ts new file mode 100644 index 0000000000000..2ea1692cf37c0 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/types.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; +import type { AggregateQuery } from '@kbn/es-query'; + +export interface TextBasedLanguagesLayerColumn { + columnId: string; + fieldName: string; + meta?: DatatableColumn['meta']; +} + +export interface TextBasedLanguageField { + id: string; + field: string; +} + +export interface TextBasedLanguagesLayer { + index: string; + query: AggregateQuery | undefined; + columns: TextBasedLanguagesLayerColumn[]; + allColumns: TextBasedLanguagesLayerColumn[]; + timeField?: string; + errors?: Error[]; +} + +export interface TextBasedLanguagesPersistedState { + layers: Record; +} + +export type TextBasedLanguagesPrivateState = TextBasedLanguagesPersistedState & { + indexPatternRefs: IndexPatternRef[]; + fieldList: DatatableColumn[]; +}; + +export interface IndexPatternRef { + id: string; + title: string; + timeField?: string; +} diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/utils.test.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/utils.test.ts new file mode 100644 index 0000000000000..1cbd830a92fc2 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/utils.test.ts @@ -0,0 +1,193 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; + +import { dataPluginMock } from '@kbn/data-plugin/public/mocks'; +import { expressionsPluginMock } from '@kbn/expressions-plugin/public/mocks'; +import { dataViewPluginMocks } from '@kbn/data-views-plugin/public/mocks'; +import { mockDataViewsService } from '../data_views_service/mocks'; +import { + getIndexPatternFromTextBasedQuery, + loadIndexPatternRefs, + getStateFromAggregateQuery, +} from './utils'; +import { type AggregateQuery } from '@kbn/es-query'; + +jest.mock('./fetch_data_from_aggregate_query', () => ({ + fetchDataFromAggregateQuery: jest.fn(() => { + return { + columns: [ + { + name: 'timestamp', + id: 'timestamp', + meta: { + type: 'date', + }, + }, + { + name: 'bytes', + id: 'bytes', + meta: { + type: 'number', + }, + }, + { + name: 'memory', + id: 'memory', + meta: { + type: 'number', + }, + }, + ], + }; + }), +})); + +describe('Text based languages utils', () => { + describe('getIndexPatternFromTextBasedQuery', () => { + it('should return the index pattern for sql query', () => { + const indexPattern = getIndexPatternFromTextBasedQuery({ + sql: 'SELECT bytes, memory from foo', + }); + + expect(indexPattern).toBe('foo'); + }); + + it('should return empty index pattern for non sql query', () => { + const indexPattern = getIndexPatternFromTextBasedQuery({ + lang1: 'SELECT bytes, memory from foo', + } as unknown as AggregateQuery); + + expect(indexPattern).toBe(''); + }); + }); + + describe('loadIndexPatternRefs', () => { + it('should return a list of sorted indexpattern refs', async () => { + const refs = await loadIndexPatternRefs(mockDataViewsService() as DataViewsPublicPluginStart); + expect(refs[0].title < refs[1].title).toBeTruthy(); + }); + }); + + describe('getStateFromAggregateQuery', () => { + it('should return the correct state', async () => { + const state = { + layers: { + first: { + allColumns: [], + columns: [], + query: undefined, + index: '', + }, + }, + }; + const dataViewsMock = dataViewPluginMocks.createStartContract(); + const dataMock = dataPluginMock.createStartContract(); + const expressionsMock = expressionsPluginMock.createStartContract(); + const updatedState = await getStateFromAggregateQuery( + state, + { sql: 'SELECT * FROM my-fake-index-pattern' }, + { + ...dataViewsMock, + getIdsWithTitle: jest.fn().mockReturnValue( + Promise.resolve([ + { id: '1', title: 'my-fake-index-pattern' }, + { id: '2', title: 'my-fake-restricted-pattern' }, + { id: '3', title: 'my-compatible-pattern' }, + ]) + ), + get: jest.fn().mockReturnValue( + Promise.resolve({ + id: '1', + title: 'my-fake-index-pattern', + timeFieldName: 'timeField', + }) + ), + }, + dataMock, + expressionsMock + ); + + expect(updatedState).toStrictEqual({ + fieldList: [ + { + name: 'timestamp', + id: 'timestamp', + meta: { + type: 'date', + }, + }, + { + name: 'bytes', + id: 'bytes', + meta: { + type: 'number', + }, + }, + { + name: 'memory', + id: 'memory', + meta: { + type: 'number', + }, + }, + ], + indexPatternRefs: [ + { + id: '3', + timeField: 'timeField', + title: 'my-compatible-pattern', + }, + { + id: '1', + timeField: 'timeField', + title: 'my-fake-index-pattern', + }, + { + id: '2', + timeField: 'timeField', + title: 'my-fake-restricted-pattern', + }, + ], + layers: { + first: { + allColumns: [ + { + fieldName: 'timestamp', + columnId: 'timestamp', + meta: { + type: 'date', + }, + }, + { + fieldName: 'bytes', + columnId: 'bytes', + meta: { + type: 'number', + }, + }, + { + fieldName: 'memory', + columnId: 'memory', + meta: { + type: 'number', + }, + }, + ], + columns: [], + errors: [], + index: '1', + query: { + sql: 'SELECT * FROM my-fake-index-pattern', + }, + timeField: 'timeField', + }, + }, + }); + }); + }); +}); diff --git a/x-pack/plugins/lens/public/text_based_languages_datasource/utils.ts b/x-pack/plugins/lens/public/text_based_languages_datasource/utils.ts new file mode 100644 index 0000000000000..6c17d5206efb0 --- /dev/null +++ b/x-pack/plugins/lens/public/text_based_languages_datasource/utils.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; +import type { ExpressionsStart } from '@kbn/expressions-plugin/public'; + +import { type AggregateQuery, getIndexPatternFromSQLQuery } from '@kbn/es-query'; +import type { DatatableColumn } from '@kbn/expressions-plugin/public'; +import { generateId } from '../id_generator'; +import { fetchDataFromAggregateQuery } from './fetch_data_from_aggregate_query'; + +import type { + IndexPatternRef, + TextBasedLanguagesPersistedState, + TextBasedLanguagesLayerColumn, +} from './types'; + +export async function loadIndexPatternRefs( + indexPatternsService: DataViewsPublicPluginStart +): Promise { + const indexPatterns = await indexPatternsService.getIdsWithTitle(); + + const timefields = await Promise.all( + indexPatterns.map((p) => indexPatternsService.get(p.id).then((pat) => pat.timeFieldName)) + ); + + return indexPatterns + .map((p, i) => ({ ...p, timeField: timefields[i] })) + .sort((a, b) => { + return a.title.localeCompare(b.title); + }); +} + +export async function getStateFromAggregateQuery( + state: TextBasedLanguagesPersistedState, + query: AggregateQuery, + dataViews: DataViewsPublicPluginStart, + data: DataPublicPluginStart, + expressions: ExpressionsStart +) { + const indexPatternRefs: IndexPatternRef[] = await loadIndexPatternRefs(dataViews); + const errors: Error[] = []; + const layerIds = Object.keys(state.layers); + const newLayerId = layerIds.length > 0 ? layerIds[0] : generateId(); + // fetch the pattern from the query + const indexPattern = getIndexPatternFromTextBasedQuery(query); + // get the id of the dataview + const index = indexPatternRefs.find((r) => r.title === indexPattern)?.id ?? ''; + let columnsFromQuery: DatatableColumn[] = []; + let columns: TextBasedLanguagesLayerColumn[] = []; + let timeFieldName; + try { + const table = await fetchDataFromAggregateQuery(query, dataViews, data, expressions); + const dataView = await dataViews.get(index); + timeFieldName = dataView.timeFieldName; + columnsFromQuery = table?.columns ?? []; + const existingColumns = state.layers[newLayerId].allColumns; + columns = [ + ...existingColumns, + ...columnsFromQuery.map((c) => ({ columnId: c.id, fieldName: c.id, meta: c.meta })), + ]; + } catch (e) { + errors.push(e); + } + + const tempState = { + layers: { + [newLayerId]: { + index, + query, + columns: state.layers[newLayerId].columns ?? [], + allColumns: columns, + timeField: timeFieldName, + errors, + }, + }, + }; + + return { + ...tempState, + fieldList: columnsFromQuery ?? [], + indexPatternRefs, + }; +} + +export function getIndexPatternFromTextBasedQuery(query: AggregateQuery): string { + let indexPattern = ''; + // sql queries + if ('sql' in query) { + indexPattern = getIndexPatternFromSQLQuery(query.sql); + } + // other textbased queries.... + + return indexPattern; +} diff --git a/x-pack/plugins/lens/public/trigger_actions/visualize_agg_based_vis_actions.ts b/x-pack/plugins/lens/public/trigger_actions/visualize_agg_based_vis_actions.ts new file mode 100644 index 0000000000000..a5300d550f2c7 --- /dev/null +++ b/x-pack/plugins/lens/public/trigger_actions/visualize_agg_based_vis_actions.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; +import { createAction } from '@kbn/ui-actions-plugin/public'; +import { + ACTION_CONVERT_TO_LENS, + ACTION_CONVERT_AGG_BASED_TO_LENS, +} from '@kbn/visualizations-plugin/public'; +import type { ApplicationStart } from '@kbn/core/public'; +import type { VisualizeEditorContext } from '../types'; + +export const visualizeAggBasedVisAction = (application: ApplicationStart) => + createAction<{ [key: string]: VisualizeEditorContext }>({ + type: ACTION_CONVERT_TO_LENS, + id: ACTION_CONVERT_AGG_BASED_TO_LENS, + getDisplayName: () => + i18n.translate('xpack.lens.visualizeAggBasedLegend', { + defaultMessage: 'Visualize agg based chart', + }), + isCompatible: async () => !!application.capabilities.visualize.show, + execute: async (context: { [key: string]: VisualizeEditorContext }) => { + const table = Object.values(context.layers); + const payload = { + ...context, + layers: table, + isVisualizeAction: true, + }; + application.navigateToApp('lens', { + state: { + type: ACTION_CONVERT_TO_LENS, + payload, + originatingApp: i18n.translate('xpack.lens.AggBasedLabel', { + defaultMessage: 'aggregation based visualization', + }), + }, + }); + }, + }); diff --git a/x-pack/plugins/lens/public/types.ts b/x-pack/plugins/lens/public/types.ts index e581064bcdbf2..32fc21cc4a61d 100644 --- a/x-pack/plugins/lens/public/types.ts +++ b/x-pack/plugins/lens/public/types.ts @@ -17,7 +17,7 @@ import type { IInterpreterRenderHandlers, Datatable, } from '@kbn/expressions-plugin/public'; -import type { NavigateToLensContext } from '@kbn/visualizations-plugin/common'; +import type { Configuration, NavigateToLensContext } from '@kbn/visualizations-plugin/common'; import { Adapters } from '@kbn/inspector-plugin/public'; import type { Query } from '@kbn/es-query'; import type { @@ -217,13 +217,13 @@ export interface InitializationOptions { isFullEditor?: boolean; } -export type VisualizeEditorContext = { +export type VisualizeEditorContext = { savedObjectId?: string; embeddableId?: string; vizEditorOriginatingAppUrl?: string; originatingApp?: string; isVisualizeAction: boolean; -} & NavigateToLensContext; +} & NavigateToLensContext; export interface GetDropPropsArgs { state: T; @@ -259,8 +259,10 @@ export interface Datasource { // Given the current state, which parts should be saved? getPersistableState: (state: T) => { state: P; savedObjectReferences: SavedObjectReference[] }; getCurrentIndexPatternId: (state: T) => string; + getUnifiedSearchErrors?: (state: T) => Error[]; insertLayer: (state: T, newLayerId: string) => T; + createEmptyLayer: (indexPatternId: string) => T; removeLayer: (state: T, layerId: string) => T; clearLayer: (state: T, layerId: string) => T; cloneLayer: ( @@ -466,6 +468,10 @@ export interface DatasourcePublicAPI { * Retrieve the specific source id for the current state */ getSourceId: () => string | undefined; + /** + * Returns true if this is a text based language datasource + */ + isTextBasedLanguage: () => boolean; /** * Collect all defined filters from all the operations in the layer. If it returns undefined, this means that filters can't be constructed for the current layer */ @@ -698,7 +704,6 @@ export type VisualizationDimensionGroupConfig = SharedDimensionProps & { supportsMoreColumns: boolean; dimensionsTooMany?: number; /** If required, a warning will appear if accessors are empty */ - required?: boolean; requiredMinDimensionCount?: number; dataTestSubj?: string; prioritizedOperation?: string; @@ -1123,7 +1128,7 @@ export interface Visualization { getSuggestionFromConvertToLensContext?: ( props: VisualizationStateFromContextChangeProps - ) => Suggestion; + ) => Suggestion | undefined; } // Use same technique as TriggerContext diff --git a/x-pack/plugins/lens/public/visualizations/datatable/visualization.tsx b/x-pack/plugins/lens/public/visualizations/datatable/visualization.tsx index 8cc30c65ed1a9..ca6f6775f8934 100644 --- a/x-pack/plugins/lens/public/visualizations/datatable/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/datatable/visualization.tsx @@ -20,6 +20,7 @@ import type { Visualization, VisualizationSuggestion, DatasourceLayers, + Suggestion, } from '../../types'; import { TableDimensionEditor } from './components/dimension_editor'; import { TableDimensionEditorAdditionalSection } from './components/dimension_editor_addtional_section'; @@ -27,6 +28,7 @@ import { LayerType, layerTypes } from '../../../common'; import { getDefaultSummaryLabel, PagingState } from '../../../common/expressions'; import type { ColumnState, SortingState } from '../../../common/expressions'; import { DataTableToolbar } from './components/toolbar'; +import { IndexPatternLayer } from '../../indexpattern_datasource/types'; export interface DatatableVisualizationState { columns: ColumnState[]; @@ -40,6 +42,16 @@ export interface DatatableVisualizationState { paging?: PagingState; } +interface DatatableDatasourceState { + [prop: string]: unknown; + layers: IndexPatternLayer[]; +} + +export interface DatatableSuggestion extends Suggestion { + datasourceState: DatatableDatasourceState; + visualizationState: DatatableVisualizationState; +} + const visualizationLabel = i18n.translate('xpack.lens.datatable.label', { defaultMessage: 'Table', }); @@ -149,11 +161,19 @@ export const getDatatableVisualization = ({ }, }); + const changeType = table.changeType; + const changeFactor = + changeType === 'reduced' || changeType === 'layers' + ? 0.3 + : changeType === 'unchanged' + ? 0.5 + : 1; + return [ { title, // table with >= 10 columns will have a score of 0.4, fewer columns reduce score - score: (Math.min(table.columns.length, 10) / 10) * 0.4, + score: (Math.min(table.columns.length, 10) / 10) * 0.4 * changeFactor, state: { ...(state || {}), layerId: table.layerId, @@ -265,12 +285,12 @@ export const getDatatableVisualization = ({ .filter((c) => !datasource!.getOperationForColumnId(c)?.isBucketed) .map((accessor) => { const columnConfig = columnMap[accessor]; - const stops = columnConfig.palette?.params?.stops; - const hasColoring = Boolean(columnConfig.colorMode !== 'none' && stops); + const stops = columnConfig?.palette?.params?.stops; + const hasColoring = Boolean(columnConfig?.colorMode !== 'none' && stops); return { columnId: accessor, - triggerIcon: columnConfig.hidden + triggerIcon: columnConfig?.hidden ? 'invisible' : hasColoring ? 'colorBy' @@ -280,7 +300,7 @@ export const getDatatableVisualization = ({ }), supportsMoreColumns: true, filterOperations: (op) => !op.isBucketed, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsDatatable_metrics', enableDimensionEditor: true, }, @@ -583,6 +603,26 @@ export const getDatatableVisualization = ({ return state; } }, + getSuggestionFromConvertToLensContext({ suggestions, context }) { + const allSuggestions = suggestions as DatatableSuggestion[]; + return { + ...allSuggestions[0], + datasourceState: { + ...allSuggestions[0].datasourceState, + layers: allSuggestions.reduce( + (acc, s) => ({ + ...acc, + ...s.datasourceState.layers, + }), + {} + ), + }, + visualizationState: { + ...allSuggestions[0].visualizationState, + ...context.configuration, + }, + }; + }, }); function getDataSourceAndSortedColumns( diff --git a/x-pack/plugins/lens/public/visualizations/gauge/visualization.test.ts b/x-pack/plugins/lens/public/visualizations/gauge/visualization.test.ts index 94c9ce28987bf..e999cac9dd0e6 100644 --- a/x-pack/plugins/lens/public/visualizations/gauge/visualization.test.ts +++ b/x-pack/plugins/lens/public/visualizations/gauge/visualization.test.ts @@ -105,7 +105,7 @@ describe('gauge', () => { accessors: [{ columnId: 'metric-accessor', triggerIcon: 'none' }], filterOperations: isNumericDynamicMetric, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsGauge_metricDimensionPanel', enableDimensionEditor: true, enableFormatSelector: true, @@ -155,7 +155,7 @@ describe('gauge', () => { accessors: [{ columnId: 'goal-accessor' }], filterOperations: isNumericMetric, supportsMoreColumns: false, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsGauge_goalDimensionPanel', enableFormatSelector: false, supportStaticValue: true, @@ -187,7 +187,7 @@ describe('gauge', () => { accessors: [], filterOperations: isNumericDynamicMetric, supportsMoreColumns: true, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsGauge_metricDimensionPanel', enableDimensionEditor: true, enableFormatSelector: true, @@ -237,7 +237,7 @@ describe('gauge', () => { accessors: [], filterOperations: isNumericMetric, supportsMoreColumns: true, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsGauge_goalDimensionPanel', enableFormatSelector: false, supportStaticValue: true, @@ -275,7 +275,7 @@ describe('gauge', () => { accessors: [{ columnId: 'metric-accessor', triggerIcon: 'none' }], filterOperations: isNumericDynamicMetric, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsGauge_metricDimensionPanel', enableDimensionEditor: true, enableFormatSelector: true, @@ -325,7 +325,7 @@ describe('gauge', () => { accessors: [{ columnId: 'goal-accessor' }], filterOperations: isNumericMetric, supportsMoreColumns: false, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsGauge_goalDimensionPanel', enableFormatSelector: false, supportStaticValue: true, @@ -368,7 +368,7 @@ describe('gauge', () => { accessors: [{ columnId: 'metric-accessor', triggerIcon: 'none' }], filterOperations: isNumericDynamicMetric, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsGauge_metricDimensionPanel', enableDimensionEditor: true, enableFormatSelector: true, @@ -422,7 +422,7 @@ describe('gauge', () => { accessors: [{ columnId: 'goal-accessor' }], filterOperations: isNumericMetric, supportsMoreColumns: false, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsGauge_goalDimensionPanel', enableFormatSelector: false, supportStaticValue: true, diff --git a/x-pack/plugins/lens/public/visualizations/gauge/visualization.tsx b/x-pack/plugins/lens/public/visualizations/gauge/visualization.tsx index 37d10918d4129..19fd46459b2b7 100644 --- a/x-pack/plugins/lens/public/visualizations/gauge/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/gauge/visualization.tsx @@ -275,7 +275,7 @@ export const getGaugeVisualization = ({ : [], filterOperations: isNumericDynamicMetric, supportsMoreColumns: !metricAccessor, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsGauge_metricDimensionPanel', enableDimensionEditor: true, }, @@ -352,7 +352,7 @@ export const getGaugeVisualization = ({ accessors: state.goalAccessor ? [{ columnId: state.goalAccessor }] : [], filterOperations: isNumericMetric, supportsMoreColumns: !state.goalAccessor, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsGauge_goalDimensionPanel', }, ], diff --git a/x-pack/plugins/lens/public/visualizations/heatmap/visualization.test.ts b/x-pack/plugins/lens/public/visualizations/heatmap/visualization.test.ts index ee6a7030a0c9d..38cfa9bf10b54 100644 --- a/x-pack/plugins/lens/public/visualizations/heatmap/visualization.test.ts +++ b/x-pack/plugins/lens/public/visualizations/heatmap/visualization.test.ts @@ -136,7 +136,7 @@ describe('heatmap', () => { accessors: [{ columnId: 'x-accessor' }], filterOperations: filterOperationsAxis, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_xDimensionPanel', }, { @@ -146,7 +146,7 @@ describe('heatmap', () => { accessors: [{ columnId: 'y-accessor' }], filterOperations: filterOperationsAxis, supportsMoreColumns: false, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsHeatmap_yDimensionPanel', }, { @@ -165,7 +165,7 @@ describe('heatmap', () => { ], filterOperations: isCellValueSupported, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_cellPanel', enableDimensionEditor: true, }, @@ -194,7 +194,7 @@ describe('heatmap', () => { accessors: [{ columnId: 'x-accessor' }], filterOperations: filterOperationsAxis, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_xDimensionPanel', }, { @@ -204,7 +204,7 @@ describe('heatmap', () => { accessors: [], filterOperations: filterOperationsAxis, supportsMoreColumns: true, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsHeatmap_yDimensionPanel', }, { @@ -217,7 +217,7 @@ describe('heatmap', () => { accessors: [], filterOperations: isCellValueSupported, supportsMoreColumns: true, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_cellPanel', enableDimensionEditor: true, }, @@ -250,7 +250,7 @@ describe('heatmap', () => { accessors: [{ columnId: 'x-accessor' }], filterOperations: filterOperationsAxis, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_xDimensionPanel', }, { @@ -260,7 +260,7 @@ describe('heatmap', () => { accessors: [{ columnId: 'y-accessor' }], filterOperations: filterOperationsAxis, supportsMoreColumns: false, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsHeatmap_yDimensionPanel', }, { @@ -278,7 +278,7 @@ describe('heatmap', () => { ], filterOperations: isCellValueSupported, supportsMoreColumns: false, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_cellPanel', enableDimensionEditor: true, }, diff --git a/x-pack/plugins/lens/public/visualizations/heatmap/visualization.tsx b/x-pack/plugins/lens/public/visualizations/heatmap/visualization.tsx index 09548df0a67e4..1fc48b4d71c3e 100644 --- a/x-pack/plugins/lens/public/visualizations/heatmap/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/heatmap/visualization.tsx @@ -181,7 +181,7 @@ export const getHeatmapVisualization = ({ accessors: state.xAccessor ? [{ columnId: state.xAccessor }] : [], filterOperations: filterOperationsAxis, supportsMoreColumns: !state.xAccessor, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_xDimensionPanel', }, { @@ -191,7 +191,7 @@ export const getHeatmapVisualization = ({ accessors: state.yAccessor ? [{ columnId: state.yAccessor }] : [], filterOperations: filterOperationsAxis, supportsMoreColumns: !state.yAccessor, - required: false, + requiredMinDimensionCount: 0, dataTestSubj: 'lnsHeatmap_yDimensionPanel', }, { @@ -224,7 +224,7 @@ export const getHeatmapVisualization = ({ filterOperations: isCellValueSupported, supportsMoreColumns: !state.valueAccessor, enableDimensionEditor: true, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsHeatmap_cellPanel', }, ], diff --git a/x-pack/plugins/lens/public/visualizations/legacy_metric/visualization.tsx b/x-pack/plugins/lens/public/visualizations/legacy_metric/visualization.tsx index f1b1ffd1f00b4..02a4cd23ad4f8 100644 --- a/x-pack/plugins/lens/public/visualizations/legacy_metric/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/legacy_metric/visualization.tsx @@ -258,7 +258,7 @@ export const getLegacyMetricVisualization = ({ filterOperations: (op: OperationMetadata) => !op.isBucketed && legacyMetricSupportedTypes.has(op.dataType), enableDimensionEditor: true, - required: true, + requiredMinDimensionCount: 1, }, ], }; diff --git a/x-pack/plugins/lens/public/visualizations/metric/__snapshots__/visualization.test.ts.snap b/x-pack/plugins/lens/public/visualizations/metric/__snapshots__/visualization.test.ts.snap index 8c565cbed53be..7d1df68158266 100644 --- a/x-pack/plugins/lens/public/visualizations/metric/__snapshots__/visualization.test.ts.snap +++ b/x-pack/plugins/lens/public/visualizations/metric/__snapshots__/visualization.test.ts.snap @@ -24,7 +24,7 @@ Object { "paramEditorCustomProps": Object { "headingLabel": "Value", }, - "required": true, + "requiredMinDimensionCount": 1, "supportsMoreColumns": false, }, Object { @@ -46,7 +46,7 @@ Object { "paramEditorCustomProps": Object { "headingLabel": "Value", }, - "required": false, + "requiredMinDimensionCount": 0, "supportsMoreColumns": false, }, Object { @@ -70,7 +70,7 @@ Object { "headingLabel": "Value", }, "prioritizedOperation": "max", - "required": false, + "requiredMinDimensionCount": 0, "supportStaticValue": true, "supportsMoreColumns": false, }, @@ -91,7 +91,7 @@ Object { "groupId": "breakdownBy", "groupLabel": "Break down by", "layerId": "first", - "required": false, + "requiredMinDimensionCount": 0, "supportsMoreColumns": false, }, ], diff --git a/x-pack/plugins/lens/public/visualizations/metric/suggestions.test.ts b/x-pack/plugins/lens/public/visualizations/metric/suggestions.test.ts index 47229650e05f7..45f332776a4d0 100644 --- a/x-pack/plugins/lens/public/visualizations/metric/suggestions.test.ts +++ b/x-pack/plugins/lens/public/visualizations/metric/suggestions.test.ts @@ -79,6 +79,10 @@ describe('metric suggestions', () => { ...metricColumn, columnId: 'metric-column2', }, + { + ...metricColumn, + columnId: 'metric-column3', + }, ], changeType: 'unchanged', }, @@ -99,6 +103,10 @@ describe('metric suggestions', () => { ...metricColumn, columnId: 'metric-column2', }, + { + ...metricColumn, + columnId: 'metric-column3', + }, ], changeType: 'unchanged', }, diff --git a/x-pack/plugins/lens/public/visualizations/metric/suggestions.ts b/x-pack/plugins/lens/public/visualizations/metric/suggestions.ts index ae40bf83574f4..c0354d4db65e0 100644 --- a/x-pack/plugins/lens/public/visualizations/metric/suggestions.ts +++ b/x-pack/plugins/lens/public/visualizations/metric/suggestions.ts @@ -11,7 +11,7 @@ import { layerTypes } from '../../../common'; import { metricLabel, MetricVisualizationState, supportedDataTypes } from './visualization'; const MAX_BUCKETED_COLUMNS = 1; -const MAX_METRIC_COLUMNS = 1; +const MAX_METRIC_COLUMNS = 2; // primary and secondary metric const hasLayerMismatch = (keptLayerIds: string[], table: TableSuggestion) => keptLayerIds.length > 1 || (keptLayerIds.length && table.layerId !== keptLayerIds[0]); diff --git a/x-pack/plugins/lens/public/visualizations/metric/visualization.tsx b/x-pack/plugins/lens/public/visualizations/metric/visualization.tsx index ed1efa900cf24..81f7f08fe3223 100644 --- a/x-pack/plugins/lens/public/visualizations/metric/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/metric/visualization.tsx @@ -19,13 +19,20 @@ import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; import { IconChartMetric } from '@kbn/chart-icons'; import { LayerType } from '../../../common'; import { getSuggestions } from './suggestions'; -import { Visualization, OperationMetadata, DatasourceLayers, AccessorConfig } from '../../types'; +import { + Visualization, + OperationMetadata, + DatasourceLayers, + AccessorConfig, + Suggestion, +} from '../../types'; import { layerTypes } from '../../../common'; import { GROUP_ID, LENS_METRIC_ID } from './constants'; import { DimensionEditor } from './dimension_editor'; import { Toolbar } from './toolbar'; import { generateId } from '../../id_generator'; import { FormatSelectorOptions } from '../../indexpattern_datasource/dimension_panel/format_selector'; +import { IndexPatternLayer } from '../../indexpattern_datasource/types'; export const DEFAULT_MAX_COLUMNS = 3; @@ -50,6 +57,16 @@ export interface MetricVisualizationState { maxCols?: number; } +interface MetricDatasourceState { + [prop: string]: unknown; + layers: IndexPatternLayer[]; +} + +export interface MetricSuggestion extends Suggestion { + datasourceState: MetricDatasourceState; + visualizationState: MetricVisualizationState; +} + export const supportedDataTypes = new Set(['number']); // TODO - deduplicate with gauges? @@ -298,7 +315,7 @@ export const getMetricVisualization = ({ enableDimensionEditor: true, enableFormatSelector: true, formatSelectorOptions: formatterOptions, - required: true, + requiredMinDimensionCount: 1, }, { groupId: GROUP_ID.SECONDARY_METRIC, @@ -324,7 +341,7 @@ export const getMetricVisualization = ({ enableDimensionEditor: true, enableFormatSelector: true, formatSelectorOptions: formatterOptions, - required: false, + requiredMinDimensionCount: 0, }, { groupId: GROUP_ID.MAX, @@ -350,7 +367,7 @@ export const getMetricVisualization = ({ formatSelectorOptions: formatterOptions, supportStaticValue: true, prioritizedOperation: 'max', - required: false, + requiredMinDimensionCount: 0, groupTooltip: i18n.translate('xpack.lens.metric.maxTooltip', { defaultMessage: 'If the maximum value is specified, the minimum value is fixed at zero.', @@ -376,7 +393,7 @@ export const getMetricVisualization = ({ enableDimensionEditor: true, enableFormatSelector: true, formatSelectorOptions: formatterOptions, - required: false, + requiredMinDimensionCount: 0, }, ], }; @@ -484,4 +501,25 @@ export const getMetricVisualization = ({ noPadding: true, }; }, + + getSuggestionFromConvertToLensContext({ suggestions, context }) { + const allSuggestions = suggestions as MetricSuggestion[]; + return { + ...allSuggestions[0], + datasourceState: { + ...allSuggestions[0].datasourceState, + layers: allSuggestions.reduce( + (acc, s) => ({ + ...acc, + ...s.datasourceState.layers, + }), + {} + ), + }, + visualizationState: { + ...allSuggestions[0].visualizationState, + ...context.configuration, + }, + }; + }, }); diff --git a/x-pack/plugins/lens/public/visualizations/partition/suggestions.test.ts b/x-pack/plugins/lens/public/visualizations/partition/suggestions.test.ts index eea673dc531d3..dc0ce54b5bc09 100644 --- a/x-pack/plugins/lens/public/visualizations/partition/suggestions.test.ts +++ b/x-pack/plugins/lens/public/visualizations/partition/suggestions.test.ts @@ -93,7 +93,7 @@ describe('suggestions', () => { ).toHaveLength(0); }); - it('should reject date operations', () => { + it('should hide date operations', () => { expect( suggestions({ table: { @@ -118,11 +118,17 @@ describe('suggestions', () => { }, state: undefined, keptLayerIds: ['first'], - }) - ).toHaveLength(0); + }).map((s) => [s.hide, s.score]) + ).toEqual([ + [true, 0], + [true, 0], + [true, 0], + [true, 0], + [true, 0], + ]); }); - it('should reject histogram operations', () => { + it('should hide histogram operations', () => { expect( suggestions({ table: { @@ -147,8 +153,14 @@ describe('suggestions', () => { }, state: undefined, keptLayerIds: ['first'], - }) - ).toHaveLength(0); + }).map((s) => [s.hide, s.score]) + ).toEqual([ + [true, 0], + [true, 0], + [true, 0], + [true, 0], + [true, 0], + ]); }); it('should not reject histogram operations in case of switching between partition charts', () => { diff --git a/x-pack/plugins/lens/public/visualizations/partition/suggestions.ts b/x-pack/plugins/lens/public/visualizations/partition/suggestions.ts index 36e367ca3ad6f..9f2d0920983ad 100644 --- a/x-pack/plugins/lens/public/visualizations/partition/suggestions.ts +++ b/x-pack/plugins/lens/public/visualizations/partition/suggestions.ts @@ -29,15 +29,10 @@ function hasIntervalScale(columns: TableSuggestionColumn[]) { } function shouldReject({ table, keptLayerIds, state }: SuggestionRequest) { - // Histograms are not good for pi. But we should not reject them on switching between partition charts. - const shouldRejectIntervals = - state?.shape && isPartitionShape(state.shape) ? false : hasIntervalScale(table.columns); - return ( keptLayerIds.length > 1 || (keptLayerIds.length && table.layerId !== keptLayerIds[0]) || table.changeType === 'reorder' || - shouldRejectIntervals || table.columns.some((col) => col.operation.isStaticValue) ); } @@ -111,6 +106,10 @@ export function suggestions({ const results: Array> = []; + // Histograms are not good for pi. But we should not hide suggestion on switching between partition charts. + const shouldHideSuggestion = + state?.shape && isPartitionShape(state.shape) ? false : hasIntervalScale(table.columns); + if ( groups.length <= PartitionChartsMeta.pie.maxBuckets && !hasCustomSuggestionsExists(subVisualizationId) @@ -309,11 +308,11 @@ export function suggestions({ return [...results] .map((suggestion) => ({ ...suggestion, - score: suggestion.score + 0.05 * groups.length, + score: shouldHideSuggestion ? 0 : suggestion.score + 0.05 * groups.length, })) .sort((a, b) => b.score - a.score) .map((suggestion) => ({ ...suggestion, - hide: incompleteConfiguration || suggestion.hide, + hide: shouldHideSuggestion || incompleteConfiguration || suggestion.hide, })); } diff --git a/x-pack/plugins/lens/public/visualizations/partition/visualization.tsx b/x-pack/plugins/lens/public/visualizations/partition/visualization.tsx index 6a58d46b34caa..2a8bdc2dd4ab0 100644 --- a/x-pack/plugins/lens/public/visualizations/partition/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/partition/visualization.tsx @@ -14,11 +14,14 @@ import { ThemeServiceStart } from '@kbn/core/public'; import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; import { VIS_EVENT_TO_TRIGGER } from '@kbn/visualizations-plugin/public'; import { EuiSpacer } from '@elastic/eui'; +import { PartitionVisConfiguration } from '@kbn/visualizations-plugin/common/convert_to_lens'; import type { Visualization, OperationMetadata, AccessorConfig, VisualizationDimensionGroupConfig, + Suggestion, + VisualizeEditorContext, } from '../../types'; import { getSortedGroups, toExpression, toPreviewExpression } from './to_expression'; import { CategoryDisplay, layerTypes, LegendDisplay, NumberDisplay } from '../../../common'; @@ -27,6 +30,17 @@ import { PartitionChartsMeta } from './partition_charts_meta'; import { DimensionEditor, PieToolbar } from './toolbar'; import { checkTableForContainsSmallValues } from './render_helpers'; import { PieChartTypes, PieLayerState, PieVisualizationState } from '../../../common'; +import { IndexPatternLayer } from '../..'; + +interface DatatableDatasourceState { + [prop: string]: unknown; + layers: IndexPatternLayer[]; +} + +export interface PartitionSuggestion extends Suggestion { + datasourceState: DatatableDatasourceState; + visualizationState: PieVisualizationState; +} function newLayerState(layerId: string): PieLayerState { return { @@ -42,6 +56,12 @@ function newLayerState(layerId: string): PieLayerState { }; } +function isPartitionVisConfiguration( + context: VisualizeEditorContext +): context is VisualizeEditorContext { + return context.type === 'lnsPie'; +} + const bucketedOperations = (op: OperationMetadata) => op.isBucketed; const numberMetricOperations = (op: OperationMetadata) => !op.isBucketed && op.dataType === 'number' && !op.isStaticValue; @@ -148,7 +168,7 @@ export const getPieVisualization = ({ } const primaryGroupConfigBaseProps = { - required: true, + requiredMinDimensionCount: 1, groupId: 'primaryGroups', accessors, enableDimensionEditor: true, @@ -264,7 +284,7 @@ export const getPieVisualization = ({ accessors: layer.metric ? [{ columnId: layer.metric }] : [], supportsMoreColumns: !layer.metric, filterOperations: numberMetricOperations, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsPie_sizeByDimensionPanel', }); @@ -422,6 +442,29 @@ export const getPieVisualization = ({ return warningMessages; }, + getSuggestionFromConvertToLensContext(props) { + const context = props.context; + if (!isPartitionVisConfiguration(context)) { + return; + } + if (!props.suggestions.length) { + return; + } + const suggestionByShape = (props.suggestions as PartitionSuggestion[]).find( + (suggestion) => suggestion.visualizationState.shape === context.configuration.shape + ); + if (!suggestionByShape) { + return; + } + return { + ...suggestionByShape, + visualizationState: { + ...suggestionByShape.visualizationState, + ...context.configuration, + }, + }; + }, + getErrorMessages(state) { const hasTooManyBucketDimensions = state.layers .map( diff --git a/x-pack/plugins/lens/public/visualizations/xy/annotations/helpers.tsx b/x-pack/plugins/lens/public/visualizations/xy/annotations/helpers.tsx index 34aff26582771..baaed78ec0237 100644 --- a/x-pack/plugins/lens/public/visualizations/xy/annotations/helpers.tsx +++ b/x-pack/plugins/lens/public/visualizations/xy/annotations/helpers.tsx @@ -414,7 +414,7 @@ export const getAnnotationsConfiguration = ({ invalidMessage: i18n.translate('xpack.lens.xyChart.addAnnotationsLayerLabelDisabledHelp', { defaultMessage: 'Annotations require a time based chart to work. Add a date histogram.', }), - required: false, + requiredMinDimensionCount: 0, supportsMoreColumns: true, supportFieldFormat: false, enableDimensionEditor: true, diff --git a/x-pack/plugins/lens/public/visualizations/xy/reference_line_helpers.tsx b/x-pack/plugins/lens/public/visualizations/xy/reference_line_helpers.tsx index 362b63c46eb2d..84f0a35d3b95e 100644 --- a/x-pack/plugins/lens/public/visualizations/xy/reference_line_helpers.tsx +++ b/x-pack/plugins/lens/public/visualizations/xy/reference_line_helpers.tsx @@ -461,7 +461,7 @@ export const getReferenceConfiguration = ({ accessors: config.map(({ forAccessor, color }) => getSingleColorConfig(forAccessor, color)), filterOperations: isNumericMetric, supportsMoreColumns: true, - required: false, + requiredMinDimensionCount: 0, enableDimensionEditor: true, supportStaticValue: true, paramEditorCustomProps: { diff --git a/x-pack/plugins/lens/public/visualizations/xy/visualization.test.ts b/x-pack/plugins/lens/public/visualizations/xy/visualization.test.ts index 818df64fba94f..556a89c9a8553 100644 --- a/x-pack/plugins/lens/public/visualizations/xy/visualization.test.ts +++ b/x-pack/plugins/lens/public/visualizations/xy/visualization.test.ts @@ -1047,7 +1047,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - expect(splitGroup.required).toBe(true); + expect(splitGroup.requiredMinDimensionCount).toBe(1); }); test.each([ @@ -1087,7 +1087,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - expect(splitGroup.required).toBe(false); + expect(splitGroup.requiredMinDimensionCount).toBe(0); } ); @@ -1236,7 +1236,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - expect(splitGroup.required).toBe(true); + expect(splitGroup.requiredMinDimensionCount).toBe(1); } ); }); diff --git a/x-pack/plugins/lens/public/visualizations/xy/visualization.tsx b/x-pack/plugins/lens/public/visualizations/xy/visualization.tsx index 61bdd4151219c..34ab6c88ffa19 100644 --- a/x-pack/plugins/lens/public/visualizations/xy/visualization.tsx +++ b/x-pack/plugins/lens/public/visualizations/xy/visualization.tsx @@ -276,10 +276,6 @@ export const getXyVisualization = ({ accessors: sortedAccessors, }); - if (isReferenceLayer(layer)) { - return getReferenceConfiguration({ state, frame, layer, sortedAccessors }); - } - const dataLayer: XYDataLayerConfig = layer; const dataLayers = getDataLayers(state.layers); @@ -332,7 +328,7 @@ export const getXyVisualization = ({ accessors: mappedAccessors, filterOperations: isNumericDynamicMetric, supportsMoreColumns: true, - required: true, + requiredMinDimensionCount: 1, dataTestSubj: 'lnsXY_yDimensionPanel', enableDimensionEditor: true, }, @@ -357,7 +353,8 @@ export const getXyVisualization = ({ filterOperations: isBucketed, supportsMoreColumns: !dataLayer.splitAccessor, dataTestSubj: 'lnsXY_splitDimensionPanel', - required: dataLayer.seriesType.includes('percentage') && hasOnlyOneAccessor, + requiredMinDimensionCount: + dataLayer.seriesType.includes('percentage') && hasOnlyOneAccessor ? 1 : 0, enableDimensionEditor: true, }, ], diff --git a/x-pack/plugins/lens/public/visualizations/xy/xy_suggestions.ts b/x-pack/plugins/lens/public/visualizations/xy/xy_suggestions.ts index 1184712ae033a..b63bfeb5fbd9b 100644 --- a/x-pack/plugins/lens/public/visualizations/xy/xy_suggestions.ts +++ b/x-pack/plugins/lens/public/visualizations/xy/xy_suggestions.ts @@ -615,7 +615,12 @@ function getScore( changeType: TableChangeType ) { // Unchanged table suggestions half the score because the underlying data doesn't change - const changeFactor = changeType === 'unchanged' ? 0.5 : 1; + const changeFactor = + changeType === 'reduced' || changeType === 'layers' + ? 0.3 + : changeType === 'unchanged' + ? 0.5 + : 1; // chart with multiple y values and split series will have a score of 1, single y value and no split series reduce score return (((yValues.length > 1 ? 2 : 1) + (splitBy ? 1 : 0)) / 3) * changeFactor; } diff --git a/x-pack/plugins/maps/public/actions/layer_actions.ts b/x-pack/plugins/maps/public/actions/layer_actions.ts index 7a4377f0bfc27..317f6e09053e5 100644 --- a/x-pack/plugins/maps/public/actions/layer_actions.ts +++ b/x-pack/plugins/maps/public/actions/layer_actions.ts @@ -284,6 +284,32 @@ export function toggleLayerVisible(layerId: string) { }; } +export function hideAllLayers() { + return ( + dispatch: ThunkDispatch, + getState: () => MapStoreState + ) => { + getLayerList(getState()).forEach((layer: ILayer, index: number) => { + if (layer.isVisible() && !layer.isBasemap(index)) { + dispatch(setLayerVisibility(layer.getId(), false)); + } + }); + }; +} + +export function showAllLayers() { + return ( + dispatch: ThunkDispatch, + getState: () => MapStoreState + ) => { + getLayerList(getState()).forEach((layer: ILayer, index: number) => { + if (!layer.isVisible()) { + dispatch(setLayerVisibility(layer.getId(), true)); + } + }); + }; +} + export function showThisLayerOnly(layerId: string) { return ( dispatch: ThunkDispatch, diff --git a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/__snapshots__/layer_control.test.tsx.snap b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/__snapshots__/layer_control.test.tsx.snap index 7d0c67ff41797..e043a8d723e14 100644 --- a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/__snapshots__/layer_control.test.tsx.snap +++ b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/__snapshots__/layer_control.test.tsx.snap @@ -31,6 +31,40 @@ exports[`LayerControl is rendered 1`] = ` + + + + + + + + + + @@ -184,6 +218,40 @@ exports[`LayerControl isReadOnly 1`] = ` + + + + + + + + + + @@ -245,6 +313,40 @@ exports[`LayerControl should disable buttons when flyout is open 1`] = ` + + + + + + + + + + diff --git a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/index.ts b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/index.ts index c525523047c40..d5dc63ecb8e8b 100644 --- a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/index.ts +++ b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/index.ts @@ -11,7 +11,14 @@ import { connect } from 'react-redux'; import { LayerControl } from './layer_control'; import { FLYOUT_STATE } from '../../../reducers/ui'; -import { setSelectedLayer, updateFlyout, setIsLayerTOCOpen, setDrawMode } from '../../../actions'; +import { + hideAllLayers, + setSelectedLayer, + updateFlyout, + setIsLayerTOCOpen, + setDrawMode, + showAllLayers, +} from '../../../actions'; import { getIsReadOnly, getIsLayerTOCOpen, @@ -43,6 +50,12 @@ function mapDispatchToProps(dispatch: ThunkDispatch { dispatch(setIsLayerTOCOpen(true)); }, + hideAllLayers: () => { + dispatch(hideAllLayers()); + }, + showAllLayers: () => { + dispatch(showAllLayers()); + }, }; } diff --git a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.test.tsx b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.test.tsx index 649999ab49a9d..1fc9fa6b9755e 100644 --- a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.test.tsx +++ b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.test.tsx @@ -28,6 +28,8 @@ const defaultProps = { showAddLayerWizard: async () => {}, closeLayerTOC: () => {}, openLayerTOC: () => {}, + hideAllLayers: () => {}, + showAllLayers: () => {}, isLayerTOCOpen: true, layerList: [], isFlyoutOpen: false, diff --git a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.tsx b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.tsx index d131bf9b98026..297d7ccfd5063 100644 --- a/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.tsx +++ b/x-pack/plugins/maps/public/connected_components/right_side_controls/layer_control/layer_control.tsx @@ -31,6 +31,8 @@ export interface Props { showAddLayerWizard: () => Promise; closeLayerTOC: () => void; openLayerTOC: () => void; + hideAllLayers: () => void; + showAllLayers: () => void; } function renderExpandButton({ @@ -81,6 +83,8 @@ export function LayerControl({ openLayerTOC, layerList, isFlyoutOpen, + hideAllLayers, + showAllLayers, }: Props) { if (!isLayerTOCOpen) { if (isScreenshotMode()) { @@ -152,6 +156,40 @@ export function LayerControl({ + + + + + + + + + + void; +} + +interface State { + lat: number | string; + lon: number | string; + zoom: number | string; +} + +export class DecimalDegreesForm extends Component { + state: State = { + lat: this.props.center.lat, + lon: this.props.center.lon, + zoom: this.props.zoom, + }; + + _onLatChange = (evt: ChangeEvent) => { + const sanitizedValue = parseFloat(evt.target.value); + this.setState({ + lat: isNaN(sanitizedValue) ? '' : sanitizedValue, + }); + }; + + _onLonChange = (evt: ChangeEvent) => { + const sanitizedValue = parseFloat(evt.target.value); + this.setState({ + lon: isNaN(sanitizedValue) ? '' : sanitizedValue, + }); + }; + + _onZoomChange = (evt: ChangeEvent) => { + const sanitizedValue = parseFloat(evt.target.value); + this.setState({ + zoom: isNaN(sanitizedValue) ? '' : sanitizedValue, + }); + }; + + _onSubmit = () => { + const { lat, lon, zoom } = this.state; + this.props.onSubmit(lat as number, lon as number, zoom as number); + }; + + render() { + const { isInvalid: isLatInvalid, error: latError } = withinRange(this.state.lat, -90, 90); + const { isInvalid: isLonInvalid, error: lonError } = withinRange(this.state.lon, -180, 180); + const { isInvalid: isZoomInvalid, error: zoomError } = withinRange( + this.state.zoom, + this.props.settings.minZoom, + this.props.settings.maxZoom + ); + + return ( + + + + + + + + + + + + + + + + + + + + + + ); + } +} diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/mgrs_form.tsx b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/mgrs_form.tsx new file mode 100644 index 0000000000000..48455f89b7464 --- /dev/null +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/mgrs_form.tsx @@ -0,0 +1,149 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import _ from 'lodash'; +import React, { ChangeEvent, Component } from 'react'; +import { + EuiForm, + EuiFormRow, + EuiButton, + EuiFieldNumber, + EuiFieldText, + EuiTextAlign, + EuiSpacer, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { MapCenter, MapSettings } from '../../../../common/descriptor_types'; +import { ddToMGRS, mgrsToDD, withinRange } from './utils'; + +interface Props { + settings: MapSettings; + zoom: number; + center: MapCenter; + onSubmit: (lat: number, lon: number, zoom: number) => void; +} + +interface State { + mgrs: string; + zoom: number | string; +} + +export class MgrsForm extends Component { + state: State = { + mgrs: ddToMGRS(this.props.center.lat, this.props.center.lon), + zoom: this.props.zoom, + }; + + _toPoint() { + return this.state.mgrs === '' ? undefined : mgrsToDD(this.state.mgrs); + } + + _isMgrsInvalid() { + const point = this._toPoint(); + return ( + point === undefined || + !point.north || + _.isNaN(point.north) || + !point.south || + _.isNaN(point.south) || + !point.east || + _.isNaN(point.east) || + !point.west || + _.isNaN(point.west) + ); + } + + _onMGRSChange = (evt: ChangeEvent) => { + this.setState({ + mgrs: _.isNull(evt.target.value) ? '' : evt.target.value, + }); + }; + + _onZoomChange = (evt: ChangeEvent) => { + const sanitizedValue = parseFloat(evt.target.value); + this.setState({ + zoom: isNaN(sanitizedValue) ? '' : sanitizedValue, + }); + }; + + _onSubmit = () => { + const point = this._toPoint(); + if (point) { + this.props.onSubmit(point.north, point.east, this.state.zoom as number); + } + }; + + render() { + const isMgrsInvalid = this._isMgrsInvalid(); + const mgrsError = isMgrsInvalid + ? i18n.translate('xpack.maps.setViewControl.mgrsInvalid', { + defaultMessage: 'MGRS is invalid', + }) + : null; + const { isInvalid: isZoomInvalid, error: zoomError } = withinRange( + this.state.zoom, + this.props.settings.minZoom, + this.props.settings.maxZoom + ); + + return ( + + + + + + + + + + + + + + + + + + ); + } +} diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/index.tsx b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/number_form_row.tsx similarity index 85% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/index.tsx rename to x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/number_form_row.tsx index 9252945c8f552..1fec1c76430eb 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/index.tsx +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/number_form_row.tsx @@ -4,5 +4,3 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - -export * from './indicator_fields_table'; diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.tsx b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.tsx index eb0b1cfc1ddaf..906cbb8a0bb00 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.tsx +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.tsx @@ -5,50 +5,11 @@ * 2.0. */ -import React, { ChangeEvent, Component, Fragment } from 'react'; -import { - EuiForm, - EuiFormRow, - EuiButton, - EuiFieldNumber, - EuiFieldText, - EuiButtonIcon, - EuiPopover, - EuiTextAlign, - EuiSpacer, - EuiPanel, -} from '@elastic/eui'; -import { EuiButtonEmpty } from '@elastic/eui'; -import { EuiRadioGroup } from '@elastic/eui'; +import React, { Component } from 'react'; +import { EuiButtonIcon, EuiPopover, EuiPanel } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n-react'; -import * as usng from 'usng.js'; -import { isNaN, isNull } from 'lodash'; import { MapCenter, MapSettings } from '../../../../common/descriptor_types'; - -export const COORDINATE_SYSTEM_DEGREES_DECIMAL = 'dd'; -export const COORDINATE_SYSTEM_MGRS = 'mgrs'; -export const COORDINATE_SYSTEM_UTM = 'utm'; - -export const DEFAULT_SET_VIEW_COORDINATE_SYSTEM = COORDINATE_SYSTEM_DEGREES_DECIMAL; - -// @ts-ignore -const converter = new usng.Converter(); - -const COORDINATE_SYSTEMS = [ - { - id: COORDINATE_SYSTEM_DEGREES_DECIMAL, - label: 'Degrees Decimal', - }, - { - id: COORDINATE_SYSTEM_UTM, - label: 'UTM', - }, - { - id: COORDINATE_SYSTEM_MGRS, - label: 'MGRS', - }, -]; +import { SetViewForm } from './set_view_form'; export interface Props { settings: MapSettings; @@ -59,73 +20,17 @@ export interface Props { interface State { isPopoverOpen: boolean; - lat: number | string; - lon: number | string; - zoom: number | string; - coord: string; - mgrs: string; - utm: { - northing: string; - easting: string; - zoneNumber: string; - zoneLetter: string | undefined; - zone: string; - }; - isCoordPopoverOpen: boolean; - prevView: string | undefined; } export class SetViewControl extends Component { state: State = { isPopoverOpen: false, - lat: 0, - lon: 0, - zoom: 0, - coord: DEFAULT_SET_VIEW_COORDINATE_SYSTEM, - mgrs: '', - utm: { - northing: '', - easting: '', - zoneNumber: '', - zoneLetter: '', - zone: '', - }, - isCoordPopoverOpen: false, - prevView: '', }; - static getDerivedStateFromProps(nextProps: Props, prevState: State) { - const nextView = getViewString(nextProps.center.lat, nextProps.center.lon, nextProps.zoom); - - const utm = convertLatLonToUTM(nextProps.center.lat, nextProps.center.lon); - const mgrs = convertLatLonToMGRS(nextProps.center.lat, nextProps.center.lon); - - if (nextView !== prevState.prevView) { - return { - lat: nextProps.center.lat, - lon: nextProps.center.lon, - zoom: nextProps.zoom, - utm, - mgrs, - prevView: nextView, - }; - } - - return null; - } - _togglePopover = () => { - if (this.state.isPopoverOpen) { - this._closePopover(); - return; - } - - this.setState({ - lat: this.props.center.lat, - lon: this.props.center.lon, - zoom: this.props.zoom, - isPopoverOpen: true, - }); + this.setState((prevState) => ({ + isPopoverOpen: !prevState.isPopoverOpen, + })); }; _closePopover = () => { @@ -134,567 +39,11 @@ export class SetViewControl extends Component { }); }; - _onCoordinateSystemChange = (coordId: string) => { - this.setState({ - coord: coordId, - }); - }; - - _onLatChange = (evt: ChangeEvent) => { - this._onChange('lat', evt); - }; - - _onLonChange = (evt: ChangeEvent) => { - this._onChange('lon', evt); - }; - - _onZoomChange = (evt: ChangeEvent) => { - const sanitizedValue = parseFloat(evt.target.value); - this.setState({ - ['zoom']: isNaN(sanitizedValue) ? '' : sanitizedValue, - }); - }; - - _onUTMZoneChange = (evt: ChangeEvent) => { - this._onUTMChange('zone', evt); - }; - - _onUTMEastingChange = (evt: ChangeEvent) => { - this._onUTMChange('easting', evt); - }; - - _onUTMNorthingChange = (evt: ChangeEvent) => { - this._onUTMChange('northing', evt); - }; - - _onMGRSChange = (evt: ChangeEvent) => { - this.setState( - { - ['mgrs']: isNull(evt.target.value) ? '' : evt.target.value, - }, - this._syncToMGRS - ); - }; - - _onUTMChange = (name: 'easting' | 'northing' | 'zone', evt: ChangeEvent) => { - const value = evt.target.value; - const updateObj = { ...this.state.utm }; - updateObj[name] = isNull(value) ? '' : value; - if (name === 'zone' && value.length > 0) { - const zoneLetter = value.substring(value.length - 1); - const zoneNumber = value.substring(0, value.length - 1); - updateObj.zoneLetter = isNaN(zoneLetter) ? zoneLetter : ''; - updateObj.zoneNumber = isNaN(zoneNumber) ? '' : zoneNumber; - } - this.setState( - { - // @ts-ignore - ['utm']: updateObj, - }, - this._syncToUTM - ); - }; - - _onChange = (name: 'lat' | 'lon', evt: ChangeEvent) => { - const sanitizedValue = parseFloat(evt.target.value); - - this.setState( - // @ts-ignore - { - [name]: isNaN(sanitizedValue) ? '' : sanitizedValue, - }, - this._syncToLatLon - ); - }; - - /** - * Sync all coordinates to the lat/lon that is set - */ - _syncToLatLon = () => { - if (this.state.lat !== '' && this.state.lon !== '') { - const utm = convertLatLonToUTM(this.state.lat, this.state.lon); - const mgrs = convertLatLonToMGRS(this.state.lat, this.state.lon); - - this.setState({ mgrs, utm }); - } else { - this.setState({ - mgrs: '', - utm: { northing: '', easting: '', zoneNumber: '', zoneLetter: '', zone: '' }, - }); - } - }; - - /** - * Sync the current lat/lon to MGRS that is set - */ - _syncToMGRS = () => { - if (this.state.mgrs !== '') { - let lon; - let lat; - - try { - const { north, east } = convertMGRStoLL(this.state.mgrs); - lat = north; - lon = east; - } catch (err) { - return; - } - - const utm = convertLatLonToUTM(lat, lon); - - this.setState({ - lat: isNaN(lat) ? '' : lat, - lon: isNaN(lon) ? '' : lon, - utm, - }); - } else { - this.setState({ - lat: '', - lon: '', - utm: { northing: '', easting: '', zoneNumber: '', zoneLetter: '', zone: '' }, - }); - } - }; - - /** - * Sync the current lat/lon to UTM that is set - */ - _syncToUTM = () => { - if (this.state.utm) { - let lat; - let lon; - try { - ({ lat, lon } = converter.UTMtoLL( - this.state.utm.northing, - this.state.utm.easting, - this.state.utm.zoneNumber - )); - } catch (err) { - return; - } - - const mgrs = convertLatLonToMGRS(lat, lon); - - this.setState({ - lat: isNaN(lat) ? '' : lat, - lon: isNaN(lon) ? '' : lon, - mgrs, - }); - } else { - this.setState({ - lat: '', - lon: '', - mgrs: '', - }); - } - }; - - _renderNumberFormRow = ({ - value, - min, - max, - onChange, - label, - dataTestSubj, - }: { - value: string | number; - min: number; - max: number; - onChange: (evt: ChangeEvent) => void; - label: string; - dataTestSubj: string; - }) => { - const isInvalid = value === '' || value > max || value < min; - const error = isInvalid ? `Must be between ${min} and ${max}` : null; - return { - isInvalid, - component: ( - - - - ), - }; - }; - - _renderMGRSFormRow = ({ - value, - onChange, - label, - dataTestSubj, - }: { - value: string; - onChange: (evt: ChangeEvent) => void; - label: string; - dataTestSubj: string; - }) => { - let point; - try { - point = convertMGRStoLL(value); - } catch (err) { - point = undefined; - } - - const isInvalid = - value === '' || - point === undefined || - !point.north || - isNaN(point.north) || - !point.south || - isNaN(point.south) || - !point.east || - isNaN(point.east) || - !point.west || - isNaN(point.west); - const error = isInvalid - ? i18n.translate('xpack.maps.setViewControl.mgrsInvalid', { - defaultMessage: 'MGRS is invalid', - }) - : null; - return { - isInvalid, - component: ( - - - - ), - }; - }; - - _renderUTMZoneRow = ({ - value, - onChange, - label, - dataTestSubj, - }: { - value: string | number; - onChange: (evt: ChangeEvent) => void; - label: string; - dataTestSubj: string; - }) => { - let point; - try { - point = converter.UTMtoLL( - this.state.utm.northing, - this.state.utm.easting, - this.state.utm.zoneNumber - ); - } catch { - point = undefined; - } - - const isInvalid = value === '' || point === undefined; - const error = isInvalid - ? i18n.translate('xpack.maps.setViewControl.utmInvalidZone', { - defaultMessage: 'UTM Zone is invalid', - }) - : null; - return { - isInvalid, - component: ( - - - - ), - }; - }; - - _renderUTMEastingRow = ({ - value, - onChange, - label, - dataTestSubj, - }: { - value: string | number; - onChange: (evt: ChangeEvent) => void; - label: string; - dataTestSubj: string; - }) => { - let point; - try { - point = converter.UTMtoLL(this.state.utm.northing, value, this.state.utm.zoneNumber); - } catch { - point = undefined; - } - const isInvalid = value === '' || point === undefined; - const error = isInvalid - ? i18n.translate('xpack.maps.setViewControl.utmInvalidEasting', { - defaultMessage: 'UTM Easting is invalid', - }) - : null; - return { - isInvalid, - component: ( - - - - ), - }; - }; - - _renderUTMNorthingRow = ({ - value, - onChange, - label, - dataTestSubj, - }: { - value: string | number; - onChange: (evt: ChangeEvent) => void; - label: string; - dataTestSubj: string; - }) => { - let point; - try { - point = converter.UTMtoLL(value, this.state.utm.easting, this.state.utm.zoneNumber); - } catch { - point = undefined; - } - const isInvalid = value === '' || point === undefined; - const error = isInvalid - ? i18n.translate('xpack.maps.setViewControl.utmInvalidNorthing', { - defaultMessage: 'UTM Northing is invalid', - }) - : null; - return { - isInvalid, - component: ( - - - - ), - }; - }; - - _onSubmit = () => { - const { lat, lon, zoom } = this.state; + _onSubmit = (lat: number, lon: number, zoom: number) => { this._closePopover(); - this.props.onSubmit({ lat: lat as number, lon: lon as number, zoom: zoom as number }); + this.props.onSubmit({ lat, lon, zoom }); }; - _renderSetViewForm() { - let isLatInvalid; - let latFormRow; - let isLonInvalid; - let lonFormRow; - let isMGRSInvalid; - let mgrsFormRow; - let isUtmZoneInvalid; - let utmZoneRow; - let isUtmEastingInvalid; - let utmEastingRow; - let isUtmNorthingInvalid; - let utmNorthingRow; - - if (this.state.coord === COORDINATE_SYSTEM_DEGREES_DECIMAL) { - const latRenderObject = this._renderNumberFormRow({ - value: this.state.lat, - min: -90, - max: 90, - onChange: this._onLatChange, - label: i18n.translate('xpack.maps.setViewControl.latitudeLabel', { - defaultMessage: 'Latitude', - }), - dataTestSubj: 'latitudeInput', - }); - - isLatInvalid = latRenderObject.isInvalid; - latFormRow = latRenderObject.component; - - const lonRenderObject = this._renderNumberFormRow({ - value: this.state.lon, - min: -180, - max: 180, - onChange: this._onLonChange, - label: i18n.translate('xpack.maps.setViewControl.longitudeLabel', { - defaultMessage: 'Longitude', - }), - dataTestSubj: 'longitudeInput', - }); - - isLonInvalid = lonRenderObject.isInvalid; - lonFormRow = lonRenderObject.component; - } else if (this.state.coord === COORDINATE_SYSTEM_MGRS) { - const mgrsRenderObject = this._renderMGRSFormRow({ - value: this.state.mgrs, - onChange: this._onMGRSChange, - label: i18n.translate('xpack.maps.setViewControl.mgrsLabel', { - defaultMessage: 'MGRS', - }), - dataTestSubj: 'mgrsInput', - }); - - isMGRSInvalid = mgrsRenderObject.isInvalid; - mgrsFormRow = mgrsRenderObject.component; - } else if (this.state.coord === COORDINATE_SYSTEM_UTM) { - const utmZoneRenderObject = this._renderUTMZoneRow({ - value: this.state.utm !== undefined ? this.state.utm.zone : '', - onChange: this._onUTMZoneChange, - label: i18n.translate('xpack.maps.setViewControl.utmZoneLabel', { - defaultMessage: 'UTM Zone', - }), - dataTestSubj: 'utmZoneInput', - }); - - isUtmZoneInvalid = utmZoneRenderObject.isInvalid; - utmZoneRow = utmZoneRenderObject.component; - - const utmEastingRenderObject = this._renderUTMEastingRow({ - value: this.state.utm !== undefined ? this.state.utm.easting : '', - onChange: this._onUTMEastingChange, - label: i18n.translate('xpack.maps.setViewControl.utmEastingLabel', { - defaultMessage: 'UTM Easting', - }), - dataTestSubj: 'utmEastingInput', - }); - - isUtmEastingInvalid = utmEastingRenderObject.isInvalid; - utmEastingRow = utmEastingRenderObject.component; - - const utmNorthingRenderObject = this._renderUTMNorthingRow({ - value: this.state.utm !== undefined ? this.state.utm.northing : '', - onChange: this._onUTMNorthingChange, - label: i18n.translate('xpack.maps.setViewControl.utmNorthingLabel', { - defaultMessage: 'UTM Northing', - }), - dataTestSubj: 'utmNorthingInput', - }); - - isUtmNorthingInvalid = utmNorthingRenderObject.isInvalid; - utmNorthingRow = utmNorthingRenderObject.component; - } - - const { isInvalid: isZoomInvalid, component: zoomFormRow } = this._renderNumberFormRow({ - value: this.state.zoom, - min: this.props.settings.minZoom, - max: this.props.settings.maxZoom, - onChange: this._onZoomChange, - label: i18n.translate('xpack.maps.setViewControl.zoomLabel', { - defaultMessage: 'Zoom', - }), - dataTestSubj: 'zoomInput', - }); - - let coordinateInputs; - if (this.state.coord === 'dd') { - coordinateInputs = ( - - {latFormRow} - {lonFormRow} - {zoomFormRow} - - ); - } else if (this.state.coord === 'dms') { - coordinateInputs = ( - - {latFormRow} - {lonFormRow} - {zoomFormRow} - - ); - } else if (this.state.coord === 'utm') { - coordinateInputs = ( - - {utmZoneRow} - {utmEastingRow} - {utmNorthingRow} - {zoomFormRow} - - ); - } else if (this.state.coord === 'mgrs') { - coordinateInputs = ( - - {mgrsFormRow} - {zoomFormRow} - - ); - } - - return ( - - { - this.setState({ isCoordPopoverOpen: false }); - }} - button={ - { - this.setState({ isCoordPopoverOpen: !this.state.isCoordPopoverOpen }); - }} - > - Coordinate System - - } - > - - - - {coordinateInputs} - - - - - - - - - - ); - } - render() { return ( { isOpen={this.state.isPopoverOpen} closePopover={this._closePopover} > - {this._renderSetViewForm()} + ); } } - -function convertLatLonToUTM(lat: string | number, lon: string | number) { - const utmCoord = converter.LLtoUTM(lat, lon); - - let eastwest = 'E'; - if (utmCoord.easting < 0) { - eastwest = 'W'; - } - let norwest = 'N'; - if (utmCoord.northing < 0) { - norwest = 'S'; - } - - if (utmCoord !== 'undefined') { - utmCoord.zoneLetter = isNaN(lat) ? '' : converter.UTMLetterDesignator(lat); - utmCoord.zone = `${utmCoord.zoneNumber}${utmCoord.zoneLetter}`; - utmCoord.easting = Math.round(utmCoord.easting); - utmCoord.northing = Math.round(utmCoord.northing); - utmCoord.str = `${utmCoord.zoneNumber}${utmCoord.zoneLetter} ${utmCoord.easting}${eastwest} ${utmCoord.northing}${norwest}`; - } - - return utmCoord; -} - -function convertLatLonToMGRS(lat: string | number, lon: string | number) { - const mgrsCoord = converter.LLtoMGRS(lat, lon, 5); - return mgrsCoord; -} - -function getViewString(lat: number, lon: number, zoom: number) { - return `${lat},${lon},${zoom}`; -} - -function convertMGRStoUSNG(mgrs: string) { - let squareIdEastSpace = 0; - for (let i = mgrs.length - 1; i > -1; i--) { - // check if we have hit letters yet - if (isNaN(mgrs.substr(i, 1))) { - squareIdEastSpace = i + 1; - break; - } - } - const gridZoneSquareIdSpace = squareIdEastSpace ? squareIdEastSpace - 2 : -1; - const numPartLength = mgrs.substr(squareIdEastSpace).length / 2; - // add the number split space - const eastNorthSpace = squareIdEastSpace ? squareIdEastSpace + numPartLength : -1; - const stringArray = mgrs.split(''); - - stringArray.splice(eastNorthSpace, 0, ' '); - stringArray.splice(squareIdEastSpace, 0, ' '); - stringArray.splice(gridZoneSquareIdSpace, 0, ' '); - - const rejoinedArray = stringArray.join(''); - return rejoinedArray; -} - -function convertMGRStoLL(mgrs: string) { - return mgrs ? converter.USNGtoLL(convertMGRStoUSNG(mgrs)) : ''; -} diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_form.tsx b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_form.tsx new file mode 100644 index 0000000000000..28fe6073d7646 --- /dev/null +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_form.tsx @@ -0,0 +1,134 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { Component } from 'react'; +import { EuiButtonEmpty, EuiPopover, EuiRadioGroup } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { MapCenter, MapSettings } from '../../../../common/descriptor_types'; +import { DecimalDegreesForm } from './decimal_degrees_form'; +import { MgrsForm } from './mgrs_form'; +import { UtmForm } from './utm_form'; + +const DEGREES_DECIMAL = 'dd'; +const MGRS = 'mgrs'; +const UTM = 'utm'; + +const COORDINATE_SYSTEM_OPTIONS = [ + { + id: DEGREES_DECIMAL, + label: i18n.translate('xpack.maps.setViewControl.decimalDegreesLabel', { + defaultMessage: 'Decimal degrees', + }), + }, + { + id: UTM, + label: 'UTM', + }, + { + id: MGRS, + label: 'MGRS', + }, +]; + +interface Props { + settings: MapSettings; + zoom: number; + center: MapCenter; + onSubmit: (lat: number, lon: number, zoom: number) => void; +} + +interface State { + isPopoverOpen: boolean; + coordinateSystem: string; +} + +export class SetViewForm extends Component { + state: State = { + coordinateSystem: DEGREES_DECIMAL, + isPopoverOpen: false, + }; + + _togglePopover = () => { + this.setState((prevState) => ({ + isPopoverOpen: !prevState.isPopoverOpen, + })); + }; + + _closePopover = () => { + this.setState({ + isPopoverOpen: false, + }); + }; + + _onCoordinateSystemChange = (optionId: string) => { + this._closePopover(); + this.setState({ + coordinateSystem: optionId, + }); + }; + + _renderForm() { + if (this.state.coordinateSystem === MGRS) { + return ( + + ); + } + + if (this.state.coordinateSystem === UTM) { + return ( + + ); + } + + return ( + + ); + } + + render() { + return ( +
+ + + + } + > + + + {this._renderForm()} +
+ ); + } +} diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.test.ts b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.test.ts new file mode 100644 index 0000000000000..e6a6819687d10 --- /dev/null +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.test.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ddToMGRS, mgrsToDD, ddToUTM, utmToDD } from './utils'; + +describe('MGRS', () => { + test('ddToMGRS should convert lat lon to MGRS', () => { + expect(ddToMGRS(29.29926, 32.05495)).toEqual('36RVT08214151'); + }); + + test('ddToMGRS should return empty string for lat lon that does not translate to MGRS grid', () => { + expect(ddToMGRS(90, 32.05495)).toEqual(''); + }); + + test('mgrsToDD should convert MGRS to lat lon', () => { + expect(mgrsToDD('36RVT08214151')).toEqual({ + east: 32.05498649594143, + north: 29.299330195900975, + south: 29.299239224067065, + west: 32.054884373627345, + }); + }); +}); + +describe('UTM', () => { + test('ddToUTM should convert lat lon to UTM', () => { + expect(ddToUTM(29.29926, 32.05495)).toEqual({ + easting: '408216', + northing: '3241512', + zone: '36R', + }); + }); + + test('ddToUTM should return empty strings for lat lon that does not translate to UTM grid', () => { + expect(ddToUTM(90, 32.05495)).toEqual({ + northing: '', + easting: '', + zone: '', + }); + }); + + test('utmToDD should convert UTM to lat lon', () => { + expect(utmToDD('3241512', '408216', '36R')).toEqual({ + lat: 29.29925770984472, + lon: 32.05494597943409, + }); + }); +}); diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.ts b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.ts new file mode 100644 index 0000000000000..7edf1428d9312 --- /dev/null +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utils.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; +import * as usng from 'usng.js'; + +// @ts-ignore +const converter = new usng.Converter(); + +export function withinRange(value: string | number, min: number, max: number) { + const isInvalid = value === '' || value > max || value < min; + const error = isInvalid + ? i18n.translate('xpack.maps.setViewControl.outOfRangeErrorMsg', { + defaultMessage: `Must be between {min} and {max}`, + values: { min, max }, + }) + : null; + return { isInvalid, error }; +} + +export function ddToUTM(lat: number, lon: number) { + try { + const utm = converter.LLtoUTM(lat, lon); + return { + northing: utm === converter.UNDEFINED_STR ? '' : String(Math.round(utm.northing)), + easting: utm === converter.UNDEFINED_STR ? '' : String(Math.round(utm.easting)), + zone: + utm === converter.UNDEFINED_STR + ? '' + : `${utm.zoneNumber}${converter.UTMLetterDesignator(lat)}`, + }; + } catch (e) { + return { + northing: '', + easting: '', + zone: '', + }; + } +} + +export function utmToDD(northing: string, easting: string, zoneNumber: string) { + try { + return converter.UTMtoLL(northing, easting, zoneNumber); + } catch (e) { + return undefined; + } +} + +export function ddToMGRS(lat: number, lon: number) { + try { + const mgrsCoord = converter.LLtoMGRS(lat, lon, 5); + return mgrsCoord; + } catch (e) { + return ''; + } +} + +function mgrstoUSNG(mgrs: string) { + let squareIdEastSpace = 0; + for (let i = mgrs.length - 1; i > -1; i--) { + // check if we have hit letters yet + if (isNaN(parseInt(mgrs.substr(i, 1), 10))) { + squareIdEastSpace = i + 1; + break; + } + } + const gridZoneSquareIdSpace = squareIdEastSpace ? squareIdEastSpace - 2 : -1; + const numPartLength = mgrs.substr(squareIdEastSpace).length / 2; + // add the number split space + const eastNorthSpace = squareIdEastSpace ? squareIdEastSpace + numPartLength : -1; + const stringArray = mgrs.split(''); + + stringArray.splice(eastNorthSpace, 0, ' '); + stringArray.splice(squareIdEastSpace, 0, ' '); + stringArray.splice(gridZoneSquareIdSpace, 0, ' '); + + const rejoinedArray = stringArray.join(''); + return rejoinedArray; +} + +export function mgrsToDD(mgrs: string) { + try { + return converter.USNGtoLL(mgrstoUSNG(mgrs)); + } catch (e) { + return undefined; + } +} diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utm_form.tsx b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utm_form.tsx new file mode 100644 index 0000000000000..76a3628217056 --- /dev/null +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/utm_form.tsx @@ -0,0 +1,209 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import _ from 'lodash'; +import React, { ChangeEvent, Component } from 'react'; +import { + EuiForm, + EuiFormRow, + EuiButton, + EuiFieldNumber, + EuiFieldText, + EuiTextAlign, + EuiSpacer, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { MapCenter, MapSettings } from '../../../../common/descriptor_types'; +import { ddToUTM, utmToDD, withinRange } from './utils'; + +interface Props { + settings: MapSettings; + zoom: number; + center: MapCenter; + onSubmit: (lat: number, lon: number, zoom: number) => void; +} + +interface State { + northing: string; + easting: string; + zone: string; + zoom: number | string; +} + +export class UtmForm extends Component { + constructor(props: Props) { + super(props); + const utm = ddToUTM(this.props.center.lat, this.props.center.lon); + this.state = { + northing: utm.northing, + easting: utm.easting, + zone: utm.zone, + zoom: this.props.zoom, + }; + } + + _toPoint() { + const { northing, easting, zone } = this.state; + return northing === '' || easting === '' || zone.length < 2 + ? undefined + : utmToDD(northing, easting, zone.substring(0, zone.length - 1)); + } + + _isUtmInvalid() { + const point = this._toPoint(); + return point === undefined; + } + + _onZoneChange = (evt: ChangeEvent) => { + this.setState({ + zone: _.isNull(evt.target.value) ? '' : evt.target.value, + }); + }; + + _onEastingChange = (evt: ChangeEvent) => { + this.setState({ + easting: _.isNull(evt.target.value) ? '' : evt.target.value, + }); + }; + + _onNorthingChange = (evt: ChangeEvent) => { + this.setState({ + northing: _.isNull(evt.target.value) ? '' : evt.target.value, + }); + }; + + _onZoomChange = (evt: ChangeEvent) => { + const sanitizedValue = parseFloat(evt.target.value); + this.setState({ + zoom: isNaN(sanitizedValue) ? '' : sanitizedValue, + }); + }; + + _onSubmit = () => { + const point = this._toPoint(); + if (point) { + this.props.onSubmit(point.lat, point.lon, this.state.zoom as number); + } + }; + + render() { + const isUtmInvalid = this._isUtmInvalid(); + const northingError = + isUtmInvalid || this.state.northing === '' + ? i18n.translate('xpack.maps.setViewControl.utmInvalidNorthing', { + defaultMessage: 'UTM Northing is invalid', + }) + : null; + const eastingError = + isUtmInvalid || this.state.northing === '' + ? i18n.translate('xpack.maps.setViewControl.utmInvalidEasting', { + defaultMessage: 'UTM Easting is invalid', + }) + : null; + const zoneError = + isUtmInvalid || this.state.northing === '' + ? i18n.translate('xpack.maps.setViewControl.utmInvalidZone', { + defaultMessage: 'UTM Zone is invalid', + }) + : null; + const { isInvalid: isZoomInvalid, error: zoomError } = withinRange( + this.state.zoom, + this.props.settings.minZoom, + this.props.settings.maxZoom + ); + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + ); + } +} diff --git a/x-pack/plugins/ml/common/openapi/README.md b/x-pack/plugins/ml/common/openapi/README.md index 256b3be6a8cc4..450f95cd52071 100644 --- a/x-pack/plugins/ml/common/openapi/README.md +++ b/x-pack/plugins/ml/common/openapi/README.md @@ -5,6 +5,7 @@ The current self-contained spec file can be used for online tools like those fou A guide about the openApi specification can be found at [https://swagger.io/docs/specification/about/](https://swagger.io/docs/specification/about/). The `ml_apis_v2.json` file uses OpenAPI Specification Version 2.0. +The `ml_apis_v3.yaml` file uses OpenAPI Specification Version 3.0.1. ## Tools @@ -12,4 +13,5 @@ It is possible to validate the docs before bundling them by running the followin ``` npx swagger-cli validate ml_apis_v2.json +npx swagger-cli validate ml_apis_v3.yaml ``` diff --git a/x-pack/plugins/ml/common/openapi/ml_apis_v3.yaml b/x-pack/plugins/ml/common/openapi/ml_apis_v3.yaml new file mode 100644 index 0000000000000..938b3c312c0c4 --- /dev/null +++ b/x-pack/plugins/ml/common/openapi/ml_apis_v3.yaml @@ -0,0 +1,169 @@ +openapi: 3.0.1 +info: + title: Machine learning APIs + description: Kibana APIs for the machine learning feature + version: "1.0.1" + license: + name: Elastic License 2.0 + url: https://www.elastic.co/licensing/elastic-license +tags: + - name: ml + description: Machine learning +servers: + - url: https://localhost:5601/ +paths: + /s/{spaceId}/api/ml/saved_objects/sync: + get: + summary: Synchronizes Kibana saved objects for machine learning jobs and trained models. + description: > + You must have `all` privileges for the **Machine Learning** feature in the **Analytics** section of the Kibana feature privileges. + This API runs automatically when you start Kibana and periodically thereafter. + operationId: ml-sync + tags: + - ml + parameters: + - $ref: '#/components/parameters/spaceParam' + - $ref: '#/components/parameters/simulateParam' + responses: + '200': + description: Indicates a successful call + content: + application/json: + schema: + $ref: '#/components/schemas/mlSyncResponse' + examples: + syncExample: + $ref: '#/components/examples/mlSyncExample' +components: + parameters: + spaceParam: + in: path + name: spaceId + description: An identifier for the space. If `/s/` and the identifier are omitted from the path, the default space is used. + required: true + schema: + type: string + simulateParam: + in: query + name: simulate + description: When true, simulates the synchronization by returning only the list of actions that would be performed. + required: false + schema: + type: boolean + example: 'true' + securitySchemes: + basicAuth: + type: http + scheme: basic + apiKeyAuth: + type: apiKey + in: header + name: ApiKey + schemas: + mlSyncResponseSuccess: + type: boolean + description: The success or failure of the synchronization. + mlSyncResponseAnomalyDetectors: + type: object + title: Sync API response for anomaly detection jobs + description: The sync machine learning saved objects API response contains this object when there are anomaly detection jobs affected by the synchronization. There is an object for each relevant job, which contains the synchronization status. + properties: + success: + $ref: '#/components/schemas/mlSyncResponseSuccess' + mlSyncResponseDatafeeds: + type: object + title: Sync API response for datafeeds + description: The sync machine learning saved objects API response contains this object when there are datafeeds affected by the synchronization. There is an object for each relevant datafeed, which contains the synchronization status. + properties: + success: + $ref: '#/components/schemas/mlSyncResponseSuccess' + mlSyncResponseDataFrameAnalytics: + type: object + title: Sync API response for data frame analytics jobs + description: The sync machine learning saved objects API response contains this object when there are data frame analytics jobs affected by the synchronization. There is an object for each relevant job, which contains the synchronization status. + properties: + success: + $ref: '#/components/schemas/mlSyncResponseSuccess' + mlSyncResponseSavedObjectsCreated: + type: object + title: Sync API response for created saved objects + description: If saved objects are missing for machine learning jobs or trained models, they are created when you run the sync machine learning saved objects API. + properties: + anomaly-detector: + type: object + description: If saved objects are missing for anomaly detection jobs, they are created. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseAnomalyDetectors' + data-frame-analytics: + type: object + description: If saved objects are missing for data frame analytics jobs, they are created. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseDataFrameAnalytics' + trained-model: + type: object + description: If saved objects are missing for trained models, they are created. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseTrainedModels' + mlSyncResponseSavedObjectsDeleted: + type: object + title: Sync API response for deleted saved objects + description: If saved objects exist for machine learning jobs or trained models that no longer exist, they are deleted when you run the sync machine learning saved objects API. + properties: + anomaly-detector: + type: object + description: If there are saved objects exist for nonexistent anomaly detection jobs, they are deleted. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseAnomalyDetectors' + data-frame-analytics: + type: object + description: If there are saved objects exist for nonexistent data frame analytics jobs, they are deleted. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseDataFrameAnalytics' + trained-model: + type: object + description: If there are saved objects exist for nonexistent trained models, they are deleted. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseTrainedModels' + mlSyncResponseTrainedModels: + type: object + title: Sync API response for trained models + description: The sync machine learning saved objects API response contains this object when there are trained models affected by the synchronization. There is an object for each relevant trained model, which contains the synchronization status. + properties: + success: + $ref: '#/components/schemas/mlSyncResponseSuccess' + mlSyncResponse: + type: object + title: Sync API response + properties: + datafeedsAdded: + type: object + description: If a saved object for an anomaly detection job is missing a datafeed identifier, it is added when you run the sync machine learning saved objects API. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseDatafeeds' + datafeedsRemoved: + type: object + description: If a saved object for an anomaly detection job references a datafeed that no longer exists, it is deleted when you run the sync machine learning saved objects API. + additionalProperties: + $ref: '#/components/schemas/mlSyncResponseDatafeeds' + savedObjectsCreated: + $ref: '#/components/schemas/mlSyncResponseSavedObjectsCreated' + savedObjectsDeleted: + $ref: '#/components/schemas/mlSyncResponseSavedObjectsDeleted' + examples: + mlSyncExample: + summary: Two anomaly detection jobs required synchronization in this example. + value: + { + "savedObjectsCreated": { + "anomaly_detector": { + "myjob1": { "success":true }, + "myjob2":{ "success":true } + } + }, + "savedObjectsDeleted": {}, + "datafeedsAdded":{}, + "datafeedsRemoved":{} + } +security: + - basicAuth: [ ] + - ApiKeyAuth: [ ] \ No newline at end of file diff --git a/x-pack/plugins/ml/public/application/aiops/log_categorization.tsx b/x-pack/plugins/ml/public/application/aiops/log_categorization.tsx index e1d816d61357a..899006b5918dd 100644 --- a/x-pack/plugins/ml/public/application/aiops/log_categorization.tsx +++ b/x-pack/plugins/ml/public/application/aiops/log_categorization.tsx @@ -34,7 +34,7 @@ export const LogCategorizationPage: FC = () => { diff --git a/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.test.tsx b/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.test.tsx index 0d20267f33ecb..7566d3664af61 100644 --- a/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.test.tsx +++ b/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.test.tsx @@ -20,7 +20,7 @@ jest.mock('./full_time_range_selector_service', () => ({ mockSetFullTimeRange(indexPattern, query), })); -jest.mock('../../contexts/ml/use_storage', () => { +jest.mock('../../contexts/storage', () => { return { useStorage: jest.fn(() => 'exclude-frozen'), }; diff --git a/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.tsx b/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.tsx index 06bb873971ba0..9b9154eb33660 100644 --- a/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.tsx +++ b/x-pack/plugins/ml/public/application/components/full_time_range_selector/full_time_range_selector.tsx @@ -23,7 +23,7 @@ import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/type import { i18n } from '@kbn/i18n'; import type { DataView } from '@kbn/data-views-plugin/public'; import { setFullTimeRange } from './full_time_range_selector_service'; -import { useStorage } from '../../contexts/ml/use_storage'; +import { useStorage } from '../../contexts/storage'; import { ML_FROZEN_TIER_PREFERENCE } from '../../../../common/types/storage'; import { GetTimeFieldRangeResponse } from '../../services/ml_api_service'; diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx index 79d33ef9cd2ab..16fbc81b23f12 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx @@ -28,7 +28,7 @@ import { JobSelectorFlyoutProps, } from './job_selector_flyout'; import { MlJobWithTimeRange } from '../../../../common/types/anomaly_detection_jobs'; -import { useStorage } from '../../contexts/ml/use_storage'; +import { useStorage } from '../../contexts/storage'; import { ML_APPLY_TIME_RANGE_CONFIG } from '../../../../common/types/storage'; interface GroupObj { diff --git a/x-pack/plugins/ml/public/application/components/ml_page/notifications_indicator.tsx b/x-pack/plugins/ml/public/application/components/ml_page/notifications_indicator.tsx index 20d771f5654d4..d0e3516af3db0 100644 --- a/x-pack/plugins/ml/public/application/components/ml_page/notifications_indicator.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_page/notifications_indicator.tsx @@ -16,7 +16,10 @@ import { EuiToolTip, } from '@elastic/eui'; import { combineLatest, of, timer } from 'rxjs'; -import { catchError, filter, switchMap } from 'rxjs/operators'; +import { catchError, switchMap } from 'rxjs/operators'; +import moment from 'moment'; +import { FIELD_FORMAT_IDS } from '@kbn/field-formats-plugin/common'; +import { useFieldFormatter } from '../../contexts/kibana/use_field_formatter'; import { useAsObservable } from '../../hooks'; import { NotificationsCountResponse } from '../../../../common/types/notifications'; import { useMlKibana } from '../../contexts/kibana'; @@ -31,21 +34,26 @@ export const NotificationsIndicator: FC = () => { mlServices: { mlApiServices }, }, } = useMlKibana(); - const [lastCheckedAt] = useStorage(ML_NOTIFICATIONS_LAST_CHECKED_AT); + const dateFormatter = useFieldFormatter(FIELD_FORMAT_IDS.DATE); + const [lastCheckedAt] = useStorage(ML_NOTIFICATIONS_LAST_CHECKED_AT); const lastCheckedAt$ = useAsObservable(lastCheckedAt); + /** Holds the value used for the actual request */ + const [lastCheckRequested, setLastCheckRequested] = useState(); const [notificationsCounts, setNotificationsCounts] = useState(); useEffect(function startPollingNotifications() { - const subscription = combineLatest([ - lastCheckedAt$.pipe(filter((v): v is number => !!v)), - timer(0, NOTIFICATIONS_CHECK_INTERVAL), - ]) + const subscription = combineLatest([lastCheckedAt$, timer(0, NOTIFICATIONS_CHECK_INTERVAL)]) .pipe( - switchMap(([lastChecked]) => - mlApiServices.notifications.countMessages$({ lastCheckedAt: lastChecked }) - ), + switchMap(([lastChecked]) => { + const lastCheckedAtQuery = lastChecked ?? moment().subtract(7, 'd').valueOf(); + setLastCheckRequested(lastCheckedAtQuery); + // Use the latest check time or 7 days ago by default. + return mlApiServices.notifications.countMessages$({ + lastCheckedAt: lastCheckedAtQuery, + }); + }), catchError((error) => { // Fail silently for now return of({} as NotificationsCountResponse); @@ -80,12 +88,22 @@ export const NotificationsIndicator: FC = () => { content={ } > - {errorsAndWarningCount} + + {errorsAndWarningCount} +
) : null} @@ -96,7 +114,8 @@ export const NotificationsIndicator: FC = () => { content={ } > @@ -106,6 +125,7 @@ export const NotificationsIndicator: FC = () => { aria-label={i18n.translate('xpack.ml.notificationsIndicator.unreadIcon', { defaultMessage: 'Unread notifications indicator.', })} + data-test-subj={'mlNotificationsIndicator'} /> diff --git a/x-pack/plugins/ml/public/application/contexts/ml/use_storage.ts b/x-pack/plugins/ml/public/application/contexts/ml/use_storage.ts deleted file mode 100644 index 761434a7bb3b4..0000000000000 --- a/x-pack/plugins/ml/public/application/contexts/ml/use_storage.ts +++ /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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { useCallback, useState } from 'react'; -import { isDefined } from '../../../../common/types/guards'; -import { useMlKibana } from '../kibana'; -import type { MlStorageKey } from '../../../../common/types/storage'; -import { TMlStorageMapped } from '../../../../common/types/storage'; - -/** - * Hook for accessing and changing a value in the storage. - * @param key - Storage key - * @param initValue - */ -export function useStorage>( - key: K, - initValue?: T -): [ - typeof initValue extends undefined - ? TMlStorageMapped - : Exclude, undefined>, - (value: TMlStorageMapped) => void -] { - const { - services: { storage }, - } = useMlKibana(); - - const [val, setVal] = useState(storage.get(key) ?? initValue); - - const setStorage = useCallback((value: TMlStorageMapped): void => { - try { - if (isDefined(value)) { - storage.set(key, value); - setVal(value); - } else { - storage.remove(key); - setVal(initValue); - } - } catch (e) { - throw new Error('Unable to update storage with provided value'); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return [val, setStorage]; -} diff --git a/x-pack/plugins/ml/public/application/contexts/storage/storage_context.test.tsx b/x-pack/plugins/ml/public/application/contexts/storage/storage_context.test.tsx new file mode 100644 index 0000000000000..6aeeb396f38c3 --- /dev/null +++ b/x-pack/plugins/ml/public/application/contexts/storage/storage_context.test.tsx @@ -0,0 +1,144 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook, act } from '@testing-library/react-hooks'; +import { MlStorageContextProvider, useStorage } from './storage_context'; +import { MlStorageKey } from '../../../../common/types/storage'; + +const mockSet = jest.fn(); +const mockRemove = jest.fn(); + +jest.mock('../kibana', () => ({ + useMlKibana: () => { + return { + services: { + storage: { + set: mockSet, + get: jest.fn((key: MlStorageKey) => { + switch (key) { + case 'ml.gettingStarted.isDismissed': + return true; + default: + return; + } + }), + remove: mockRemove, + }, + }, + }; + }, +})); + +describe('useStorage', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + test('returns the default value', () => { + const { result } = renderHook(() => useStorage('ml.jobSelectorFlyout.applyTimeRange', true), { + wrapper: MlStorageContextProvider, + }); + + expect(result.current[0]).toBe(true); + }); + + test('returns the value from storage', () => { + const { result } = renderHook(() => useStorage('ml.gettingStarted.isDismissed', false), { + wrapper: MlStorageContextProvider, + }); + + expect(result.current[0]).toBe(true); + }); + + test('updates the storage value', async () => { + const { result, waitForNextUpdate } = renderHook( + () => useStorage('ml.gettingStarted.isDismissed'), + { + wrapper: MlStorageContextProvider, + } + ); + + const [value, setValue] = result.current; + + expect(value).toBe(true); + + await act(async () => { + setValue(false); + await waitForNextUpdate(); + }); + + expect(result.current[0]).toBe(false); + expect(mockSet).toHaveBeenCalledWith('ml.gettingStarted.isDismissed', false); + }); + + test('removes the storage value', async () => { + const { result, waitForNextUpdate } = renderHook( + () => useStorage('ml.gettingStarted.isDismissed'), + { + wrapper: MlStorageContextProvider, + } + ); + + const [value, setValue] = result.current; + + expect(value).toBe(true); + + await act(async () => { + setValue(undefined); + await waitForNextUpdate(); + }); + + expect(result.current[0]).toBe(undefined); + expect(mockRemove).toHaveBeenCalledWith('ml.gettingStarted.isDismissed'); + }); + + test('updates the value on storage event', async () => { + const { result, waitForNextUpdate } = renderHook( + () => useStorage('ml.gettingStarted.isDismissed'), + { + wrapper: MlStorageContextProvider, + } + ); + + expect(result.current[0]).toBe(true); + + await act(async () => { + window.dispatchEvent( + new StorageEvent('storage', { + key: 'test_key', + newValue: 'test_value', + }) + ); + }); + + expect(result.current[0]).toBe(true); + + await act(async () => { + window.dispatchEvent( + new StorageEvent('storage', { + key: 'ml.gettingStarted.isDismissed', + newValue: null, + }) + ); + await waitForNextUpdate(); + }); + + expect(result.current[0]).toBe(undefined); + + await act(async () => { + window.dispatchEvent( + new StorageEvent('storage', { + key: 'ml.gettingStarted.isDismissed', + newValue: 'false', + }) + ); + await waitForNextUpdate(); + }); + + expect(result.current[0]).toBe(false); + }); +}); diff --git a/x-pack/plugins/ml/public/application/contexts/storage/storage_context.tsx b/x-pack/plugins/ml/public/application/contexts/storage/storage_context.tsx index ccd46c446ed2c..c2b00a176c08c 100644 --- a/x-pack/plugins/ml/public/application/contexts/storage/storage_context.tsx +++ b/x-pack/plugins/ml/public/application/contexts/storage/storage_context.tsx @@ -69,7 +69,8 @@ export const MlStorageContextProvider: FC = ({ children }) => { setState((prev) => { return { ...prev, - [event.key as MlStorageKey]: event.newValue, + [event.key as MlStorageKey]: + typeof event.newValue === 'string' ? JSON.parse(event.newValue) : event.newValue, }; }); } else { @@ -106,21 +107,32 @@ export const MlStorageContextProvider: FC = ({ children }) => { * @param key * @param initValue */ -export function useStorage( +export function useStorage>( key: K, - initValue?: TMlStorageMapped -): [TMlStorageMapped | undefined, (value: TMlStorageMapped) => void] { - const { value, setValue } = useContext(MlStorageContext); + initValue?: T +): [ + typeof initValue extends undefined + ? TMlStorageMapped | undefined + : Exclude, undefined>, + (value: TMlStorageMapped) => void +] { + const { value, setValue, removeValue } = useContext(MlStorageContext); const resultValue = useMemo(() => { - return (value?.[key] ?? initValue) as TMlStorageMapped; + return (value?.[key] ?? initValue) as typeof initValue extends undefined + ? TMlStorageMapped | undefined + : Exclude, undefined>; }, [value, key, initValue]); const setVal = useCallback( (v: TMlStorageMapped) => { - setValue(key, v); + if (isDefined(v)) { + setValue(key, v); + } else { + removeValue(key); + } }, - [setValue, key] + [setValue, removeValue, key] ); return [resultValue, setVal]; diff --git a/x-pack/plugins/ml/public/application/explorer/dashboard_controls/add_swimlane_to_dashboard_controls.tsx b/x-pack/plugins/ml/public/application/explorer/dashboard_controls/add_swimlane_to_dashboard_controls.tsx index 7f109defdff79..93fa7e908f35a 100644 --- a/x-pack/plugins/ml/public/application/explorer/dashboard_controls/add_swimlane_to_dashboard_controls.tsx +++ b/x-pack/plugins/ml/public/application/explorer/dashboard_controls/add_swimlane_to_dashboard_controls.tsx @@ -15,7 +15,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; -import { DashboardSavedObject } from '@kbn/dashboard-plugin/public'; +import { DashboardAttributes } from '@kbn/dashboard-plugin/common'; import type { Query } from '@kbn/es-query'; import { SEARCH_QUERY_LANGUAGE } from '../../../../common/constants/search'; import { getDefaultSwimlanePanelTitle } from '../../../embeddables/anomaly_swimlane/anomaly_swimlane_embeddable'; @@ -30,7 +30,7 @@ export interface DashboardItem { id: string; title: string; description: string | undefined; - attributes: DashboardSavedObject; + attributes: DashboardAttributes; } export type EuiTableProps = EuiInMemoryTableProps; diff --git a/x-pack/plugins/ml/public/application/explorer/dashboard_controls/use_dashboards_table.tsx b/x-pack/plugins/ml/public/application/explorer/dashboard_controls/use_dashboards_table.tsx index ac023017d43f5..8bb7705938d84 100644 --- a/x-pack/plugins/ml/public/application/explorer/dashboard_controls/use_dashboards_table.tsx +++ b/x-pack/plugins/ml/public/application/explorer/dashboard_controls/use_dashboards_table.tsx @@ -8,7 +8,7 @@ import type { EuiInMemoryTableProps } from '@elastic/eui'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { debounce } from 'lodash'; -import type { DashboardSavedObject } from '@kbn/dashboard-plugin/public'; +import type { DashboardAttributes } from '@kbn/dashboard-plugin/common'; import { useDashboardService } from '../../services/dashboard_service'; import { useMlKibana } from '../../contexts/kibana'; @@ -16,7 +16,7 @@ export interface DashboardItem { id: string; title: string; description: string | undefined; - attributes: DashboardSavedObject; + attributes: DashboardAttributes; } export type EuiTableProps = EuiInMemoryTableProps; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer.tsx b/x-pack/plugins/ml/public/application/explorer/explorer.tsx index b9feffb1ec116..5fcab05f068b8 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer.tsx @@ -78,7 +78,7 @@ import { useMlKibana, useMlLocator } from '../contexts/kibana'; import { useMlContext } from '../contexts/ml'; import { useAnomalyExplorerContext } from './anomaly_explorer_context'; import { ML_ANOMALY_EXPLORER_PANELS } from '../../../common/types/storage'; -import { useStorage } from '../contexts/ml/use_storage'; +import { useStorage } from '../contexts/storage'; interface ExplorerPageProps { jobSelectorProps: JobSelectorProps; diff --git a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx index 811b1c43bce37..9ea6aa1b70f00 100644 --- a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx +++ b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx @@ -162,6 +162,7 @@ export const NotificationsList: FC = () => { const columns: Array> = [ { + id: 'timestamp', field: 'timestamp', name: , sortable: true, @@ -175,7 +176,7 @@ export const NotificationsList: FC = () => { name: , sortable: true, truncateText: false, - 'data-test-subj': 'mlNotificationLabel', + 'data-test-subj': 'mlNotificationLevel', render: (value: MlNotificationMessageLevel) => { return {value}; }, @@ -194,7 +195,7 @@ export const NotificationsList: FC = () => { }, { field: 'job_id', - name: , + name: , sortable: true, truncateText: false, 'data-test-subj': 'mlNotificationEntity', @@ -320,6 +321,7 @@ export const NotificationsList: FC = () => { }, }, }, + 'data-test-subj': 'mlNotificationsSearchBarInput', }} filters={filters} onChange={(e) => { diff --git a/x-pack/plugins/ml/public/application/overview/components/getting_started_callout.tsx b/x-pack/plugins/ml/public/application/overview/components/getting_started_callout.tsx index 457bca80ee2c0..7b1f380c90658 100644 --- a/x-pack/plugins/ml/public/application/overview/components/getting_started_callout.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/getting_started_callout.tsx @@ -9,7 +9,7 @@ import React, { FC } from 'react'; import { EuiButton, EuiCallOut, EuiLink, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { useMlKibana } from '../../contexts/kibana'; -import { useStorage } from '../../contexts/ml/use_storage'; +import { useStorage } from '../../contexts/storage'; import { ML_GETTING_STARTED_CALLOUT_DISMISSED } from '../../../../common/types/storage'; const feedbackLink = 'https://www.elastic.co/community/'; diff --git a/x-pack/plugins/ml/public/application/services/dashboard_service.ts b/x-pack/plugins/ml/public/application/services/dashboard_service.ts index ff7b696551f41..abd97722f86bc 100644 --- a/x-pack/plugins/ml/public/application/services/dashboard_service.ts +++ b/x-pack/plugins/ml/public/application/services/dashboard_service.ts @@ -7,7 +7,8 @@ import { SavedObjectsClientContract } from '@kbn/core/public'; import { useMemo } from 'react'; -import { DashboardSavedObject, DashboardAppLocator } from '@kbn/dashboard-plugin/public'; +import { DashboardAppLocator } from '@kbn/dashboard-plugin/public'; +import type { DashboardAttributes } from '@kbn/dashboard-plugin/common'; import { ViewMode } from '@kbn/embeddable-plugin/public'; import { useMlKibana } from '../contexts/kibana'; @@ -22,7 +23,7 @@ export function dashboardServiceProvider( * Fetches dashboards */ async fetchDashboards(query?: string) { - return await savedObjectClient.find({ + return await savedObjectClient.find({ type: 'dashboard', perPage: 1000, search: query ? `${query}*` : '', diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx index 0df10505e73cc..23084c8d8886d 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx @@ -26,7 +26,7 @@ import { PartitionFieldConfig, PartitionFieldsConfig, } from '../../../../../common/types/storage'; -import { useStorage } from '../../../contexts/ml/use_storage'; +import { useStorage } from '../../../contexts/storage'; import { EntityFieldType } from '../../../../../common/types/anomalies'; import { FieldDefinition } from '../../../services/results_service/result_service_rx'; import { getViewableDetectors } from '../../timeseriesexplorer_utils/get_viewable_detectors'; diff --git a/x-pack/plugins/ml/public/application/trained_models/nodes_overview/allocated_models.tsx b/x-pack/plugins/ml/public/application/trained_models/nodes_overview/allocated_models.tsx index 0da7778c6e2bc..d1808c2c82135 100644 --- a/x-pack/plugins/ml/public/application/trained_models/nodes_overview/allocated_models.tsx +++ b/x-pack/plugins/ml/public/application/trained_models/nodes_overview/allocated_models.tsx @@ -190,6 +190,7 @@ export const AllocatedModels: FC = ({ })} onTableChange={() => {}} data-test-subj={'mlNodesAllocatedModels'} + css={{ overflow: 'auto' }} /> ); }; diff --git a/x-pack/plugins/ml/public/application/trained_models/nodes_overview/expanded_row.tsx b/x-pack/plugins/ml/public/application/trained_models/nodes_overview/expanded_row.tsx index 4c96904862786..a6b6adc4fbc20 100644 --- a/x-pack/plugins/ml/public/application/trained_models/nodes_overview/expanded_row.tsx +++ b/x-pack/plugins/ml/public/application/trained_models/nodes_overview/expanded_row.tsx @@ -17,6 +17,7 @@ import { import { FormattedMessage } from '@kbn/i18n-react'; import { cloneDeep } from 'lodash'; import { FIELD_FORMAT_IDS } from '@kbn/field-formats-plugin/common'; +import { css } from '@emotion/react'; import { NodeItem } from './nodes_list'; import { useListItemsFormatter } from '../models_management/expanded_row'; import { AllocatedModels } from './allocated_models'; @@ -44,10 +45,12 @@ export const ExpandedRow: FC = ({ item }) => { attributes['ml.max_jvm_size'] = bytesFormatter(attributes['ml.max_jvm_size']); return ( - <> - - - +
+ @@ -85,25 +88,26 @@ export const ExpandedRow: FC = ({ item }) => { /> + - {allocatedModels.length > 0 ? ( - - - -
- -
-
- + {allocatedModels.length > 0 ? ( + <> + + + +
+ +
+
+ - -
-
- ) : null} - - + + + + ) : null} +
); }; diff --git a/x-pack/plugins/ml/server/routes/schemas/notifications_schema.ts b/x-pack/plugins/ml/server/routes/schemas/notifications_schema.ts index a82691ee52813..153ffd0aeea87 100644 --- a/x-pack/plugins/ml/server/routes/schemas/notifications_schema.ts +++ b/x-pack/plugins/ml/server/routes/schemas/notifications_schema.ts @@ -8,26 +8,10 @@ import { schema, TypeOf } from '@kbn/config-schema'; export const getNotificationsQuerySchema = schema.object({ - /** - * Message level, e.g. info, error - */ - level: schema.maybe(schema.string()), - /** - * Message type, e.g. anomaly_detector - */ - type: schema.maybe(schema.string()), /** * Search string for the message content */ queryString: schema.maybe(schema.string()), - /** - * Page numer, zero-indexed - */ - from: schema.number({ defaultValue: 0 }), - /** - * Number of messages to return - */ - size: schema.number({ defaultValue: 10 }), /** * Sort field */ diff --git a/x-pack/plugins/observability/e2e/synthetics_runner.ts b/x-pack/plugins/observability/e2e/synthetics_runner.ts index 25c236c6da585..a24771c091c09 100644 --- a/x-pack/plugins/observability/e2e/synthetics_runner.ts +++ b/x-pack/plugins/observability/e2e/synthetics_runner.ts @@ -10,7 +10,7 @@ import Url from 'url'; import { run as syntheticsRun } from '@elastic/synthetics'; import { PromiseType } from 'utility-types'; -import { createApmUsers } from '@kbn/apm-plugin/scripts/create_apm_users/create_apm_users'; +import { createApmUsers } from '@kbn/apm-plugin/server/test_helpers/create_apm_users/create_apm_users'; import { esArchiverUnload } from './tasks/es_archiver'; @@ -23,6 +23,7 @@ export interface ArgParams { export class SyntheticsRunner { public getService: any; public kibanaUrl: string; + private elasticsearchUrl: string; public testFilesLoaded: boolean = false; @@ -31,6 +32,7 @@ export class SyntheticsRunner { constructor(getService: any, params: ArgParams) { this.getService = getService; this.kibanaUrl = this.getKibanaUrl(); + this.elasticsearchUrl = this.getElasticsearchUrl(); this.params = params; } @@ -40,7 +42,7 @@ export class SyntheticsRunner { async createTestUsers() { await createApmUsers({ - elasticsearch: { username: 'elastic', password: 'changeme' }, + elasticsearch: { node: this.elasticsearchUrl, username: 'elastic', password: 'changeme' }, kibana: { hostname: this.kibanaUrl }, }); } @@ -79,6 +81,16 @@ export class SyntheticsRunner { }); } + getElasticsearchUrl() { + const config = this.getService('config'); + + return Url.format({ + protocol: config.get('servers.elasticsearch.protocol'), + hostname: config.get('servers.elasticsearch.hostname'), + port: config.get('servers.elasticsearch.port'), + }); + } + async run() { if (!this.testFilesLoaded) { throw new Error('Test files not loaded'); diff --git a/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.test.tsx b/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.test.tsx index 6e79c3691402a..38626ad0364cc 100644 --- a/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.test.tsx +++ b/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.test.tsx @@ -30,16 +30,6 @@ describe('ObservabilityStatusProgress', () => { forceUpdate: '', } as HasDataContextValue); }); - it('should render the progress', () => { - render( - - - - ); - const progressBar = screen.getByRole('progressbar') as HTMLProgressElement; - expect(progressBar).toBeInTheDocument(); - expect(progressBar.value).toBe(50); - }); it('should call the onViewDetailsCallback when view details button is clicked', () => { render( diff --git a/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.tsx b/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.tsx index 050da44457969..e08ffe0fb3c4e 100644 --- a/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.tsx +++ b/x-pack/plugins/observability/public/components/app/observability_status/observability_status_progress.tsx @@ -4,10 +4,9 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React, { useState, useEffect, useCallback } from 'react'; +import React, { useCallback } from 'react'; import { EuiPanel, - EuiProgress, EuiTitle, EuiButtonEmpty, EuiButton, @@ -16,9 +15,7 @@ import { EuiFlexItem, EuiSpacer, } from '@elastic/eui'; -import { reduce } from 'lodash'; import { FormattedMessage } from '@kbn/i18n-react'; -import { useHasData } from '../../../hooks/use_has_data'; import { useUiTracker } from '../../../hooks/use_track_metric'; import { useGuidedSetupProgress } from '../../../hooks/use_guided_setup_progress'; @@ -30,28 +27,9 @@ export function ObservabilityStatusProgress({ onViewDetailsClick, onDismissClick, }: ObservabilityStatusProgressProps) { - const { hasDataMap, isAllRequestsComplete } = useHasData(); const trackMetric = useUiTracker({ app: 'observability-overview' }); const { isGuidedSetupProgressDismissed, dismissGuidedSetupProgress } = useGuidedSetupProgress(); - const [progress, setProgress] = useState(0); - - useEffect(() => { - const totalCounts = Object.keys(hasDataMap); - if (isAllRequestsComplete) { - const hasDataCount = reduce( - hasDataMap, - (result, value) => { - return value?.hasData ? result + 1 : result; - }, - 0 - ); - - const percentage = (hasDataCount / totalCounts.length) * 100; - setProgress(isFinite(percentage) ? percentage : 0); - } - }, [isAllRequestsComplete, hasDataMap]); - const dismissGuidedSetup = useCallback(() => { dismissGuidedSetupProgress(); if (onDismissClick) { @@ -68,15 +46,13 @@ export function ObservabilityStatusProgress({ return !isGuidedSetupProgressDismissed ? ( <> - -

diff --git a/x-pack/plugins/observability/public/components/shared/tour/steps_config.ts b/x-pack/plugins/observability/public/components/shared/tour/steps_config.ts index 0c5e101aac9ad..50200d22f0ad5 100644 --- a/x-pack/plugins/observability/public/components/shared/tour/steps_config.ts +++ b/x-pack/plugins/observability/public/components/shared/tour/steps_config.ts @@ -112,7 +112,7 @@ export const tourStepsConfig: TourStep[] = [ }), content: i18n.translate('xpack.observability.tour.guidedSetupStep.tourContent', { defaultMessage: - 'The easiest way to get going with Elastic Observability is to follow the Guided setup.', + 'The easiest way to get going with Elastic Observability is to follow the steps in the data assistant.', }), anchor: '#guidedSetupButton', anchorPosition: 'rightUp', diff --git a/x-pack/plugins/observability/public/components/shared/tour/tour.tsx b/x-pack/plugins/observability/public/components/shared/tour/tour.tsx index 98b6bb7e0a38a..0c9e9ae65b058 100644 --- a/x-pack/plugins/observability/public/components/shared/tour/tour.tsx +++ b/x-pack/plugins/observability/public/components/shared/tour/tour.tsx @@ -239,7 +239,7 @@ export function ObservabilityTour({ }, [activeStep]); useEffect(() => { - // The user must be on the overview page to view the guided setup step in the tour + // The user must be on the overview page to view the data assistant step in the tour if (isTourActive && isOverviewPage === false && activeStep === guidedSetupStep) { navigateToApp(observabilityAppId, { path: overviewPath, diff --git a/x-pack/plugins/observability/public/pages/overview/containers/overview_page/overview_page.tsx b/x-pack/plugins/observability/public/pages/overview/containers/overview_page/overview_page.tsx index 1f09cfc38cf4c..16ccd0e1fdc06 100644 --- a/x-pack/plugins/observability/public/pages/overview/containers/overview_page/overview_page.tsx +++ b/x-pack/plugins/observability/public/pages/overview/containers/overview_page/overview_page.tsx @@ -226,10 +226,13 @@ export function OverviewPage() { > -

+

@@ -289,7 +292,7 @@ function PageHeader({ color="text" iconType="wrench" onClick={() => { - // End the Observability tour if it's visible and the user clicks the guided setup button + // End the Observability tour if it's visible and the user clicks the data assistant button if (isObservabilityTourVisible) { endObservabilityTour(); } @@ -298,7 +301,7 @@ function PageHeader({ > {showTour ? ( @@ -307,13 +310,13 @@ function PageHeader({ anchor={() => buttonRef.current} isStepOpen title={i18n.translate('xpack.observability.overview.guidedSetupTourTitle', { - defaultMessage: 'Guided setup is always available', + defaultMessage: 'Data assistant is always available', })} content={ } diff --git a/x-pack/plugins/observability/server/assets/constants.ts b/x-pack/plugins/observability/server/assets/constants.ts index 4c0cc0e2e6f83..182ca89712dcc 100644 --- a/x-pack/plugins/observability/server/assets/constants.ts +++ b/x-pack/plugins/observability/server/assets/constants.ts @@ -9,11 +9,7 @@ export const SLO_COMPONENT_TEMPLATE_MAPPINGS_NAME = 'slo-observability.sli-mappi export const SLO_COMPONENT_TEMPLATE_SETTINGS_NAME = 'slo-observability.sli-settings'; export const SLO_INDEX_TEMPLATE_NAME = 'slo-observability.sli'; export const SLO_RESOURCES_VERSION = 1; - -export const getSLOIngestPipelineName = (spaceId: string) => - `${SLO_INDEX_TEMPLATE_NAME}.monthly-${spaceId}`; - -export const getSLODestinationIndexName = (spaceId: string) => - `${SLO_INDEX_TEMPLATE_NAME}-v${SLO_RESOURCES_VERSION}-${spaceId}`; +export const SLO_INGEST_PIPELINE_NAME = `${SLO_INDEX_TEMPLATE_NAME}.monthly`; +export const SLO_DESTINATION_INDEX_NAME = `${SLO_INDEX_TEMPLATE_NAME}-v${SLO_RESOURCES_VERSION}`; export const getSLOTransformId = (sloId: string) => `slo-${sloId}`; diff --git a/x-pack/plugins/observability/server/plugin.ts b/x-pack/plugins/observability/server/plugin.ts index 1d9d3cbf455f1..ff5fd246bea1b 100644 --- a/x-pack/plugins/observability/server/plugin.ts +++ b/x-pack/plugins/observability/server/plugin.ts @@ -144,7 +144,6 @@ export class ObservabilityPlugin implements Plugin { const start = () => core.getStartServices().then(([coreStart]) => coreStart); - const { spacesService } = plugins.spaces; const { ruleDataService } = plugins.ruleRegistry; registerRoutes({ @@ -155,7 +154,6 @@ export class ObservabilityPlugin implements Plugin { logger: this.initContext.logger.get(), repository: getGlobalObservabilityServerRouteRepository(config), ruleDataService, - spacesService, }); return { diff --git a/x-pack/plugins/observability/server/routes/register_routes.ts b/x-pack/plugins/observability/server/routes/register_routes.ts index e0e9e94f5cb21..1c45eb6001479 100644 --- a/x-pack/plugins/observability/server/routes/register_routes.ts +++ b/x-pack/plugins/observability/server/routes/register_routes.ts @@ -14,7 +14,6 @@ import { CoreSetup, CoreStart, Logger, RouteRegistrar } from '@kbn/core/server'; import Boom from '@hapi/boom'; import { errors } from '@elastic/elasticsearch'; import { RuleDataPluginService } from '@kbn/rule-registry-plugin/server'; -import { SpacesServiceStart } from '@kbn/spaces-plugin/server'; import { ObservabilityRequestHandlerContext } from '../types'; import { AbstractObservabilityServerRouteRepository } from './types'; import { getHTTPResponseCode, ObservabilityError } from '../errors'; @@ -24,7 +23,6 @@ export function registerRoutes({ core, logger, ruleDataService, - spacesService, }: { core: { setup: CoreSetup; @@ -33,7 +31,6 @@ export function registerRoutes({ repository: AbstractObservabilityServerRouteRepository; logger: Logger; ruleDataService: RuleDataPluginService; - spacesService: SpacesServiceStart; }) { const routes = Object.values(repository); @@ -67,7 +64,6 @@ export function registerRoutes({ logger, params: decodedParams, ruleDataService, - spacesService, })) as any; if (data === undefined) { diff --git a/x-pack/plugins/observability/server/routes/slo/route.ts b/x-pack/plugins/observability/server/routes/slo/route.ts index dc1db41e44995..63ef4e1e07e64 100644 --- a/x-pack/plugins/observability/server/routes/slo/route.ts +++ b/x-pack/plugins/observability/server/routes/slo/route.ts @@ -11,14 +11,20 @@ import { DefaultResourceInstaller, DefaultTransformManager, KibanaSavedObjectsSLORepository, + GetSLO, } from '../../services/slo'; + import { ApmTransactionDurationTransformGenerator, ApmTransactionErrorRateTransformGenerator, TransformGenerator, } from '../../services/slo/transform_generators'; import { SLITypes } from '../../types/models'; -import { createSLOParamsSchema, deleteSLOParamsSchema } from '../../types/rest_specs'; +import { + createSLOParamsSchema, + deleteSLOParamsSchema, + getSLOParamsSchema, +} from '../../types/rest_specs'; import { createObservabilityServerRoute } from '../create_observability_server_route'; const transformGenerators: Record = { @@ -32,19 +38,13 @@ const createSLORoute = createObservabilityServerRoute({ tags: [], }, params: createSLOParamsSchema, - handler: async ({ context, request, params, logger, spacesService }) => { + handler: async ({ context, params, logger }) => { const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; - const spaceId = spacesService.getSpaceId(request); - const resourceInstaller = new DefaultResourceInstaller(esClient, logger, spaceId); + const resourceInstaller = new DefaultResourceInstaller(esClient, logger); const repository = new KibanaSavedObjectsSLORepository(soClient); - const transformManager = new DefaultTransformManager( - transformGenerators, - esClient, - logger, - spaceId - ); + const transformManager = new DefaultTransformManager(transformGenerators, esClient, logger); const createSLO = new CreateSLO(resourceInstaller, repository, transformManager); const response = await createSLO.execute(params.body); @@ -59,18 +59,12 @@ const deleteSLORoute = createObservabilityServerRoute({ tags: [], }, params: deleteSLOParamsSchema, - handler: async ({ context, request, params, logger, spacesService }) => { + handler: async ({ context, params, logger }) => { const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; - const spaceId = spacesService.getSpaceId(request); const repository = new KibanaSavedObjectsSLORepository(soClient); - const transformManager = new DefaultTransformManager( - transformGenerators, - esClient, - logger, - spaceId - ); + const transformManager = new DefaultTransformManager(transformGenerators, esClient, logger); const deleteSLO = new DeleteSLO(repository, transformManager, esClient); @@ -78,4 +72,21 @@ const deleteSLORoute = createObservabilityServerRoute({ }, }); -export const slosRouteRepository = { ...createSLORoute, ...deleteSLORoute }; +const getSLORoute = createObservabilityServerRoute({ + endpoint: 'GET /api/observability/slos/{id}', + options: { + tags: [], + }, + params: getSLOParamsSchema, + handler: async ({ context, params }) => { + const soClient = (await context.core).savedObjects.client; + const repository = new KibanaSavedObjectsSLORepository(soClient); + const getSLO = new GetSLO(repository); + + const response = await getSLO.execute(params.path.id); + + return response; + }, +}); + +export const slosRouteRepository = { ...createSLORoute, ...getSLORoute, ...deleteSLORoute }; diff --git a/x-pack/plugins/observability/server/services/slo/delete_slo.test.ts b/x-pack/plugins/observability/server/services/slo/delete_slo.test.ts index b1a68b9c04aee..2e43c81f6d382 100644 --- a/x-pack/plugins/observability/server/services/slo/delete_slo.test.ts +++ b/x-pack/plugins/observability/server/services/slo/delete_slo.test.ts @@ -33,6 +33,7 @@ describe('DeleteSLO', () => { await deleteSLO.execute(slo.id); + expect(mockRepository.findById).toHaveBeenCalledWith(slo.id); expect(mockTransformManager.stop).toHaveBeenCalledWith(getSLOTransformId(slo.id)); expect(mockTransformManager.uninstall).toHaveBeenCalledWith(getSLOTransformId(slo.id)); expect(mockEsClient.deleteByQuery).toHaveBeenCalledWith( diff --git a/x-pack/plugins/observability/server/services/slo/delete_slo.ts b/x-pack/plugins/observability/server/services/slo/delete_slo.ts index 59e5df8a5975a..a7d931174a59a 100644 --- a/x-pack/plugins/observability/server/services/slo/delete_slo.ts +++ b/x-pack/plugins/observability/server/services/slo/delete_slo.ts @@ -19,6 +19,9 @@ export class DeleteSLO { ) {} public async execute(sloId: string): Promise { + // ensure the slo exists on the request's space. + await this.repository.findById(sloId); + const sloTransformId = getSLOTransformId(sloId); await this.transformManager.stop(sloTransformId); await this.transformManager.uninstall(sloTransformId); diff --git a/x-pack/plugins/observability/server/services/slo/get_slo.test.ts b/x-pack/plugins/observability/server/services/slo/get_slo.test.ts new file mode 100644 index 0000000000000..768424d6b9eec --- /dev/null +++ b/x-pack/plugins/observability/server/services/slo/get_slo.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { createAPMTransactionErrorRateIndicator, createSLO } from './fixtures/slo'; +import { GetSLO } from './get_slo'; +import { createSLORepositoryMock } from './mocks'; +import { SLORepository } from './slo_repository'; + +describe('GetSLO', () => { + let mockRepository: jest.Mocked; + let getSLO: GetSLO; + + beforeEach(() => { + mockRepository = createSLORepositoryMock(); + getSLO = new GetSLO(mockRepository); + }); + + describe('happy path', () => { + it('retrieves the SLO from the repository', async () => { + const slo = createSLO(createAPMTransactionErrorRateIndicator()); + mockRepository.findById.mockResolvedValueOnce(slo); + + const result = await getSLO.execute(slo.id); + + expect(mockRepository.findById).toHaveBeenCalledWith(slo.id); + expect(result).toEqual({ + id: slo.id, + name: 'irrelevant', + description: 'irrelevant', + budgeting_method: 'occurrences', + indicator: { + params: { + environment: 'irrelevant', + good_status_codes: ['2xx', '3xx', '4xx'], + service: 'irrelevant', + transaction_name: 'irrelevant', + transaction_type: 'irrelevant', + }, + type: 'slo.apm.transaction_error_rate', + }, + objective: { + target: 0.999, + }, + time_window: { + duration: '7d', + is_rolling: true, + }, + }); + }); + }); +}); diff --git a/x-pack/plugins/observability/server/services/slo/get_slo.ts b/x-pack/plugins/observability/server/services/slo/get_slo.ts new file mode 100644 index 0000000000000..1730dec464964 --- /dev/null +++ b/x-pack/plugins/observability/server/services/slo/get_slo.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { SLO } from '../../types/models'; +import { GetSLOResponse } from '../../types/rest_specs'; +import { SLORepository } from './slo_repository'; + +export class GetSLO { + constructor(private repository: SLORepository) {} + + public async execute(sloId: string): Promise { + const slo = await this.repository.findById(sloId); + return this.toResponse(slo); + } + + private toResponse(slo: SLO): GetSLOResponse { + return { + id: slo.id, + name: slo.name, + description: slo.description, + indicator: slo.indicator, + time_window: slo.time_window, + budgeting_method: slo.budgeting_method, + objective: slo.objective, + }; + } +} diff --git a/x-pack/plugins/observability/server/services/slo/index.ts b/x-pack/plugins/observability/server/services/slo/index.ts index 895a7f4497ad5..7515262628f08 100644 --- a/x-pack/plugins/observability/server/services/slo/index.ts +++ b/x-pack/plugins/observability/server/services/slo/index.ts @@ -10,3 +10,4 @@ export * from './slo_repository'; export * from './transform_manager'; export * from './create_slo'; export * from './delete_slo'; +export * from './get_slo'; diff --git a/x-pack/plugins/observability/server/services/slo/resource_installer.test.ts b/x-pack/plugins/observability/server/services/slo/resource_installer.test.ts index f8746f38cd246..90749176513da 100644 --- a/x-pack/plugins/observability/server/services/slo/resource_installer.test.ts +++ b/x-pack/plugins/observability/server/services/slo/resource_installer.test.ts @@ -9,7 +9,7 @@ import { IngestGetPipelineResponse } from '@elastic/elasticsearch/lib/api/typesW import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { loggerMock } from '@kbn/logging-mocks'; import { - getSLOIngestPipelineName, + SLO_INGEST_PIPELINE_NAME, SLO_COMPONENT_TEMPLATE_MAPPINGS_NAME, SLO_COMPONENT_TEMPLATE_SETTINGS_NAME, SLO_INDEX_TEMPLATE_NAME, @@ -17,17 +17,12 @@ import { } from '../../assets/constants'; import { DefaultResourceInstaller } from './resource_installer'; -const SPACE_ID = 'space-id'; describe('resourceInstaller', () => { describe("when the common resources don't exist", () => { it('installs the common resources', async () => { const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient(); mockClusterClient.indices.existsIndexTemplate.mockResponseOnce(false); - const installer = new DefaultResourceInstaller( - mockClusterClient, - loggerMock.create(), - SPACE_ID - ); + const installer = new DefaultResourceInstaller(mockClusterClient, loggerMock.create()); await installer.ensureCommonResourcesInstalled(); @@ -44,7 +39,7 @@ describe('resourceInstaller', () => { expect.objectContaining({ name: SLO_INDEX_TEMPLATE_NAME }) ); expect(mockClusterClient.ingest.putPipeline).toHaveBeenCalledWith( - expect.objectContaining({ id: getSLOIngestPipelineName(SPACE_ID) }) + expect.objectContaining({ id: SLO_INGEST_PIPELINE_NAME }) ); }); }); @@ -55,13 +50,9 @@ describe('resourceInstaller', () => { mockClusterClient.indices.existsIndexTemplate.mockResponseOnce(true); mockClusterClient.ingest.getPipeline.mockResponseOnce({ // @ts-ignore _meta not typed properly - [getSLOIngestPipelineName(SPACE_ID)]: { _meta: { version: SLO_RESOURCES_VERSION } }, + [SLO_INGEST_PIPELINE_NAME]: { _meta: { version: SLO_RESOURCES_VERSION } }, } as IngestGetPipelineResponse); - const installer = new DefaultResourceInstaller( - mockClusterClient, - loggerMock.create(), - SPACE_ID - ); + const installer = new DefaultResourceInstaller(mockClusterClient, loggerMock.create()); await installer.ensureCommonResourcesInstalled(); diff --git a/x-pack/plugins/observability/server/services/slo/resource_installer.ts b/x-pack/plugins/observability/server/services/slo/resource_installer.ts index 8ed8108b3c4b7..abc02052097b5 100644 --- a/x-pack/plugins/observability/server/services/slo/resource_installer.ts +++ b/x-pack/plugins/observability/server/services/slo/resource_installer.ts @@ -13,7 +13,7 @@ import type { import type { ElasticsearchClient, Logger } from '@kbn/core/server'; import { - getSLOIngestPipelineName, + SLO_INGEST_PIPELINE_NAME, SLO_COMPONENT_TEMPLATE_MAPPINGS_NAME, SLO_COMPONENT_TEMPLATE_SETTINGS_NAME, SLO_INDEX_TEMPLATE_NAME, @@ -29,11 +29,7 @@ export interface ResourceInstaller { } export class DefaultResourceInstaller implements ResourceInstaller { - constructor( - private esClient: ElasticsearchClient, - private logger: Logger, - private spaceId: string - ) {} + constructor(private esClient: ElasticsearchClient, private logger: Logger) {} public async ensureCommonResourcesInstalled(): Promise { const alreadyInstalled = await this.areResourcesAlreadyInstalled(); @@ -64,8 +60,8 @@ export class DefaultResourceInstaller implements ResourceInstaller { await this.createOrUpdateIngestPipelineTemplate( getSLOPipelineTemplate( - getSLOIngestPipelineName(this.spaceId), - this.getPipelinePrefix(SLO_RESOURCES_VERSION, this.spaceId) + SLO_INGEST_PIPELINE_NAME, + this.getPipelinePrefix(SLO_RESOURCES_VERSION) ) ); } catch (err) { @@ -74,10 +70,10 @@ export class DefaultResourceInstaller implements ResourceInstaller { } } - private getPipelinePrefix(version: number, spaceId: string): string { + private getPipelinePrefix(version: number): string { // Following https://www.elastic.co/blog/an-introduction-to-the-elastic-data-stream-naming-scheme - // slo-observability.sli--. - return `${SLO_INDEX_TEMPLATE_NAME}-v${version}-${spaceId}.`; + // slo-observability.sli-. + return `${SLO_INDEX_TEMPLATE_NAME}-v${version}.`; } private async areResourcesAlreadyInstalled(): Promise { @@ -87,12 +83,11 @@ export class DefaultResourceInstaller implements ResourceInstaller { let ingestPipelineExists = false; try { - const pipelineName = getSLOIngestPipelineName(this.spaceId); - const pipeline = await this.esClient.ingest.getPipeline({ id: pipelineName }); + const pipeline = await this.esClient.ingest.getPipeline({ id: SLO_INGEST_PIPELINE_NAME }); ingestPipelineExists = // @ts-ignore _meta is not defined on the type - pipeline && pipeline[pipelineName]._meta.version === SLO_RESOURCES_VERSION; + pipeline && pipeline[SLO_INGEST_PIPELINE_NAME]._meta.version === SLO_RESOURCES_VERSION; } catch (err) { return false; } diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_duration.test.ts.snap b/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_duration.test.ts.snap index 239c3c93503b9..7b7f49061fd57 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_duration.test.ts.snap +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_duration.test.ts.snap @@ -20,8 +20,8 @@ Object { "version": 1, }, "dest": Object { - "index": "slo-observability.sli-v1-my-namespace", - "pipeline": "slo-observability.sli.monthly-my-namespace", + "index": "slo-observability.sli-v1", + "pipeline": "slo-observability.sli.monthly", }, "frequency": "1m", "pivot": Object { diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_error_rate.test.ts.snap b/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_error_rate.test.ts.snap index 1fdaec28f8977..8b73f76a8082d 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_error_rate.test.ts.snap +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/__snapshots__/apm_transaction_error_rate.test.ts.snap @@ -20,8 +20,8 @@ Object { "version": 1, }, "dest": Object { - "index": "slo-observability.sli-v1-my-namespace", - "pipeline": "slo-observability.sli.monthly-my-namespace", + "index": "slo-observability.sli-v1", + "pipeline": "slo-observability.sli.monthly", }, "frequency": "1m", "pivot": Object { diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.test.ts b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.test.ts index 1e8fadf365d72..ba984e542619b 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.test.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.test.ts @@ -13,7 +13,7 @@ const generator = new ApmTransactionDurationTransformGenerator(); describe('APM Transaction Duration Transform Generator', () => { it('returns the correct transform params with every specified indicator params', async () => { const anSLO = createSLO(createAPMTransactionDurationIndicator()); - const transform = generator.getTransformParams(anSLO, 'my-namespace'); + const transform = generator.getTransformParams(anSLO); expect(transform).toMatchSnapshot({ transform_id: expect.any(String), @@ -34,7 +34,7 @@ describe('APM Transaction Duration Transform Generator', () => { transaction_type: '*', }) ); - const transform = generator.getTransformParams(anSLO, 'my-namespace'); + const transform = generator.getTransformParams(anSLO); expect(transform.source.query).toMatchSnapshot(); }); diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.ts b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.ts index 4c46421737630..bc45e12abbb30 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_duration.ts @@ -12,8 +12,8 @@ import { } from '@elastic/elasticsearch/lib/api/types'; import { ALL_VALUE } from '../../../types/schema'; import { - getSLODestinationIndexName, - getSLOIngestPipelineName, + SLO_DESTINATION_INDEX_NAME, + SLO_INGEST_PIPELINE_NAME, getSLOTransformId, } from '../../../assets/constants'; import { getSLOTransformTemplate } from '../../../assets/transform_templates/slo_transform_template'; @@ -27,7 +27,7 @@ import { TransformGenerator } from '.'; const APM_SOURCE_INDEX = 'metrics-apm*'; export class ApmTransactionDurationTransformGenerator implements TransformGenerator { - public getTransformParams(slo: SLO, spaceId: string): TransformPutTransformRequest { + public getTransformParams(slo: SLO): TransformPutTransformRequest { if (!apmTransactionDurationSLOSchema.is(slo)) { throw new Error(`Cannot handle SLO of indicator type: ${slo.indicator.type}`); } @@ -35,7 +35,7 @@ export class ApmTransactionDurationTransformGenerator implements TransformGenera return getSLOTransformTemplate( this.buildTransformId(slo), this.buildSource(slo), - this.buildDestination(slo, spaceId), + this.buildDestination(), this.buildGroupBy(), this.buildAggregations(slo) ); @@ -104,10 +104,10 @@ export class ApmTransactionDurationTransformGenerator implements TransformGenera }; } - private buildDestination(slo: APMTransactionDurationSLO, spaceId: string) { + private buildDestination() { return { - pipeline: getSLOIngestPipelineName(spaceId), - index: getSLODestinationIndexName(spaceId), + pipeline: SLO_INGEST_PIPELINE_NAME, + index: SLO_DESTINATION_INDEX_NAME, }; } diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.test.ts b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.test.ts index afa904fa1f8cb..2bc88c576f8c4 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.test.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.test.ts @@ -13,7 +13,7 @@ const generator = new ApmTransactionErrorRateTransformGenerator(); describe('APM Transaction Error Rate Transform Generator', () => { it('returns the correct transform params with every specified indicator params', async () => { const anSLO = createSLO(createAPMTransactionErrorRateIndicator()); - const transform = generator.getTransformParams(anSLO, 'my-namespace'); + const transform = generator.getTransformParams(anSLO); expect(transform).toMatchSnapshot({ transform_id: expect.any(String), @@ -27,7 +27,7 @@ describe('APM Transaction Error Rate Transform Generator', () => { it("uses default values when 'good_status_codes' is not specified", async () => { const anSLO = createSLO(createAPMTransactionErrorRateIndicator({ good_status_codes: [] })); - const transform = generator.getTransformParams(anSLO, 'my-namespace'); + const transform = generator.getTransformParams(anSLO); expect(transform.pivot?.aggregations).toMatchSnapshot(); }); @@ -41,7 +41,7 @@ describe('APM Transaction Error Rate Transform Generator', () => { transaction_type: '*', }) ); - const transform = generator.getTransformParams(anSLO, 'my-namespace'); + const transform = generator.getTransformParams(anSLO); expect(transform.source.query).toMatchSnapshot(); }); diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.ts b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.ts index 6740bee2b707f..23a9a03f6e14c 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/apm_transaction_error_rate.ts @@ -14,8 +14,8 @@ import { ALL_VALUE } from '../../../types/schema'; import { getSLOTransformTemplate } from '../../../assets/transform_templates/slo_transform_template'; import { TransformGenerator } from '.'; import { - getSLODestinationIndexName, - getSLOIngestPipelineName, + SLO_DESTINATION_INDEX_NAME, + SLO_INGEST_PIPELINE_NAME, getSLOTransformId, } from '../../../assets/constants'; import { @@ -29,7 +29,7 @@ const ALLOWED_STATUS_CODES = ['2xx', '3xx', '4xx', '5xx']; const DEFAULT_GOOD_STATUS_CODES = ['2xx', '3xx', '4xx']; export class ApmTransactionErrorRateTransformGenerator implements TransformGenerator { - public getTransformParams(slo: SLO, spaceId: string): TransformPutTransformRequest { + public getTransformParams(slo: SLO): TransformPutTransformRequest { if (!apmTransactionErrorRateSLOSchema.is(slo)) { throw new Error(`Cannot handle SLO of indicator type: ${slo.indicator.type}`); } @@ -37,7 +37,7 @@ export class ApmTransactionErrorRateTransformGenerator implements TransformGener return getSLOTransformTemplate( this.buildTransformId(slo), this.buildSource(slo), - this.buildDestination(slo, spaceId), + this.buildDestination(), this.buildGroupBy(), this.buildAggregations(slo) ); @@ -106,10 +106,10 @@ export class ApmTransactionErrorRateTransformGenerator implements TransformGener }; } - private buildDestination(slo: APMTransactionErrorRateSLO, spaceId: string) { + private buildDestination() { return { - pipeline: getSLOIngestPipelineName(spaceId), - index: getSLODestinationIndexName(spaceId), + pipeline: SLO_INGEST_PIPELINE_NAME, + index: SLO_DESTINATION_INDEX_NAME, }; } diff --git a/x-pack/plugins/observability/server/services/slo/transform_generators/transform_generator.ts b/x-pack/plugins/observability/server/services/slo/transform_generators/transform_generator.ts index 21a917ea1af6d..3965e809373c8 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_generators/transform_generator.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_generators/transform_generator.ts @@ -9,5 +9,5 @@ import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/typ import { SLO } from '../../../types/models'; export interface TransformGenerator { - getTransformParams(slo: SLO, spaceId: string): TransformPutTransformRequest; + getTransformParams(slo: SLO): TransformPutTransformRequest; } diff --git a/x-pack/plugins/observability/server/services/slo/transform_manager.test.ts b/x-pack/plugins/observability/server/services/slo/transform_manager.test.ts index 1badb6b08e49f..434e6841ff0e9 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_manager.test.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_manager.test.ts @@ -23,8 +23,6 @@ import { import { SLO, SLITypes } from '../../types/models'; import { createAPMTransactionErrorRateIndicator, createSLO } from './fixtures/slo'; -const SPACE_ID = 'space-id'; - describe('TransformManager', () => { let esClientMock: ElasticsearchClientMock; let loggerMock: jest.Mocked; @@ -41,7 +39,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_duration': new DummyTransformGenerator(), }; - const service = new DefaultTransformManager(generators, esClientMock, loggerMock, SPACE_ID); + const service = new DefaultTransformManager(generators, esClientMock, loggerMock); await expect( service.install( @@ -63,12 +61,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_duration': new FailTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); await expect( transformManager.install( @@ -92,12 +85,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_error_rate': new ApmTransactionErrorRateTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); const slo = createSLO(createAPMTransactionErrorRateIndicator()); const transformId = await transformManager.install(slo); @@ -113,12 +101,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_error_rate': new ApmTransactionErrorRateTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); await transformManager.start('slo-transform-id'); @@ -132,12 +115,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_error_rate': new ApmTransactionErrorRateTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); await transformManager.stop('slo-transform-id'); @@ -151,12 +129,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_error_rate': new ApmTransactionErrorRateTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); await transformManager.uninstall('slo-transform-id'); @@ -171,12 +144,7 @@ describe('TransformManager', () => { const generators: Record = { 'slo.apm.transaction_error_rate': new ApmTransactionErrorRateTransformGenerator(), }; - const transformManager = new DefaultTransformManager( - generators, - esClientMock, - loggerMock, - SPACE_ID - ); + const transformManager = new DefaultTransformManager(generators, esClientMock, loggerMock); await transformManager.uninstall('slo-transform-id'); diff --git a/x-pack/plugins/observability/server/services/slo/transform_manager.ts b/x-pack/plugins/observability/server/services/slo/transform_manager.ts index ab7799a4a00c6..154660fccaf9f 100644 --- a/x-pack/plugins/observability/server/services/slo/transform_manager.ts +++ b/x-pack/plugins/observability/server/services/slo/transform_manager.ts @@ -24,8 +24,7 @@ export class DefaultTransformManager implements TransformManager { constructor( private generators: Record, private esClient: ElasticsearchClient, - private logger: Logger, - private spaceId: string + private logger: Logger ) {} async install(slo: SLO): Promise { @@ -35,7 +34,7 @@ export class DefaultTransformManager implements TransformManager { throw new Error(`Unsupported SLO type: ${slo.indicator.type}`); } - const transformParams = generator.getTransformParams(slo, this.spaceId); + const transformParams = generator.getTransformParams(slo); try { await retryTransientEsErrors(() => this.esClient.transform.putTransform(transformParams), { logger: this.logger, diff --git a/x-pack/plugins/observability/server/types/rest_specs/slo.ts b/x-pack/plugins/observability/server/types/rest_specs/slo.ts index dec07a5d4174f..7ee912cfc3303 100644 --- a/x-pack/plugins/observability/server/types/rest_specs/slo.ts +++ b/x-pack/plugins/observability/server/types/rest_specs/slo.ts @@ -8,17 +8,8 @@ import * as t from 'io-ts'; import { commonSLOSchema } from '../schema'; -const createSLOBodySchema = t.intersection([ - commonSLOSchema, - t.partial({ - settings: t.partial({ - destination_index: t.string, - }), - }), -]); - const createSLOParamsSchema = t.type({ - body: createSLOBodySchema, + body: commonSLOSchema, }); const createSLOResponseSchema = t.type({ @@ -31,8 +22,17 @@ const deleteSLOParamsSchema = t.type({ }), }); -type CreateSLOParams = t.TypeOf; +const getSLOParamsSchema = t.type({ + path: t.type({ + id: t.string, + }), +}); + +const getSLOResponseSchema = t.intersection([t.type({ id: t.string }), commonSLOSchema]); + +type CreateSLOParams = t.TypeOf; type CreateSLOResponse = t.TypeOf; +type GetSLOResponse = t.TypeOf; -export { createSLOParamsSchema, deleteSLOParamsSchema }; -export type { CreateSLOParams, CreateSLOResponse }; +export { createSLOParamsSchema, deleteSLOParamsSchema, getSLOParamsSchema }; +export type { CreateSLOParams, CreateSLOResponse, GetSLOResponse }; diff --git a/x-pack/plugins/observability/server/ui_settings.ts b/x-pack/plugins/observability/server/ui_settings.ts index 69e7f0ba51af6..a5b111569e311 100644 --- a/x-pack/plugins/observability/server/ui_settings.ts +++ b/x-pack/plugins/observability/server/ui_settings.ts @@ -29,11 +29,16 @@ import { const technicalPreviewLabel = i18n.translate( 'xpack.observability.uiSettings.technicalPreviewLabel', - { - defaultMessage: 'technical preview', - } + { defaultMessage: 'technical preview' } ); +function feedbackLink({ href }: { href: string }) { + return `${i18n.translate( + 'xpack.observability.uiSettings.giveFeedBackLabel', + { defaultMessage: 'Give feedback' } + )}`; +} + type UiSettings = UiSettingsParams & { showInLabs?: boolean }; /** @@ -167,12 +172,7 @@ export const uiSettings: Record = { '{technicalPreviewLabel} Enable the Service groups feature on APM UI. {feedbackLink}.', values: { technicalPreviewLabel: `[${technicalPreviewLabel}]`, - feedbackLink: - '' + - i18n.translate('xpack.observability.enableServiceGroups.feedbackLinkText', { - defaultMessage: 'Give feedback', - }) + - '', + feedbackLink: feedbackLink({ href: 'https://ela.st/feedback-service-groups' }), }, }), schema: schema.boolean(), @@ -206,15 +206,7 @@ export const uiSettings: Record = { '{technicalPreviewLabel} Default APM Service Inventory page sort (for Services without Machine Learning applied) to sort by Service Name. {feedbackLink}.', values: { technicalPreviewLabel: `[${technicalPreviewLabel}]`, - feedbackLink: - '' + - i18n.translate( - 'xpack.observability.apmServiceInventoryOptimizedSorting.feedbackLinkText', - { - defaultMessage: 'Give feedback', - } - ) + - '', + feedbackLink: feedbackLink({ href: 'https://ela.st/feedback-apm-page-performance' }), }, } ), @@ -245,12 +237,7 @@ export const uiSettings: Record = { '{technicalPreviewLabel} Enable the APM Trace Explorer feature, that allows you to search and inspect traces with KQL or EQL. {feedbackLink}.', values: { technicalPreviewLabel: `[${technicalPreviewLabel}]`, - feedbackLink: - '' + - i18n.translate('xpack.observability.apmTraceExplorerTabDescription.feedbackLinkText', { - defaultMessage: 'Give feedback', - }) + - '', + feedbackLink: feedbackLink({ href: 'https://ela.st/feedback-trace-explorer' }), }, }), schema: schema.boolean(), @@ -269,12 +256,7 @@ export const uiSettings: Record = { '{technicalPreviewLabel} Enable the APM Operations Breakdown feature, that displays aggregates for backend operations. {feedbackLink}.', values: { technicalPreviewLabel: `[${technicalPreviewLabel}]`, - feedbackLink: - '' + - i18n.translate('xpack.observability.apmOperationsBreakdownDescription.feedbackLinkText', { - defaultMessage: 'Give feedback', - }) + - '', + feedbackLink: feedbackLink({ href: 'https://ela.st/feedback-operations-breakdown' }), }, }), schema: schema.boolean(), @@ -318,12 +300,7 @@ export const uiSettings: Record = { '{technicalPreviewLabel} Display Amazon Lambda metrics in the service metrics tab. {feedbackLink}', values: { technicalPreviewLabel: `[${technicalPreviewLabel}]`, - feedbackLink: - '' + - i18n.translate('xpack.observability.awsLambdaDescription', { - defaultMessage: 'Send feedback', - }) + - '', + feedbackLink: feedbackLink({ href: 'https://ela.st/feedback-aws-lambda' }), }, }), schema: schema.boolean(), diff --git a/x-pack/plugins/osquery/cypress/e2e/all/alerts.cy.ts b/x-pack/plugins/osquery/cypress/e2e/all/alerts.cy.ts index e5c6b5013b138..34d04289ad676 100644 --- a/x-pack/plugins/osquery/cypress/e2e/all/alerts.cy.ts +++ b/x-pack/plugins/osquery/cypress/e2e/all/alerts.cy.ts @@ -8,7 +8,6 @@ import { ArchiverMethod, runKbnArchiverScript } from '../../tasks/archiver'; import { login } from '../../tasks/login'; import { - checkResults, findAndClickButton, findFormFieldByRowsLabelAndType, inputQuery, @@ -59,6 +58,28 @@ describe('Alert Event Details', () => { cy.getBySel('ruleSwitch').should('have.attr', 'aria-checked', 'true'); }); + it('enables to add detection action with osquery', () => { + cy.visit('/app/security/rules'); + cy.contains(RULE_NAME).click(); + cy.contains('Edit rule settings').click(); + cy.getBySel('edit-rule-actions-tab').wait(500).click(); + cy.contains('Perform no actions').get('select').select('On each rule execution'); + cy.contains('Response actions are run on each rule execution'); + cy.getBySel('.osquery-ResponseActionTypeSelectOption').click(); + cy.get(LIVE_QUERY_EDITOR); + cy.contains('Save changes').click(); + cy.contains('Query is a required field'); + inputQuery('select * from uptime'); + cy.wait(1000); // wait for the validation to trigger - cypress is way faster than users ;) + + // getSavedQueriesDropdown().type(`users{downArrow}{enter}`); + cy.contains('Save changes').click(); + cy.contains(`${RULE_NAME} was saved`).should('exist'); + cy.contains('Edit rule settings').click(); + cy.getBySel('edit-rule-actions-tab').wait(500).click(); + cy.contains('select * from uptime'); + }); + it('should be able to run live query and add to timeline (-depending on the previous test)', () => { const TIMELINE_NAME = 'Untitled timeline'; cy.visit('/app/security/alerts'); @@ -94,38 +115,20 @@ describe('Alert Event Details', () => { cy.contains('Cancel').click(); cy.contains(TIMELINE_NAME).click(); cy.getBySel('draggableWrapperKeyboardHandler').contains('action_id: "'); - }); - it('enables to add detection action with osquery', () => { - cy.visit('/app/security/rules'); - cy.contains(RULE_NAME).click(); - cy.contains('Edit rule settings').click(); - cy.getBySel('edit-rule-actions-tab').wait(500).click(); - cy.contains('Perform no actions').get('select').select('On each rule execution'); - cy.contains('Response actions are run on each rule execution'); - cy.getBySel('.osquery-ResponseActionTypeSelectOption').click(); - cy.get(LIVE_QUERY_EDITOR); - cy.contains('Save changes').click(); - cy.contains('Query is a required field'); - inputQuery('select * from uptime'); - cy.wait(1000); // wait for the validation to trigger - cypress is way faster than users ;) - - // getSavedQueriesDropdown().type(`users{downArrow}{enter}`); - cy.contains('Save changes').click(); - cy.contains(`${RULE_NAME} was saved`).should('exist'); - cy.contains('Edit rule settings').click(); - cy.getBySel('edit-rule-actions-tab').wait(500).click(); - cy.contains('select * from uptime'); + // timeline unsaved changes modal + cy.visit('/app/osquery'); + closeModalIfVisible(); }); // TODO think on how to get these actions triggered faster (because now they are not triggered during the test). - it.skip('sees osquery results from last action', () => { - cy.visit('/app/security/alerts'); - cy.getBySel('header-page-title').contains('Alerts').should('exist'); - cy.getBySel('expand-event').first().click({ force: true }); - cy.contains('Osquery Results').click(); - cy.getBySel('osquery-results').should('exist'); - cy.contains('select * from uptime'); - cy.getBySel('osqueryResultsTable').within(() => { - checkResults(); - }); - }); + // it.skip('sees osquery results from last action', () => { + // cy.visit('/app/security/alerts'); + // cy.getBySel('header-page-title').contains('Alerts').should('exist'); + // cy.getBySel('expand-event').first().click({ force: true }); + // cy.contains('Osquery Results').click(); + // cy.getBySel('osquery-results').should('exist'); + // cy.contains('select * from uptime'); + // cy.getBySel('osqueryResultsTable').within(() => { + // checkResults(); + // }); + // }); }); diff --git a/x-pack/plugins/osquery/cypress/integration/all/cases.spec.ts b/x-pack/plugins/osquery/cypress/e2e/all/cases.cy.ts similarity index 96% rename from x-pack/plugins/osquery/cypress/integration/all/cases.spec.ts rename to x-pack/plugins/osquery/cypress/e2e/all/cases.cy.ts index cb16dd1dfb8fe..ce586e4d49943 100644 --- a/x-pack/plugins/osquery/cypress/integration/all/cases.spec.ts +++ b/x-pack/plugins/osquery/cypress/e2e/all/cases.cy.ts @@ -35,7 +35,7 @@ describe('Add to Cases', () => { cy.contains('Test Obs case').click(); checkResults(); cy.contains('attached Osquery results'); - cy.contains('SELECT * FROM users;'); + cy.contains('select * from uptime;'); cy.contains('View in Discover').should('exist'); cy.contains('View in Lens').should('exist'); cy.contains('Add to Case').should('not.exist'); @@ -66,7 +66,7 @@ describe('Add to Cases', () => { cy.contains('Test Security Case').click(); checkResults(); cy.contains('attached Osquery results'); - cy.contains('SELECT * FROM users;'); + cy.contains('select * from uptime;'); cy.contains('View in Discover').should('exist'); cy.contains('View in Lens').should('exist'); cy.contains('Add to Case').should('not.exist'); diff --git a/x-pack/plugins/osquery/kibana.json b/x-pack/plugins/osquery/kibana.json index 6d956fdce9fe9..63e7718368ce1 100644 --- a/x-pack/plugins/osquery/kibana.json +++ b/x-pack/plugins/osquery/kibana.json @@ -12,6 +12,7 @@ "requiredPlugins": [ "actions", "data", + "licensing", "dataViews", "discover", "features", diff --git a/x-pack/plugins/osquery/public/cases/add_to_cases.tsx b/x-pack/plugins/osquery/public/cases/add_to_cases.tsx new file mode 100644 index 0000000000000..bc46a76edf361 --- /dev/null +++ b/x-pack/plugins/osquery/public/cases/add_to_cases.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { useKibana } from '../common/lib/kibana'; +import type { AddToCaseButtonProps } from './add_to_cases_button'; +import { AddToCaseButton } from './add_to_cases_button'; + +const CASES_OWNER: string[] = []; + +export const AddToCaseWrapper: React.FC = React.memo((props) => { + const { cases } = useKibana().services; + const casePermissions = cases.helpers.canUseCases(); + const CasesContext = cases.ui.getCasesContext(); + + return ( + + {' '} + + ); +}); + +AddToCaseWrapper.displayName = 'AddToCaseWrapper'; diff --git a/x-pack/plugins/osquery/public/cases/add_to_cases_button.tsx b/x-pack/plugins/osquery/public/cases/add_to_cases_button.tsx index 9f2df87f35615..7124ebd955490 100644 --- a/x-pack/plugins/osquery/public/cases/add_to_cases_button.tsx +++ b/x-pack/plugins/osquery/public/cases/add_to_cases_button.tsx @@ -19,7 +19,7 @@ const ADD_TO_CASE = i18n.translate( } ); -interface IProps { +export interface AddToCaseButtonProps { queryId: string; agentIds?: string[]; actionId: string; @@ -28,7 +28,7 @@ interface IProps { iconProps?: Record; } -export const AddToCaseButton: React.FC = ({ +export const AddToCaseButton: React.FC = ({ actionId, agentIds = [], queryId = '', diff --git a/x-pack/plugins/osquery/public/discover/pack_view_in_discover.tsx b/x-pack/plugins/osquery/public/discover/pack_view_in_discover.tsx new file mode 100644 index 0000000000000..c6506126c83fe --- /dev/null +++ b/x-pack/plugins/osquery/public/discover/pack_view_in_discover.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import moment from 'moment-timezone'; +import { usePackQueryLastResults } from '../packs/use_pack_query_last_results'; +import { ViewResultsActionButtonType } from '../live_queries/form/pack_queries_status_table'; +import { ViewResultsInDiscoverAction } from './view_results_in_discover'; + +interface PackViewInActionProps { + item: { + id: string; + interval: number; + action_id?: string; + agents: string[]; + }; + actionId?: string; +} +const PackViewInDiscoverActionComponent: React.FC = ({ item }) => { + const { action_id: actionId, agents: agentIds, interval } = item; + const { data: lastResultsData } = usePackQueryLastResults({ + actionId, + interval, + }); + + const startDate = lastResultsData?.['@timestamp'] + ? moment(lastResultsData?.['@timestamp'][0]).subtract(interval, 'seconds').toISOString() + : `now-${interval}s`; + const endDate = lastResultsData?.['@timestamp'] + ? moment(lastResultsData?.['@timestamp'][0]).toISOString() + : 'now'; + + return ( + + ); +}; + +export const PackViewInDiscoverAction = React.memo(PackViewInDiscoverActionComponent); diff --git a/x-pack/plugins/osquery/public/discover/view_results_in_discover.tsx b/x-pack/plugins/osquery/public/discover/view_results_in_discover.tsx new file mode 100644 index 0000000000000..2106f11b89220 --- /dev/null +++ b/x-pack/plugins/osquery/public/discover/view_results_in_discover.tsx @@ -0,0 +1,141 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useEffect, useState } from 'react'; +import { EuiButtonEmpty, EuiButtonIcon, EuiToolTip } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FilterStateStore } from '@kbn/es-query'; +import { useKibana } from '../common/lib/kibana'; +import { useLogsDataView } from '../common/hooks/use_logs_data_view'; +import { ViewResultsActionButtonType } from '../live_queries/form/pack_queries_status_table'; + +interface ViewResultsInDiscoverActionProps { + actionId?: string; + agentIds?: string[]; + buttonType: ViewResultsActionButtonType; + endDate?: string; + startDate?: string; + mode?: string; +} + +const ViewResultsInDiscoverActionComponent: React.FC = ({ + actionId, + agentIds, + buttonType, + endDate, + startDate, +}) => { + const { discover, application } = useKibana().services; + const locator = discover?.locator; + const discoverPermissions = application.capabilities.discover; + const { data: logsDataView } = useLogsDataView({ skip: !actionId }); + + const [discoverUrl, setDiscoverUrl] = useState(''); + + useEffect(() => { + const getDiscoverUrl = async () => { + if (!locator || !logsDataView) return; + + const agentIdsQuery = agentIds?.length + ? { + bool: { + minimum_should_match: 1, + should: agentIds.map((agentId) => ({ match_phrase: { 'agent.id': agentId } })), + }, + } + : null; + + const newUrl = await locator.getUrl({ + indexPatternId: logsDataView.id, + filters: [ + { + meta: { + index: logsDataView.id, + alias: null, + negate: false, + disabled: false, + type: 'phrase', + key: 'action_id', + params: { query: actionId }, + }, + query: { match_phrase: { action_id: actionId } }, + $state: { store: FilterStateStore.APP_STATE }, + }, + ...(agentIdsQuery + ? [ + { + $state: { store: FilterStateStore.APP_STATE }, + meta: { + alias: 'agent IDs', + disabled: false, + index: logsDataView.id, + key: 'query', + negate: false, + type: 'custom', + value: JSON.stringify(agentIdsQuery), + }, + query: agentIdsQuery, + }, + ] + : []), + ], + refreshInterval: { + pause: true, + value: 0, + }, + timeRange: + startDate && endDate + ? { + to: endDate, + from: startDate, + mode: 'absolute', + } + : { + to: 'now', + from: 'now-1d', + mode: 'relative', + }, + }); + setDiscoverUrl(newUrl); + }; + + getDiscoverUrl(); + }, [actionId, agentIds, endDate, startDate, locator, logsDataView]); + + if (!discoverPermissions.show) { + return null; + } + + if (buttonType === ViewResultsActionButtonType.button) { + return ( + + {VIEW_IN_DISCOVER} + + ); + } + + return ( + + + + ); +}; + +const VIEW_IN_DISCOVER = i18n.translate( + 'xpack.osquery.pack.queriesTable.viewDiscoverResultsActionAriaLabel', + { + defaultMessage: 'View in Discover', + } +); + +export const ViewResultsInDiscoverAction = React.memo(ViewResultsInDiscoverActionComponent); diff --git a/x-pack/plugins/osquery/public/form/results_type_field.tsx b/x-pack/plugins/osquery/public/form/results_type_field.tsx index 55bbe69397f97..ccc1961259c38 100644 --- a/x-pack/plugins/osquery/public/form/results_type_field.tsx +++ b/x-pack/plugins/osquery/public/form/results_type_field.tsx @@ -34,7 +34,7 @@ const DIFFERENTIAL_OPTION = { inputDisplay: ( ), }; diff --git a/x-pack/plugins/osquery/public/lens/pack_view_in_lens.tsx b/x-pack/plugins/osquery/public/lens/pack_view_in_lens.tsx new file mode 100644 index 0000000000000..6e1cac3eda86f --- /dev/null +++ b/x-pack/plugins/osquery/public/lens/pack_view_in_lens.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import moment from 'moment-timezone'; +import { usePackQueryLastResults } from '../packs/use_pack_query_last_results'; +import { ViewResultsActionButtonType } from '../live_queries/form/pack_queries_status_table'; +import { ViewResultsInLensAction } from './view_results_in_lens'; + +interface PackViewInActionProps { + item: { + id: string; + interval: number; + action_id?: string; + agents: string[]; + }; + actionId?: string; +} +const PackViewInLensActionComponent: React.FC = ({ item }) => { + const { action_id: actionId, agents: agentIds, interval } = item; + const { data: lastResultsData } = usePackQueryLastResults({ + actionId, + interval, + }); + + const startDate = lastResultsData?.['@timestamp'] + ? moment(lastResultsData?.['@timestamp'][0]).subtract(interval, 'seconds').toISOString() + : `now-${interval}s`; + const endDate = lastResultsData?.['@timestamp'] + ? moment(lastResultsData?.['@timestamp'][0]).toISOString() + : 'now'; + + return ( + + ); +}; + +export const PackViewInLensAction = React.memo(PackViewInLensActionComponent); diff --git a/x-pack/plugins/osquery/public/lens/view_results_in_lens.tsx b/x-pack/plugins/osquery/public/lens/view_results_in_lens.tsx new file mode 100644 index 0000000000000..080c078f6a290 --- /dev/null +++ b/x-pack/plugins/osquery/public/lens/view_results_in_lens.tsx @@ -0,0 +1,234 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback, useMemo } from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiButtonEmpty, EuiButtonIcon, EuiToolTip } from '@elastic/eui'; +import type { + PersistedIndexPatternLayer, + PieVisualizationState, + TermsIndexPatternColumn, + TypedLensByValueInput, +} from '@kbn/lens-plugin/public'; +import { DOCUMENT_FIELD_NAME as RECORDS_FIELD } from '@kbn/lens-plugin/common/constants'; +import { FilterStateStore } from '@kbn/es-query'; +import { ViewResultsActionButtonType } from '../live_queries/form/pack_queries_status_table'; +import type { LogsDataView } from '../common/hooks/use_logs_data_view'; +import { useKibana } from '../common/lib/kibana'; +import { useLogsDataView } from '../common/hooks/use_logs_data_view'; + +interface ViewResultsInLensActionProps { + actionId?: string; + agentIds?: string[]; + buttonType: ViewResultsActionButtonType; + endDate?: string; + startDate?: string; + mode?: string; +} + +const ViewResultsInLensActionComponent: React.FC = ({ + actionId, + agentIds, + buttonType, + endDate, + startDate, + mode, +}) => { + const lensService = useKibana().services.lens; + const { data: logsDataView } = useLogsDataView({ skip: !actionId }); + + const handleClick = useCallback( + (event) => { + event.preventDefault(); + + if (logsDataView) { + lensService?.navigateToPrefilledEditor( + { + id: '', + timeRange: { + from: startDate ?? 'now-1d', + to: endDate ?? 'now', + mode: mode ?? (startDate || endDate) ? 'absolute' : 'relative', + }, + attributes: getLensAttributes(logsDataView, actionId, agentIds), + }, + { + openInNewTab: true, + skipAppLeave: true, + } + ); + } + }, + [actionId, agentIds, endDate, lensService, logsDataView, mode, startDate] + ); + + const isDisabled = useMemo(() => !actionId || !logsDataView, [actionId, logsDataView]); + + if (buttonType === ViewResultsActionButtonType.button) { + return ( + + {VIEW_IN_LENS} + + ); + } + + return ( + + + + ); +}; + +function getLensAttributes( + logsDataView: LogsDataView, + actionId?: string, + agentIds?: string[] +): TypedLensByValueInput['attributes'] { + const dataLayer: PersistedIndexPatternLayer = { + columnOrder: ['8690befd-fd69-4246-af4a-dd485d2a3b38', 'ed999e9d-204c-465b-897f-fe1a125b39ed'], + columns: { + '8690befd-fd69-4246-af4a-dd485d2a3b38': { + sourceField: 'type', + isBucketed: true, + dataType: 'string', + scale: 'ordinal', + operationType: 'terms', + label: 'Top values of type', + params: { + otherBucket: true, + size: 5, + missingBucket: false, + orderBy: { + columnId: 'ed999e9d-204c-465b-897f-fe1a125b39ed', + type: 'column', + }, + orderDirection: 'desc', + }, + } as TermsIndexPatternColumn, + 'ed999e9d-204c-465b-897f-fe1a125b39ed': { + sourceField: RECORDS_FIELD, + isBucketed: false, + dataType: 'number', + scale: 'ratio', + operationType: 'count', + label: 'Count of records', + }, + }, + incompleteColumns: {}, + }; + + const xyConfig: PieVisualizationState = { + shape: 'pie', + layers: [ + { + layerType: 'data', + legendDisplay: 'default', + nestedLegend: false, + layerId: 'layer1', + metric: 'ed999e9d-204c-465b-897f-fe1a125b39ed', + numberDisplay: 'percent', + primaryGroups: ['8690befd-fd69-4246-af4a-dd485d2a3b38'], + categoryDisplay: 'default', + }, + ], + }; + + const agentIdsQuery = agentIds?.length + ? { + bool: { + minimum_should_match: 1, + should: agentIds?.map((agentId) => ({ match_phrase: { 'agent.id': agentId } })), + }, + } + : undefined; + + return { + visualizationType: 'lnsPie', + title: `Action ${actionId} results`, + references: [ + { + id: logsDataView.id, + name: 'indexpattern-datasource-current-indexpattern', + type: 'index-pattern', + }, + { + id: logsDataView.id, + name: 'indexpattern-datasource-layer-layer1', + type: 'index-pattern', + }, + { + name: 'filter-index-pattern-0', + id: logsDataView.id, + type: 'index-pattern', + }, + ], + state: { + datasourceStates: { + indexpattern: { + layers: { + layer1: dataLayer, + }, + }, + }, + filters: [ + { + $state: { store: FilterStateStore.APP_STATE }, + meta: { + index: 'filter-index-pattern-0', + negate: false, + alias: null, + disabled: false, + params: { + query: actionId, + }, + type: 'phrase', + key: 'action_id', + }, + query: { + match_phrase: { + action_id: actionId, + }, + }, + }, + ...(agentIdsQuery + ? [ + { + $state: { store: FilterStateStore.APP_STATE }, + meta: { + alias: 'agent IDs', + disabled: false, + index: 'filter-index-pattern-0', + key: 'query', + negate: false, + type: 'custom', + value: JSON.stringify(agentIdsQuery), + }, + query: agentIdsQuery, + }, + ] + : []), + ], + query: { language: 'kuery', query: '' }, + visualization: xyConfig, + }, + }; +} + +const VIEW_IN_LENS = i18n.translate( + 'xpack.osquery.pack.queriesTable.viewLensResultsActionAriaLabel', + { + defaultMessage: 'View in Lens', + } +); + +export const ViewResultsInLensAction = React.memo(ViewResultsInLensActionComponent); diff --git a/x-pack/plugins/osquery/public/live_queries/form/index.tsx b/x-pack/plugins/osquery/public/live_queries/form/index.tsx index 4a6a204cec0b4..b870d1385752f 100644 --- a/x-pack/plugins/osquery/public/live_queries/form/index.tsx +++ b/x-pack/plugins/osquery/public/live_queries/form/index.tsx @@ -12,6 +12,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useForm as useHookForm, FormProvider } from 'react-hook-form'; import { isEmpty, find, pickBy } from 'lodash'; +import { AddToCaseWrapper } from '../../cases/add_to_cases'; import type { AddToTimelinePayload } from '../../timelines/get_add_to_timeline'; import { QueryPackSelectable } from './query_pack_selectable'; import type { SavedQuerySOFormData } from '../../saved_queries/form/use_saved_query_form'; @@ -25,7 +26,6 @@ import type { AgentSelection } from '../../agents/types'; import { LiveQueryQueryField } from './live_query_query_field'; import { AgentsTableField } from './agents_table_field'; import { savedQueryDataSerializer } from '../../saved_queries/form/use_saved_query_form'; -import { AddToCaseButton } from '../../cases/add_to_cases_button'; import { PackFieldWrapper } from '../../shared_components/osquery_response_action_type/pack_field_wrapper'; export interface LiveQueryFormFields { @@ -213,7 +213,7 @@ const LiveQueryFormComponent: React.FC = ({ (payload) => { if (liveQueryActionId) { return ( - ({ match_phrase: { 'agent.id': agentId } })), - }, - } - : undefined; - - return { - visualizationType: 'lnsPie', - title: `Action ${actionId} results`, - references: [ - { - id: logsDataView.id, - name: 'indexpattern-datasource-current-indexpattern', - type: 'index-pattern', - }, - { - id: logsDataView.id, - name: 'indexpattern-datasource-layer-layer1', - type: 'index-pattern', - }, - { - name: 'filter-index-pattern-0', - id: logsDataView.id, - type: 'index-pattern', - }, - ], - state: { - datasourceStates: { - indexpattern: { - layers: { - layer1: dataLayer, - }, - }, - }, - filters: [ - { - $state: { store: FilterStateStore.APP_STATE }, - meta: { - index: 'filter-index-pattern-0', - negate: false, - alias: null, - disabled: false, - params: { - query: actionId, - }, - type: 'phrase', - key: 'action_id', - }, - query: { - match_phrase: { - action_id: actionId, - }, - }, - }, - ...(agentIdsQuery - ? [ - { - $state: { store: FilterStateStore.APP_STATE }, - meta: { - alias: 'agent IDs', - disabled: false, - index: 'filter-index-pattern-0', - key: 'query', - negate: false, - type: 'custom', - value: JSON.stringify(agentIdsQuery), - }, - query: agentIdsQuery, - }, - ] - : []), - ], - query: { language: 'kuery', query: '' }, - visualization: xyConfig, - }, - }; -} - -const ViewResultsInLensActionComponent: React.FC = ({ - actionId, - agentIds, - buttonType, - endDate, - startDate, - mode, -}) => { - const lensService = useKibana().services.lens; - const isLensAvailable = lensService?.canUseEditor(); - const { data: logsDataView } = useLogsDataView({ skip: !actionId }); - - const handleClick = useCallback( - (event) => { - event.preventDefault(); - - if (logsDataView) { - lensService?.navigateToPrefilledEditor( - { - id: '', - timeRange: { - from: startDate ?? 'now-1d', - to: endDate ?? 'now', - mode: mode ?? (startDate || endDate) ? 'absolute' : 'relative', - }, - attributes: getLensAttributes(logsDataView, actionId, agentIds), - }, - { - openInNewTab: true, - skipAppLeave: true, - } - ); - } - }, - [actionId, agentIds, endDate, lensService, logsDataView, mode, startDate] - ); - - const isDisabled = useMemo(() => !actionId || !logsDataView, [actionId, logsDataView]); - - if (!isLensAvailable) { - return null; - } - - if (buttonType === ViewResultsActionButtonType.button) { - return ( - - {VIEW_IN_LENS} - - ); - } - - return ( - - - - ); -}; - -export const ViewResultsInLensAction = React.memo(ViewResultsInLensActionComponent); - -const ViewResultsInDiscoverActionComponent: React.FC = ({ - actionId, - agentIds, - buttonType, - endDate, - startDate, -}) => { - const { discover, application } = useKibana().services; - const locator = discover?.locator; - const discoverPermissions = application.capabilities.discover; - const { data: logsDataView } = useLogsDataView({ skip: !actionId }); - - const [discoverUrl, setDiscoverUrl] = useState(''); - - useEffect(() => { - const getDiscoverUrl = async () => { - if (!locator || !logsDataView) return; - - const agentIdsQuery = agentIds?.length - ? { - bool: { - minimum_should_match: 1, - should: agentIds.map((agentId) => ({ match_phrase: { 'agent.id': agentId } })), - }, - } - : null; - - const newUrl = await locator.getUrl({ - indexPatternId: logsDataView.id, - filters: [ - { - meta: { - index: logsDataView.id, - alias: null, - negate: false, - disabled: false, - type: 'phrase', - key: 'action_id', - params: { query: actionId }, - }, - query: { match_phrase: { action_id: actionId } }, - $state: { store: FilterStateStore.APP_STATE }, - }, - ...(agentIdsQuery - ? [ - { - $state: { store: FilterStateStore.APP_STATE }, - meta: { - alias: 'agent IDs', - disabled: false, - index: logsDataView.id, - key: 'query', - negate: false, - type: 'custom', - value: JSON.stringify(agentIdsQuery), - }, - query: agentIdsQuery, - }, - ] - : []), - ], - refreshInterval: { - pause: true, - value: 0, - }, - timeRange: - startDate && endDate - ? { - to: endDate, - from: startDate, - mode: 'absolute', - } - : { - to: 'now', - from: 'now-1d', - mode: 'relative', - }, - }); - setDiscoverUrl(newUrl); - }; - - getDiscoverUrl(); - }, [actionId, agentIds, endDate, startDate, locator, logsDataView]); - - if (!discoverPermissions.show) { - return null; - } - - if (buttonType === ViewResultsActionButtonType.button) { - return ( - - {VIEW_IN_DISCOVER} - - ); - } - - return ( - - - - ); -}; - -export const ViewResultsInDiscoverAction = React.memo(ViewResultsInDiscoverActionComponent); - interface DocsColumnResultsProps { count?: number; isLive?: boolean; @@ -450,72 +99,6 @@ const AgentsColumnResults: React.FC = ({
); -interface PackViewInActionProps { - item: { - id: string; - interval: number; - action_id?: string; - agents: string[]; - }; - actionId?: string; -} - -const PackViewInDiscoverActionComponent: React.FC = ({ item }) => { - const { action_id: actionId, agents: agentIds, interval } = item; - const { data: lastResultsData } = usePackQueryLastResults({ - actionId, - interval, - }); - - const startDate = lastResultsData?.['@timestamp'] - ? moment(lastResultsData?.['@timestamp'][0]).subtract(interval, 'seconds').toISOString() - : `now-${interval}s`; - const endDate = lastResultsData?.['@timestamp'] - ? moment(lastResultsData?.['@timestamp'][0]).toISOString() - : 'now'; - - return ( - - ); -}; - -const PackViewInDiscoverAction = React.memo(PackViewInDiscoverActionComponent); - -const PackViewInLensActionComponent: React.FC = ({ item }) => { - const { action_id: actionId, agents: agentIds, interval } = item; - const { data: lastResultsData } = usePackQueryLastResults({ - actionId, - interval, - }); - - const startDate = lastResultsData?.['@timestamp'] - ? moment(lastResultsData?.['@timestamp'][0]).subtract(interval, 'seconds').toISOString() - : `now-${interval}s`; - const endDate = lastResultsData?.['@timestamp'] - ? moment(lastResultsData?.['@timestamp'][0]).toISOString() - : 'now'; - - return ( - - ); -}; - -const PackViewInLensAction = React.memo(PackViewInLensActionComponent); - type PackQueryStatusItem = Partial<{ action_id: string; id: string; @@ -542,10 +125,12 @@ interface PackQueriesStatusTableProps { actionId, isIcon, isDisabled, + queryId, }: { actionId?: string; isIcon?: boolean; isDisabled?: boolean; + queryId?: string; }) => ReactElement; showResultsHeader?: boolean; } @@ -562,10 +147,6 @@ const PackQueriesStatusTableComponent: React.FC = ( showResultsHeader, }) => { const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState>({}); - const { cases, timelines, appName } = useKibana().services; - const casePermissions = cases.helpers.canUseCases(); - const CasesContext = cases.ui.getCasesContext(); - const renderIDColumn = useCallback( (id: string) => ( @@ -619,11 +200,15 @@ const PackQueriesStatusTableComponent: React.FC = ( const renderLensResultsAction = useCallback((item) => , []); const handleAddToCase = useCallback( - (payload: { actionId: string; isIcon?: boolean }) => + (payload: { actionId?: string; isIcon?: boolean; queryId: string }) => // eslint-disable-next-line react/display-name () => { if (addToCase) { - return addToCase({ actionId: payload.actionId, isIcon: payload?.isIcon }); + return addToCase({ + actionId: payload.actionId, + isIcon: payload.isIcon, + queryId: payload.queryId, + }); } return <>; @@ -648,7 +233,7 @@ const PackQueriesStatusTableComponent: React.FC = ( agentIds={agentIds} failedAgentsCount={item?.failed ?? 0} addToTimeline={addToTimeline} - addToCase={addToCase && handleAddToCase({ actionId: item.action_id })} + addToCase={addToCase && handleAddToCase({ queryId: item.action_id, actionId })} /> @@ -658,7 +243,7 @@ const PackQueriesStatusTableComponent: React.FC = ( return itemIdToExpandedRowMapValues; }); }, - [startDate, expirationDate, agentIds, addToTimeline, addToCase, handleAddToCase] + [startDate, expirationDate, agentIds, addToTimeline, addToCase, handleAddToCase, actionId] ); const renderToggleResultsAction = useCallback( @@ -677,28 +262,37 @@ const PackQueriesStatusTableComponent: React.FC = ( const getItemId = useCallback((item: PackItem) => get(item, 'id'), []); - const columns = useMemo(() => { - const resultActions = [ - { - render: renderDiscoverResultsAction, - }, - { - render: renderLensResultsAction, - }, - { - available: () => !!addToCase, - render: (item: { action_id: string }) => - addToCase && - addToCase({ actionId: item.action_id, isIcon: true, isDisabled: !item.action_id }), - }, - { - available: () => addToTimeline && timelines && appName === SECURITY_APP_NAME, - render: (item: { action_id: string }) => - addToTimeline && addToTimeline({ query: ['action_id', item.action_id], isIcon: true }), - }, - ]; + const renderResultActions = useCallback( + (row: { action_id: string }) => { + const resultActions = [ + { + render: renderDiscoverResultsAction, + }, + { + render: renderLensResultsAction, + }, + { + render: (item: { action_id: string }) => + addToTimeline && addToTimeline({ query: ['action_id', item.action_id], isIcon: true }), + }, + { + render: (item: { action_id: string }) => + addToCase && + addToCase({ + actionId, + queryId: item.action_id, + isIcon: true, + isDisabled: !item.action_id, + }), + }, + ]; - return [ + return resultActions.map((action) => action.render(row)); + }, + [actionId, addToCase, addToTimeline, renderDiscoverResultsAction, renderLensResultsAction] + ); + const columns = useMemo( + () => [ { field: 'id', name: i18n.translate('xpack.osquery.pack.queriesTable.idColumnTitle', { @@ -734,7 +328,7 @@ const PackQueriesStatusTableComponent: React.FC = ( defaultMessage: 'View results', }), width: '90px', - actions: resultActions, + render: renderResultActions, }, { id: 'actions', @@ -747,21 +341,16 @@ const PackQueriesStatusTableComponent: React.FC = ( }, ], }, - ]; - }, [ - renderDiscoverResultsAction, - renderLensResultsAction, - renderIDColumn, - renderQueryColumn, - renderDocsColumn, - renderAgentsColumn, - renderToggleResultsAction, - addToCase, - addToTimeline, - timelines, - appName, - ]); - + ], + [ + renderIDColumn, + renderQueryColumn, + renderDocsColumn, + renderAgentsColumn, + renderResultActions, + renderToggleResultsAction, + ] + ); const sorting = useMemo( () => ({ sort: { @@ -798,7 +387,7 @@ const PackQueriesStatusTableComponent: React.FC = ( ); return ( - + <> {showResultsHeader && ( )} @@ -811,7 +400,7 @@ const PackQueriesStatusTableComponent: React.FC = ( itemIdToExpandedRowMap={itemIdToExpandedRowMap} isExpandable /> - + ); }; diff --git a/x-pack/plugins/osquery/public/live_queries/form/pack_results_header.tsx b/x-pack/plugins/osquery/public/live_queries/form/pack_results_header.tsx index 854548fdb58e4..b4892a0387e8e 100644 --- a/x-pack/plugins/osquery/public/live_queries/form/pack_results_header.tsx +++ b/x-pack/plugins/osquery/public/live_queries/form/pack_results_header.tsx @@ -35,6 +35,7 @@ const StyledIconsList = styled(EuiFlexItem)` export const PackResultsHeader = ({ actionId, addToCase }: PackResultsHeadersProps) => ( <> + diff --git a/x-pack/plugins/osquery/public/packs/form/index.tsx b/x-pack/plugins/osquery/public/packs/form/index.tsx index 594c539c389cf..ac3892fe9748b 100644 --- a/x-pack/plugins/osquery/public/packs/form/index.tsx +++ b/x-pack/plugins/osquery/public/packs/form/index.tsx @@ -155,7 +155,7 @@ const PackFormComponent: React.FC = ({ - + diff --git a/x-pack/plugins/osquery/public/packs/queries/query_flyout.tsx b/x-pack/plugins/osquery/public/packs/queries/query_flyout.tsx index d709b4f639e6d..65d829e7b7e82 100644 --- a/x-pack/plugins/osquery/public/packs/queries/query_flyout.tsx +++ b/x-pack/plugins/osquery/public/packs/queries/query_flyout.tsx @@ -79,7 +79,7 @@ const QueryFlyoutComponent: React.FC = ({ resetField('version', { defaultValue: savedQuery.version ? [savedQuery.version] : [] }); resetField('interval', { defaultValue: savedQuery.interval ? savedQuery.interval : 3600 }); resetField('snapshot', { defaultValue: savedQuery.snapshot ?? true }); - resetField('removed'); + resetField('removed', { defaultValue: savedQuery.removed }); resetField('ecs_mapping', { defaultValue: savedQuery.ecs_mapping ?? {} }); } }, diff --git a/x-pack/plugins/osquery/public/routes/live_queries/details/index.tsx b/x-pack/plugins/osquery/public/routes/live_queries/details/index.tsx index a4c58074c76e1..bf35a529137f8 100644 --- a/x-pack/plugins/osquery/public/routes/live_queries/details/index.tsx +++ b/x-pack/plugins/osquery/public/routes/live_queries/details/index.tsx @@ -10,13 +10,18 @@ import { FormattedMessage } from '@kbn/i18n-react'; import React, { useCallback, useLayoutEffect, useMemo, useState } from 'react'; import { useParams } from 'react-router-dom'; -import { AddToCaseButton } from '../../../cases/add_to_cases_button'; +import styled from 'styled-components'; +import { AddToCaseWrapper } from '../../../cases/add_to_cases'; import { useRouterNavigate } from '../../../common/lib/kibana'; import { WithHeaderLayout } from '../../../components/layouts'; import { useLiveQueryDetails } from '../../../actions/use_live_query_details'; import { useBreadcrumbs } from '../../../common/hooks/use_breadcrumbs'; import { PackQueriesStatusTable } from '../../../live_queries/form/pack_queries_status_table'; +const StyledTableWrapper = styled(EuiFlexItem)` + padding-left: 10px; +`; + const LiveQueryDetailsPageComponent = () => { const { actionId } = useParams<{ actionId: string }>(); useBreadcrumbs('live_query_details', { liveQueryId: actionId }); @@ -55,7 +60,7 @@ const LiveQueryDetailsPageComponent = () => { }, [data?.status]); const addToCaseButton = useCallback( (payload) => ( - { return ( - + + + ); }; diff --git a/x-pack/plugins/osquery/public/routes/saved_queries/edit/tabs.tsx b/x-pack/plugins/osquery/public/routes/saved_queries/edit/tabs.tsx index 49501bc24b708..f4de8b04cb472 100644 --- a/x-pack/plugins/osquery/public/routes/saved_queries/edit/tabs.tsx +++ b/x-pack/plugins/osquery/public/routes/saved_queries/edit/tabs.tsx @@ -10,13 +10,10 @@ import React, { useMemo } from 'react'; import type { ReactElement } from 'react'; import type { ECSMapping } from '@kbn/osquery-io-ts-types'; -import { useKibana } from '../../../common/lib/kibana'; import type { AddToTimelinePayload } from '../../../timelines/get_add_to_timeline'; import { ResultsTable } from '../../../results/results_table'; import { ActionResultsSummary } from '../../../action_results/action_results_summary'; -const CASES_OWNER: string[] = []; - interface ResultTabsProps { actionId: string; agentIds?: string[]; @@ -38,10 +35,6 @@ const ResultTabsComponent: React.FC = ({ addToTimeline, addToCase, }) => { - const { cases } = useKibana().services; - const casePermissions = cases.helpers.canUseCases(); - const CasesContext = cases.ui.getCasesContext(); - const tabs = useMemo( () => [ { @@ -85,16 +78,14 @@ const ResultTabsComponent: React.FC = ({ ); return ( - - - + ); }; diff --git a/x-pack/plugins/osquery/public/saved_queries/form/use_saved_query_form.tsx b/x-pack/plugins/osquery/public/saved_queries/form/use_saved_query_form.tsx index 3392f2af037c2..76bdd77d17b17 100644 --- a/x-pack/plugins/osquery/public/saved_queries/form/use_saved_query_form.tsx +++ b/x-pack/plugins/osquery/public/saved_queries/form/use_saved_query_form.tsx @@ -72,11 +72,6 @@ export const savedQueryDataSerializer = (payload: SavedQueryFormData): SavedQuer draft.interval = draft.interval + ''; } - if (draft.snapshot) { - delete draft.snapshot; - delete draft.removed; - } - return draft; }); diff --git a/x-pack/plugins/osquery/public/shared_components/osquery_action/index.tsx b/x-pack/plugins/osquery/public/shared_components/osquery_action/index.tsx index 6bb8d6f5a563d..3095428d478dc 100644 --- a/x-pack/plugins/osquery/public/shared_components/osquery_action/index.tsx +++ b/x-pack/plugins/osquery/public/shared_components/osquery_action/index.tsx @@ -6,17 +6,12 @@ */ import { EuiLoadingContent, EuiEmptyPrompt, EuiCode } from '@elastic/eui'; -import React, { useMemo } from 'react'; +import React from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; +import { OsqueryEmptyPrompt, OsqueryNotAvailablePrompt } from '../prompts'; import type { AddToTimelinePayload } from '../../timelines/get_add_to_timeline'; -import { - AGENT_STATUS_ERROR, - EMPTY_PROMPT, - NOT_AVAILABLE, - PERMISSION_DENIED, - SHORT_EMPTY_TITLE, -} from './translations'; +import { AGENT_STATUS_ERROR, PERMISSION_DENIED, SHORT_EMPTY_TITLE } from './translations'; import { useKibana } from '../../common/lib/kibana'; import { LiveQuery } from '../../live_queries'; import { OsqueryIcon } from '../../components/osquery_icon'; @@ -39,22 +34,11 @@ const OsqueryActionComponent: React.FC = ({ }) => { const permissions = useKibana().services.application.capabilities.osquery; - const emptyPrompt = useMemo( - () => ( - } - title={

{SHORT_EMPTY_TITLE}

} - titleSize="xs" - body={

{EMPTY_PROMPT}

} - /> - ), - [] - ); const { osqueryAvailable, agentFetched, isLoading, policyFetched, policyLoading, agentData } = useIsOsqueryAvailable(agentId); if (agentId && agentFetched && !agentData) { - return emptyPrompt; + return ; } if ( @@ -91,14 +75,7 @@ const OsqueryActionComponent: React.FC = ({ } if (agentId && !osqueryAvailable) { - return ( - } - title={

{SHORT_EMPTY_TITLE}

} - titleSize="xs" - body={

{NOT_AVAILABLE}

} - /> - ); + return ; } if (agentId && agentData?.status !== 'online') { diff --git a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.test.tsx b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.test.tsx index e33207a12d907..772df753c8978 100644 --- a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.test.tsx +++ b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.test.tsx @@ -20,7 +20,7 @@ import { DETAILS_ID, DETAILS_QUERY, DETAILS_TIMESTAMP, - mockCasesContext, + getMockedKibanaConfig, } from './test_utils'; jest.mock('../../common/lib/kibana'); @@ -43,34 +43,8 @@ const defaultProps = { queryId: '', }; const mockKibana = (permissionType: unknown = defaultPermissions) => { - useKibanaMock.mockReturnValue({ - services: { - application: { - capabilities: permissionType, - }, - cases: { - helpers: { - canUseCases: jest.fn(), - }, - ui: { - getCasesContext: jest.fn().mockImplementation(() => mockCasesContext), - }, - }, - data: { - dataViews: { - getCanSaveSync: jest.fn(), - hasData: { - hasESData: jest.fn(), - hasUserDataView: jest.fn(), - hasDataView: jest.fn(), - }, - }, - }, - notifications: { - toasts: jest.fn(), - }, - }, - } as unknown as ReturnType); + const mockedKibana = getMockedKibanaConfig(permissionType); + useKibanaMock.mockReturnValue(mockedKibana); }; const renderWithContext = (Element: React.ReactElement) => diff --git a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.tsx b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.tsx index 998de8a15cfca..b0d0691c14f7d 100644 --- a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.tsx +++ b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_result.tsx @@ -6,9 +6,10 @@ */ import { EuiComment, EuiSpacer } from '@elastic/eui'; -import React from 'react'; +import React, { useCallback } from 'react'; import { FormattedRelative } from '@kbn/i18n-react'; +import { AddToCaseWrapper } from '../../cases/add_to_cases'; import type { OsqueryActionResultsProps } from './types'; import { useLiveQueryDetails } from '../../actions/use_live_query_details'; import { ATTACHED_QUERY } from '../../agents/translations'; @@ -22,7 +23,6 @@ interface OsqueryResultProps extends Omit export const OsqueryResult = ({ actionId, - queryId, ruleName, addToTimeline, agentIds, @@ -30,10 +30,22 @@ export const OsqueryResult = ({ }: OsqueryResultProps) => { const { data } = useLiveQueryDetails({ actionId, - // isLive, - // ...(queryId ? { queryIds: [queryId] } : {}), }); + const addToCaseButton = useCallback( + (payload) => ( + + ), + [data?.agents, actionId] + ); + return (
@@ -51,6 +63,7 @@ export const OsqueryResult = ({ expirationDate={data?.expiration} agentIds={agentIds} addToTimeline={addToTimeline} + addToCase={addToCaseButton} /> diff --git a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_results.test.tsx b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_results.test.tsx index 9e2b74e000705..5190d10dc1c7e 100644 --- a/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_results.test.tsx +++ b/x-pack/plugins/osquery/public/shared_components/osquery_results/osquery_results.test.tsx @@ -17,7 +17,7 @@ import * as useAllLiveQueries from '../../actions/use_all_live_queries'; import * as useLiveQueryDetails from '../../actions/use_live_query_details'; import { PERMISSION_DENIED } from '../osquery_action/translations'; import * as privileges from '../../action_results/use_action_privileges'; -import { defaultLiveQueryDetails, DETAILS_QUERY, mockCasesContext } from './test_utils'; +import { defaultLiveQueryDetails, DETAILS_QUERY, getMockedKibanaConfig } from './test_utils'; jest.mock('../../common/lib/kibana'); @@ -49,34 +49,8 @@ const defaultPermissions = { }; const mockKibana = (permissionType: unknown = defaultPermissions) => { - useKibanaMock.mockReturnValue({ - services: { - application: { - capabilities: permissionType, - }, - cases: { - helpers: { - canUseCases: jest.fn(), - }, - ui: { - getCasesContext: jest.fn().mockImplementation(() => mockCasesContext), - }, - }, - data: { - dataViews: { - getCanSaveSync: jest.fn(), - hasData: { - hasESData: jest.fn(), - hasUserDataView: jest.fn(), - hasDataView: jest.fn(), - }, - }, - }, - notifications: { - toasts: jest.fn(), - }, - }, - } as unknown as ReturnType); + const mockedKibana = getMockedKibanaConfig(permissionType); + useKibanaMock.mockReturnValue(mockedKibana); }; const renderWithContext = (Element: React.ReactElement) => diff --git a/x-pack/plugins/osquery/public/shared_components/osquery_results/test_utils.tsx b/x-pack/plugins/osquery/public/shared_components/osquery_results/test_utils.tsx index 4de58a4ed9aad..c1c991becc8ac 100644 --- a/x-pack/plugins/osquery/public/shared_components/osquery_results/test_utils.tsx +++ b/x-pack/plugins/osquery/public/shared_components/osquery_results/test_utils.tsx @@ -6,6 +6,7 @@ */ import React from 'react'; +import type { useKibana } from '../../common/lib/kibana'; export const DETAILS_QUERY = 'select * from uptime'; export const DETAILS_ID = 'test-id'; @@ -38,4 +39,41 @@ export const defaultLiveQueryDetails = { }, } as never; +export const getMockedKibanaConfig = (permissionType: unknown) => + ({ + services: { + application: { + capabilities: permissionType, + }, + cases: { + helpers: { + canUseCases: jest.fn().mockImplementation(() => ({ + read: true, + update: true, + push: true, + })), + }, + ui: { + getCasesContext: jest.fn().mockImplementation(() => mockCasesContext), + }, + hooks: { + getUseCasesAddToExistingCaseModal: jest.fn(), + }, + }, + data: { + dataViews: { + getCanSaveSync: jest.fn(), + hasData: { + hasESData: jest.fn(), + hasUserDataView: jest.fn(), + hasDataView: jest.fn(), + }, + }, + }, + notifications: { + toasts: jest.fn(), + }, + }, + } as unknown as ReturnType); + export const mockCasesContext: React.FC = (props) => <>{props?.children ?? null}; diff --git a/x-pack/plugins/osquery/public/shared_components/prompts.tsx b/x-pack/plugins/osquery/public/shared_components/prompts.tsx new file mode 100644 index 0000000000000..992de7c9ab14b --- /dev/null +++ b/x-pack/plugins/osquery/public/shared_components/prompts.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { EuiEmptyPrompt } from '@elastic/eui'; +import { OsqueryIcon } from '../components/osquery_icon'; +import { EMPTY_PROMPT, NOT_AVAILABLE, SHORT_EMPTY_TITLE } from './osquery_action/translations'; + +export const OsqueryEmptyPrompt = () => ( + } + title={

{SHORT_EMPTY_TITLE}

} + titleSize="xs" + body={

{EMPTY_PROMPT}

} + /> +); + +export const OsqueryNotAvailablePrompt = () => ( + } + title={

{SHORT_EMPTY_TITLE}

} + titleSize="xs" + body={

{NOT_AVAILABLE}

} + /> +); diff --git a/x-pack/plugins/osquery/server/routes/pack/create_pack_route.ts b/x-pack/plugins/osquery/server/routes/pack/create_pack_route.ts index c60c6d476974b..3dda3cdb36b0d 100644 --- a/x-pack/plugins/osquery/server/routes/pack/create_pack_route.ts +++ b/x-pack/plugins/osquery/server/routes/pack/create_pack_route.ts @@ -144,7 +144,10 @@ export const createPackRoute = (router: IRouter, osqueryContext: OsqueryAppConte } set(draft, `inputs[0].config.osquery.value.packs.${packSO.attributes.name}`, { - queries: convertSOQueriesToPack(queries, { removeMultiLines: true }), + queries: convertSOQueriesToPack(queries, { + removeMultiLines: true, + removeResultType: true, + }), }); return draft; diff --git a/x-pack/plugins/osquery/server/routes/pack/update_pack_route.ts b/x-pack/plugins/osquery/server/routes/pack/update_pack_route.ts index c113cbeb36c32..5b0d76131ee28 100644 --- a/x-pack/plugins/osquery/server/routes/pack/update_pack_route.ts +++ b/x-pack/plugins/osquery/server/routes/pack/update_pack_route.ts @@ -285,6 +285,7 @@ export const updatePackRoute = (router: IRouter, osqueryContext: OsqueryAppConte { queries: convertSOQueriesToPack(updatedPackSO.attributes.queries, { removeMultiLines: true, + removeResultType: true, }), } ); @@ -315,7 +316,9 @@ export const updatePackRoute = (router: IRouter, osqueryContext: OsqueryAppConte draft, `inputs[0].config.osquery.value.packs.${updatedPackSO.attributes.name}`, { - queries: updatedPackSO.attributes.queries, + queries: convertSOQueriesToPack(updatedPackSO.attributes.queries, { + removeResultType: true, + }), } ); diff --git a/x-pack/plugins/osquery/server/routes/pack/utils.test.ts b/x-pack/plugins/osquery/server/routes/pack/utils.test.ts index 05aff28073937..3ddb074a6edbd 100644 --- a/x-pack/plugins/osquery/server/routes/pack/utils.test.ts +++ b/x-pack/plugins/osquery/server/routes/pack/utils.test.ts @@ -42,15 +42,45 @@ describe('Pack utils', () => { describe('convertSOQueriesToPack', () => { test('converts to pack with empty ecs_mapping', () => { const convertedQueries = convertSOQueriesToPack(getTestQueries()); - expect(convertedQueries).toStrictEqual(getTestQueries({})); + expect(convertedQueries).toStrictEqual(getTestQueries()); }); test('converts to pack with converting query to single line', () => { const convertedQueries = convertSOQueriesToPack(getTestQueries(), { removeMultiLines: true }); - expect(convertedQueries).toStrictEqual(oneLiner); + expect(convertedQueries).toStrictEqual({ + ...oneLiner, + }); }); test('converts to object with pack names after query.id', () => { const convertedQueries = convertSOQueriesToPack(getTestQueries({ id: 'testId' })); expect(convertedQueries).toStrictEqual(getTestQueries({}, 'testId')); }); + test('converts with results snapshot set false', () => { + const convertedQueries = convertSOQueriesToPack( + getTestQueries({ snapshot: false, removed: true }), + { removeResultType: true } + ); + expect(convertedQueries).toStrictEqual(getTestQueries({ removed: true, snapshot: false })); + }); + test('converts with results snapshot set true and removed false', () => { + const convertedQueries = convertSOQueriesToPack( + getTestQueries({ snapshot: true, removed: true }), + { removeResultType: true } + ); + expect(convertedQueries).toStrictEqual(getTestQueries({})); + }); + test('converts with results snapshot set true but removed false', () => { + const convertedQueries = convertSOQueriesToPack( + getTestQueries({ snapshot: true, removed: false }), + { removeResultType: true } + ); + expect(convertedQueries).toStrictEqual(getTestQueries({})); + }); + test('converts with both results set to false', () => { + const convertedQueries = convertSOQueriesToPack( + getTestQueries({ snapshot: false, removed: false }), + { removeResultType: true } + ); + expect(convertedQueries).toStrictEqual(getTestQueries({ removed: false, snapshot: false })); + }); }); }); diff --git a/x-pack/plugins/osquery/server/routes/pack/utils.ts b/x-pack/plugins/osquery/server/routes/pack/utils.ts index fe1ded84f4466..4342cdb3ead8e 100644 --- a/x-pack/plugins/osquery/server/routes/pack/utils.ts +++ b/x-pack/plugins/osquery/server/routes/pack/utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { isEmpty, pick, reduce } from 'lodash'; +import { isEmpty, pick, reduce, isArray } from 'lodash'; import { DEFAULT_PLATFORM } from '../../../common/constants'; import { removeMultilines } from '../../../common/utils/build_query/remove_multilines'; import { convertECSMappingToArray, convertECSMappingToObject } from '../utils'; @@ -37,18 +37,29 @@ export const convertPackQueriesToSO = (queries) => }> ); -// @ts-expect-error update types -export const convertSOQueriesToPack = (queries, options?: { removeMultiLines?: boolean }) => +export const convertSOQueriesToPack = ( + // @ts-expect-error update types + queries, + options?: { removeMultiLines?: boolean; removeResultType?: boolean } +) => reduce( queries, // eslint-disable-next-line @typescript-eslint/naming-convention - (acc, { id: queryId, ecs_mapping, query, platform, ...rest }, key) => { + (acc, { id: queryId, ecs_mapping, query, platform, removed, snapshot, ...rest }, key) => { + const resultType = !snapshot ? { removed, snapshot } : {}; const index = queryId ? queryId : key; acc[index] = { ...rest, query: options?.removeMultiLines ? removeMultilines(query) : query, - ...(!isEmpty(ecs_mapping) ? { ecs_mapping: convertECSMappingToObject(ecs_mapping) } : {}), + ...(!isEmpty(ecs_mapping) + ? isArray(ecs_mapping) + ? { ecs_mapping: convertECSMappingToObject(ecs_mapping) } + : { ecs_mapping } + : {}), ...(platform === DEFAULT_PLATFORM || platform === undefined ? {} : { platform }), + ...(options?.removeResultType + ? resultType + : { ...(snapshot ? { snapshot } : {}), ...(removed ? { removed } : {}) }), }; return acc; diff --git a/x-pack/plugins/osquery/server/routes/saved_query/create_saved_query_route.ts b/x-pack/plugins/osquery/server/routes/saved_query/create_saved_query_route.ts index 206719927281b..4ad6146328a1c 100644 --- a/x-pack/plugins/osquery/server/routes/saved_query/create_saved_query_route.ts +++ b/x-pack/plugins/osquery/server/routes/saved_query/create_saved_query_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { isEmpty, pickBy, some } from 'lodash'; +import { isEmpty, pickBy, some, isBoolean } from 'lodash'; import type { IRouter } from '@kbn/core/server'; import { PLUGIN_ID } from '../../../common'; import type { CreateSavedQueryRequestSchemaDecoded } from '../../../common/schemas/routes/saved_query/create_saved_query_request_schema'; @@ -76,7 +76,7 @@ export const createSavedQueryRoute = (router: IRouter, osqueryContext: OsqueryAp updated_by: currentUser, updated_at: new Date().toISOString(), }, - (value) => !isEmpty(value) || value === false + (value) => !isEmpty(value) || isBoolean(value) ) ); diff --git a/x-pack/plugins/profiling/common/callercallee.test.ts b/x-pack/plugins/profiling/common/callee.test.ts similarity index 51% rename from x-pack/plugins/profiling/common/callercallee.test.ts rename to x-pack/plugins/profiling/common/callee.test.ts index a249d21623c44..0ae26e6d848e7 100644 --- a/x-pack/plugins/profiling/common/callercallee.test.ts +++ b/x-pack/plugins/profiling/common/callee.test.ts @@ -6,18 +6,19 @@ */ import { sum } from 'lodash'; -import { createCallerCalleeGraph } from './callercallee'; +import { createCalleeTree } from './callee'; import { events, stackTraces, stackFrames, executables } from './__fixtures__/stacktraces'; -describe('Caller-callee operations', () => { +describe('Callee operations', () => { test('1', () => { const totalSamples = sum([...events.values()]); + const totalFrames = sum([...stackTraces.values()].map((trace) => trace.FrameIDs.length)); - const graph = createCallerCalleeGraph(events, stackTraces, stackFrames, executables); + const tree = createCalleeTree(events, stackTraces, stackFrames, executables, totalFrames); - expect(graph.root.Samples).toEqual(totalSamples); - expect(graph.root.CountInclusive).toEqual(totalSamples); - expect(graph.root.CountExclusive).toEqual(0); + expect(tree.Samples[0]).toEqual(totalSamples); + expect(tree.CountInclusive[0]).toEqual(totalSamples); + expect(tree.CountExclusive[0]).toEqual(0); }); }); diff --git a/x-pack/plugins/profiling/common/callee.ts b/x-pack/plugins/profiling/common/callee.ts new file mode 100644 index 0000000000000..63db0640513c3 --- /dev/null +++ b/x-pack/plugins/profiling/common/callee.ts @@ -0,0 +1,193 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import fnv from 'fnv-plus'; + +import { createFrameGroupID, FrameGroupID } from './frame_group'; +import { + createStackFrameMetadata, + emptyExecutable, + emptyStackFrame, + emptyStackTrace, + Executable, + FileID, + getCalleeLabel, + StackFrame, + StackFrameID, + StackFrameMetadata, + StackTrace, + StackTraceID, +} from './profiling'; + +type NodeID = number; + +export interface CalleeTree { + Size: number; + Edges: Array>; + + ID: string[]; + FrameType: number[]; + FrameID: StackFrameID[]; + FileID: FileID[]; + Label: string[]; + + Samples: number[]; + CountInclusive: number[]; + CountExclusive: number[]; +} + +function initCalleeTree(capacity: number): CalleeTree { + const metadata = createStackFrameMetadata(); + const frameGroupID = createFrameGroupID( + metadata.FileID, + metadata.AddressOrLine, + metadata.ExeFileName, + metadata.SourceFilename, + metadata.FunctionName + ); + const tree: CalleeTree = { + Size: 1, + Edges: new Array(capacity), + ID: new Array(capacity), + FrameType: new Array(capacity), + FrameID: new Array(capacity), + FileID: new Array(capacity), + Label: new Array(capacity), + Samples: new Array(capacity), + CountInclusive: new Array(capacity), + CountExclusive: new Array(capacity), + }; + + tree.Edges[0] = new Map(); + + tree.ID[0] = fnv.fast1a64utf(frameGroupID).toString(); + tree.FrameType[0] = metadata.FrameType; + tree.FrameID[0] = metadata.FrameID; + tree.FileID[0] = metadata.FileID; + tree.Label[0] = 'root: Represents 100% of CPU time.'; + tree.Samples[0] = 0; + tree.CountInclusive[0] = 0; + tree.CountExclusive[0] = 0; + + return tree; +} + +function insertNode( + tree: CalleeTree, + parent: NodeID, + metadata: StackFrameMetadata, + frameGroupID: FrameGroupID, + samples: number +) { + const node = tree.Size; + + tree.Edges[parent].set(frameGroupID, node); + tree.Edges[node] = new Map(); + + tree.ID[node] = fnv.fast1a64utf(`${tree.ID[parent]}${frameGroupID}`).toString(); + tree.FrameType[node] = metadata.FrameType; + tree.FrameID[node] = metadata.FrameID; + tree.FileID[node] = metadata.FileID; + tree.Label[node] = getCalleeLabel(metadata); + tree.Samples[node] = samples; + tree.CountInclusive[node] = 0; + tree.CountExclusive[node] = 0; + + tree.Size++; + + return node; +} + +// createCalleeTree creates a tree from the trace results, the number of +// times that the trace has been seen, and the respective metadata. +// +// The resulting data structure contains all of the data, but is not yet in the +// form most easily digestible by others. +export function createCalleeTree( + events: Map, + stackTraces: Map, + stackFrames: Map, + executables: Map, + totalFrames: number +): CalleeTree { + const tree = initCalleeTree(totalFrames); + + const sortedStackTraceIDs = new Array(); + for (const trace of stackTraces.keys()) { + sortedStackTraceIDs.push(trace); + } + sortedStackTraceIDs.sort((t1, t2) => { + return t1.localeCompare(t2); + }); + + // Walk through all traces. Increment the count of the root by the count of + // that trace. Walk "down" the trace (through the callees) and add the count + // of the trace to each callee. + + for (const stackTraceID of sortedStackTraceIDs) { + // The slice of frames is ordered so that the leaf function is at the + // highest index. + + // It is possible that we do not have a stacktrace for an event, + // e.g. when stopping the host agent or on network errors. + const stackTrace = stackTraces.get(stackTraceID) ?? emptyStackTrace; + const lenStackTrace = stackTrace.FrameIDs.length; + const samples = events.get(stackTraceID) ?? 0; + + let currentNode = 0; + tree.Samples[currentNode] += samples; + + for (let i = 0; i < lenStackTrace; i++) { + const frameID = stackTrace.FrameIDs[i]; + const fileID = stackTrace.FileIDs[i]; + const addressOrLine = stackTrace.AddressOrLines[i]; + const frame = stackFrames.get(frameID) ?? emptyStackFrame; + const executable = executables.get(fileID) ?? emptyExecutable; + + const frameGroupID = createFrameGroupID( + fileID, + addressOrLine, + executable.FileName, + frame.FileName, + frame.FunctionName + ); + + let node = tree.Edges[currentNode].get(frameGroupID); + + if (node === undefined) { + const metadata = createStackFrameMetadata({ + FrameID: frameID, + FileID: fileID, + AddressOrLine: addressOrLine, + FrameType: stackTrace.Types[i], + FunctionName: frame.FunctionName, + FunctionOffset: frame.FunctionOffset, + SourceLine: frame.LineNumber, + SourceFilename: frame.FileName, + ExeFileName: executable.FileName, + }); + + node = insertNode(tree, currentNode, metadata, frameGroupID, samples); + } else { + tree.Samples[node] += samples; + } + + tree.CountInclusive[node] += samples; + + if (i === lenStackTrace - 1) { + // Leaf frame: sum up counts for exclusive CPU. + tree.CountExclusive[node] += samples; + } + currentNode = node; + } + } + + tree.CountExclusive[0] = 0; + tree.CountInclusive[0] = tree.Samples[0]; + + return tree; +} diff --git a/x-pack/plugins/profiling/common/callercallee.ts b/x-pack/plugins/profiling/common/callercallee.ts deleted file mode 100644 index 60573306d7f29..0000000000000 --- a/x-pack/plugins/profiling/common/callercallee.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createFrameGroup, createFrameGroupID, FrameGroupID } from './frame_group'; -import { - createStackFrameMetadata, - emptyStackTrace, - Executable, - FileID, - StackFrame, - StackFrameID, - StackFrameMetadata, - StackTrace, - StackTraceID, -} from './profiling'; - -export interface CallerCalleeNode { - Callers: Map; - Callees: Map; - FrameMetadata: StackFrameMetadata; - FrameGroupID: FrameGroupID; - Samples: number; - CountInclusive: number; - CountExclusive: number; -} - -export function createCallerCalleeNode( - frameMetadata: StackFrameMetadata, - frameGroupID: FrameGroupID, - samples: number -): CallerCalleeNode { - return { - Callers: new Map(), - Callees: new Map(), - FrameMetadata: frameMetadata, - FrameGroupID: frameGroupID, - Samples: samples, - CountInclusive: 0, - CountExclusive: 0, - }; -} - -export interface CallerCalleeGraph { - root: CallerCalleeNode; - size: number; -} - -// createCallerCalleeGraph creates a graph in the internal representation -// from a StackFrameMetadata that identifies the "centered" function and -// the trace results that provide traces and the number of times that the -// trace has been seen. -// -// The resulting data structure contains all of the data, but is not yet in the -// form most easily digestible by others. -export function createCallerCalleeGraph( - events: Map, - stackTraces: Map, - stackFrames: Map, - executables: Map -): CallerCalleeGraph { - // Create a root node for the graph - const rootFrame = createStackFrameMetadata(); - const rootFrameGroup = createFrameGroup( - rootFrame.FileID, - rootFrame.AddressOrLine, - rootFrame.ExeFileName, - rootFrame.SourceFilename, - rootFrame.FunctionName - ); - const rootFrameGroupID = createFrameGroupID(rootFrameGroup); - const root = createCallerCalleeNode(rootFrame, rootFrameGroupID, 0); - const graph: CallerCalleeGraph = { root, size: 1 }; - - const sortedStackTraceIDs = new Array(); - for (const trace of stackTraces.keys()) { - sortedStackTraceIDs.push(trace); - } - sortedStackTraceIDs.sort((t1, t2) => { - return t1.localeCompare(t2); - }); - - // Walk through all traces that contain the root. Increment the count of the - // root by the count of that trace. Walk "up" the trace (through the callers) - // and add the count of the trace to each caller. Then walk "down" the trace - // (through the callees) and add the count of the trace to each callee. - - for (const stackTraceID of sortedStackTraceIDs) { - // The slice of frames is ordered so that the leaf function is at the - // highest index. This means that the "first part" of the slice are the - // callers, and the "second part" are the callees. - // - // We currently assume there are no callers. - - // It is possible that we do not have a stacktrace for an event, - // e.g. when stopping the host agent or on network errors. - const stackTrace = stackTraces.get(stackTraceID) ?? emptyStackTrace; - const lenStackTrace = stackTrace.FrameIDs.length; - const samples = events.get(stackTraceID)!; - - let currentNode = root; - root.Samples += samples; - - for (let i = 0; i < lenStackTrace; i++) { - const frameID = stackTrace.FrameIDs[i]; - const fileID = stackTrace.FileIDs[i]; - const addressOrLine = stackTrace.AddressOrLines[i]; - const frame = stackFrames.get(frameID)!; - const executable = executables.get(fileID)!; - - const frameGroup = createFrameGroup( - fileID, - addressOrLine, - executable.FileName, - frame.FileName, - frame.FunctionName - ); - const frameGroupID = createFrameGroupID(frameGroup); - - let node = currentNode.Callees.get(frameGroupID); - - if (node === undefined) { - const callee = createStackFrameMetadata({ - FrameID: frameID, - FileID: fileID, - AddressOrLine: addressOrLine, - FrameType: stackTrace.Types[i], - FunctionName: frame.FunctionName, - FunctionOffset: frame.FunctionOffset, - SourceLine: frame.LineNumber, - SourceFilename: frame.FileName, - ExeFileName: executable.FileName, - }); - - node = createCallerCalleeNode(callee, frameGroupID, samples); - currentNode.Callees.set(frameGroupID, node); - graph.size++; - } else { - node.Samples += samples; - } - - node.CountInclusive += samples; - - if (i === lenStackTrace - 1) { - // Leaf frame: sum up counts for exclusive CPU. - node.CountExclusive += samples; - } - currentNode = node; - } - } - - root.CountExclusive = 0; - root.CountInclusive = root.Samples; - - return graph; -} - -export function sortCallerCalleeNodes( - nodes: Map -): CallerCalleeNode[] { - const sortedNodes = new Array(); - for (const [_, node] of nodes) { - sortedNodes.push(node); - } - return sortedNodes.sort((n1, n2) => { - if (n1.Samples > n2.Samples) { - return -1; - } - if (n1.Samples < n2.Samples) { - return 1; - } - return n1.FrameGroupID.localeCompare(n2.FrameGroupID); - }); -} diff --git a/x-pack/plugins/profiling/common/flamegraph.test.ts b/x-pack/plugins/profiling/common/flamegraph.test.ts new file mode 100644 index 0000000000000..3852d0152bf12 --- /dev/null +++ b/x-pack/plugins/profiling/common/flamegraph.test.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { sum } from 'lodash'; +import { createCalleeTree } from './callee'; +import { createColumnarViewModel, createFlameGraph } from './flamegraph'; + +import { events, stackTraces, stackFrames, executables } from './__fixtures__/stacktraces'; + +describe('Flamegraph operations', () => { + test('1', () => { + const totalSamples = sum([...events.values()]); + const totalFrames = sum([...stackTraces.values()].map((trace) => trace.FrameIDs.length)); + + const tree = createCalleeTree(events, stackTraces, stackFrames, executables, totalFrames); + const graph = createFlameGraph(tree, 60, totalSamples, totalSamples); + + expect(graph.Size).toEqual(totalFrames - 2); + + const viewModel1 = createColumnarViewModel(graph); + + expect(sum(viewModel1.color)).toBeGreaterThan(0); + + const viewModel2 = createColumnarViewModel(graph, false); + + expect(sum(viewModel2.color)).toEqual(0); + }); +}); diff --git a/x-pack/plugins/profiling/common/flamegraph.ts b/x-pack/plugins/profiling/common/flamegraph.ts index 71c4128b01cbb..e392022a18fcf 100644 --- a/x-pack/plugins/profiling/common/flamegraph.ts +++ b/x-pack/plugins/profiling/common/flamegraph.ts @@ -5,37 +5,24 @@ * 2.0. */ -import fnv from 'fnv-plus'; -import { CallerCalleeGraph, sortCallerCalleeNodes } from './callercallee'; -import { getCalleeLabel } from './profiling'; +import { ColumnarViewModel } from '@elastic/charts'; + +import { CalleeTree } from './callee'; + +export interface ElasticFlameGraph { + Size: number; + Edges: number[][]; -interface ColumnarCallerCallee { - Label: string[]; - Value: number[]; - X: number[]; - Y: number[]; - Color: number[]; - CountInclusive: number[]; - CountExclusive: number[]; ID: string[]; + FrameType: number[]; FrameID: string[]; ExecutableID: string[]; -} - -export interface FlameGraph { Label: string[]; - Value: number[]; - Position: number[]; - Size: number[]; - Color: number[]; + + Samples: number[]; CountInclusive: number[]; CountExclusive: number[]; - ID: string[]; - FrameID: string[]; - ExecutableID: string[]; -} -export interface ElasticFlameGraph extends FlameGraph { TotalSeconds: number; TotalTraces: number; SampledTraces: number; @@ -94,110 +81,119 @@ function normalize(n: number, lower: number, upper: number): number { return (n - lower) / (upper - lower); } -// createColumnarCallerCallee flattens the intermediate representation of the diagram -// into a columnar format that is more compact than JSON. This representation will later -// need to be normalized into the response ultimately consumed by the flamegraph. -export function createColumnarCallerCallee(graph: CallerCalleeGraph): ColumnarCallerCallee { - const numCallees = graph.size; - const columnar: ColumnarCallerCallee = { - Label: new Array(numCallees), - Value: new Array(numCallees), - X: new Array(numCallees), - Y: new Array(numCallees), - Color: new Array(numCallees * 4), - CountInclusive: new Array(numCallees), - CountExclusive: new Array(numCallees), - ID: new Array(numCallees), - FrameID: new Array(numCallees), - ExecutableID: new Array(numCallees), +// createFlameGraph encapsulates the tree representation into a serialized form. +export function createFlameGraph( + tree: CalleeTree, + totalSeconds: number, + totalTraces: number, + sampledTraces: number +): ElasticFlameGraph { + const graph: ElasticFlameGraph = { + Size: tree.Size, + Edges: new Array(tree.Size), + + ID: tree.ID.slice(0, tree.Size), + Label: tree.Label.slice(0, tree.Size), + FrameID: tree.FrameID.slice(0, tree.Size), + FrameType: tree.FrameType.slice(0, tree.Size), + ExecutableID: tree.FileID.slice(0, tree.Size), + + Samples: tree.Samples.slice(0, tree.Size), + CountInclusive: tree.CountInclusive.slice(0, tree.Size), + CountExclusive: tree.CountExclusive.slice(0, tree.Size), + + TotalSeconds: totalSeconds, + TotalTraces: totalTraces, + SampledTraces: sampledTraces, }; - const queue = [{ x: 0, depth: 1, node: graph.root, parentID: 'root' }]; - - let idx = 0; - while (queue.length > 0) { - const { x, depth, node, parentID } = queue.pop()!; - - if (x === 0 && depth === 1) { - columnar.Label[idx] = 'root: Represents 100% of CPU time.'; - } else { - columnar.Label[idx] = getCalleeLabel(node.FrameMetadata); + for (let i = 0; i < tree.Size; i++) { + let j = 0; + const nodes = new Array(tree.Edges[i].size); + for (const [, n] of tree.Edges[i]) { + nodes[j] = n; + j++; } - columnar.Value[idx] = node.Samples; - columnar.X[idx] = x; - columnar.Y[idx] = depth; - - const [red, green, blue, alpha] = rgbToRGBA(frameTypeToRGB(node.FrameMetadata.FrameType, x)); - const j = 4 * idx; - columnar.Color[j] = red; - columnar.Color[j + 1] = green; - columnar.Color[j + 2] = blue; - columnar.Color[j + 3] = alpha; + graph.Edges[i] = nodes; + } - columnar.CountInclusive[idx] = node.CountInclusive; - columnar.CountExclusive[idx] = node.CountExclusive; + return graph; +} - const id = fnv.fast1a64utf(`${parentID}${node.FrameGroupID}`).toString(); +// createColumnarViewModel normalizes the columnar representation into a form +// consumed by the flamegraph in the UI. +export function createColumnarViewModel( + flamegraph: ElasticFlameGraph, + assignColors: boolean = true +): ColumnarViewModel { + const numNodes = flamegraph.Size; + const xs = new Float32Array(numNodes); + const ys = new Float32Array(numNodes); - columnar.ID[idx] = id; - columnar.FrameID[idx] = node.FrameMetadata.FrameID; - columnar.ExecutableID[idx] = node.FrameMetadata.FileID; + const queue = [{ x: 0, depth: 1, node: 0 }]; - // For a deterministic result we have to walk the callers / callees in a deterministic - // order. A deterministic result allows deterministic UI views, something that users expect. - const callees = sortCallerCalleeNodes(node.Callees); + while (queue.length > 0) { + const { x, depth, node } = queue.pop()!; + + xs[node] = x; + ys[node] = depth; + + // For a deterministic result we have to walk the callees in a deterministic + // order. A deterministic result allows deterministic UI views, something + // that users expect. + const children = flamegraph.Edges[node].sort((n1, n2) => { + if (flamegraph.Samples[n1] > flamegraph.Samples[n2]) { + return -1; + } + if (flamegraph.Samples[n1] < flamegraph.Samples[n2]) { + return 1; + } + return flamegraph.ID[n1].localeCompare(flamegraph.ID[n2]); + }); let delta = 0; - for (const callee of callees) { - delta += callee.Samples; + for (const child of children) { + delta += flamegraph.Samples[child]; } - for (let i = callees.length - 1; i >= 0; i--) { - delta -= callees[i].Samples; - queue.push({ x: x + delta, depth: depth + 1, node: callees[i], parentID: id }); + for (let i = children.length - 1; i >= 0; i--) { + delta -= flamegraph.Samples[children[i]]; + queue.push({ x: x + delta, depth: depth + 1, node: children[i] }); } - - idx++; } - return columnar; -} + const colors = new Float32Array(numNodes * 4); -// createFlameGraph normalizes the intermediate columnar representation into the -// response ultimately consumed by the flamegraph in the UI. -export function createFlameGraph(columnar: ColumnarCallerCallee): FlameGraph { - const graph: FlameGraph = { - Label: [], - Value: [], - Position: [], - Size: [], - Color: [], - CountInclusive: [], - CountExclusive: [], - ID: [], - FrameID: [], - ExecutableID: [], - }; + if (assignColors) { + for (let i = 0; i < numNodes; i++) { + const rgba = rgbToRGBA(frameTypeToRGB(flamegraph.FrameType[i], xs[i])); + colors.set(rgba, 4 * i); + } + } + + const position = new Float32Array(numNodes * 2); + const maxX = flamegraph.Samples[0]; + const maxY = ys.reduce((max, n) => (n > max ? n : max), 0); - graph.Label = columnar.Label; - graph.Value = columnar.Value; - graph.Color = columnar.Color; - graph.CountInclusive = columnar.CountInclusive; - graph.CountExclusive = columnar.CountExclusive; - graph.ID = columnar.ID; - graph.FrameID = columnar.FrameID; - graph.ExecutableID = columnar.ExecutableID; - - const maxX = columnar.Value[0]; - const maxY = columnar.Y.reduce((max, n) => (n > max ? n : max), 0); - - for (let i = 0; i < columnar.X.length; i++) { - const x = normalize(columnar.X[i], 0, maxX); - const y = normalize(maxY - columnar.Y[i], 0, maxY); - graph.Position.push(x, y); + for (let i = 0; i < numNodes; i++) { + const j = 2 * i; + position[j] = normalize(xs[i], 0, maxX); + position[j + 1] = normalize(maxY - ys[i], 0, maxY); } - graph.Size = graph.Value.map((n) => normalize(n, 0, maxX)); + const size = new Float32Array(numNodes); - return graph; + for (let i = 0; i < numNodes; i++) { + size[i] = normalize(flamegraph.Samples[i], 0, maxX); + } + + return { + label: flamegraph.Label.slice(0, numNodes), + value: Float64Array.from(flamegraph.Samples.slice(0, numNodes)), + color: colors, + position0: position, + position1: position, + size0: size, + size1: size, + } as ColumnarViewModel; } diff --git a/x-pack/plugins/profiling/common/frame_group.test.ts b/x-pack/plugins/profiling/common/frame_group.test.ts index b8dd3c8d03632..15f1e0e4edc7f 100644 --- a/x-pack/plugins/profiling/common/frame_group.test.ts +++ b/x-pack/plugins/profiling/common/frame_group.test.ts @@ -5,40 +5,116 @@ * 2.0. */ -import { createFrameGroup, createFrameGroupID } from './frame_group'; +import { createFrameGroupID } from './frame_group'; -const nonSymbolizedFrameGroups = [ - createFrameGroup('0x0123456789ABCDEF', 102938, '', '', ''), - createFrameGroup('0x0123456789ABCDEF', 1234, '', '', ''), - createFrameGroup('0x0102030405060708', 1234, '', '', ''), +const nonSymbolizedTests = [ + { + params: { + fileID: '0x0123456789ABCDEF', + addressOrLine: 102938, + exeFilename: '', + sourceFilename: '', + functionName: '', + }, + expected: 'empty;0x0123456789ABCDEF;102938', + }, + { + params: { + fileID: '0x0123456789ABCDEF', + addressOrLine: 1234, + exeFilename: 'libpthread', + sourceFilename: '', + functionName: '', + }, + expected: 'empty;0x0123456789ABCDEF;1234', + }, ]; -const elfSymbolizedFrameGroups = [ - createFrameGroup('0x0123456789ABCDEF', 0, 'libc', '', 'strlen()'), - createFrameGroup('0xFEDCBA9876543210', 0, 'libc', '', 'strtok()'), - createFrameGroup('0xFEDCBA9876543210', 0, 'myapp', '', 'main()'), +const elfSymbolizedTests = [ + { + params: { + fileID: '0x0123456789ABCDEF', + addressOrLine: 0, + exeFilename: 'libc', + sourceFilename: '', + functionName: 'strlen()', + }, + expected: 'elf;libc;strlen()', + }, + { + params: { + fileID: '0xFEDCBA9876543210', + addressOrLine: 8888, + exeFilename: 'libc', + sourceFilename: '', + functionName: 'strtok()', + }, + expected: 'elf;libc;strtok()', + }, ]; -const symbolizedFrameGroups = [ - createFrameGroup('', 0, 'chrome', 'strlen()', 'strlen()'), - createFrameGroup('', 0, 'dockerd', 'main()', 'createTask()'), - createFrameGroup('', 0, 'oom_reaper', 'main()', 'crash()'), +const symbolizedTests = [ + { + params: { + fileID: '', + addressOrLine: 0, + exeFilename: 'chrome', + sourceFilename: 'strlen()', + functionName: 'strlen()', + }, + expected: 'full;chrome;strlen();strlen()', + }, + { + params: { + fileID: '', + addressOrLine: 0, + exeFilename: 'oom_reaper', + sourceFilename: 'main()', + functionName: 'crash()', + }, + expected: 'full;oom_reaper;crash();main()', + }, ]; describe('Frame group operations', () => { describe('check serialization for', () => { test('non-symbolized frame', () => { - expect(createFrameGroupID(nonSymbolizedFrameGroups[0])).toEqual( - 'empty;0x0123456789ABCDEF;102938' - ); + for (const test of nonSymbolizedTests) { + const frameGroupID = createFrameGroupID( + test.params.fileID, + test.params.addressOrLine, + test.params.exeFilename, + test.params.sourceFilename, + test.params.functionName + ); + expect(frameGroupID).toEqual(test.expected); + } }); test('non-symbolized ELF frame', () => { - expect(createFrameGroupID(elfSymbolizedFrameGroups[0])).toEqual('elf;libc;strlen()'); + for (const test of elfSymbolizedTests) { + const frameGroupID = createFrameGroupID( + test.params.fileID, + test.params.addressOrLine, + test.params.exeFilename, + test.params.sourceFilename, + test.params.functionName + ); + expect(frameGroupID).toEqual(test.expected); + } }); test('symbolized frame', () => { - expect(createFrameGroupID(symbolizedFrameGroups[0])).toEqual('full;chrome;strlen();strlen()'); + for (const test of symbolizedTests) { + const frameGroupID = createFrameGroupID( + test.params.fileID, + test.params.addressOrLine, + test.params.exeFilename, + test.params.sourceFilename, + test.params.functionName + ); + expect(frameGroupID).toEqual(test.expected); + } }); }); }); diff --git a/x-pack/plugins/profiling/common/frame_group.ts b/x-pack/plugins/profiling/common/frame_group.ts index 5987ecdf2ebdc..30a29fe240e1f 100644 --- a/x-pack/plugins/profiling/common/frame_group.ts +++ b/x-pack/plugins/profiling/common/frame_group.ts @@ -9,86 +9,26 @@ import { StackFrameMetadata } from './profiling'; export type FrameGroupID = string; -enum FrameGroupName { - EMPTY = 'empty', - ELF = 'elf', - FULL = 'full', -} - -interface BaseFrameGroup { - readonly name: FrameGroupName; -} - -interface EmptyFrameGroup extends BaseFrameGroup { - readonly name: FrameGroupName.EMPTY; - readonly fileID: StackFrameMetadata['FileID']; - readonly addressOrLine: StackFrameMetadata['AddressOrLine']; -} - -interface ElfFrameGroup extends BaseFrameGroup { - readonly name: FrameGroupName.ELF; - readonly fileID: StackFrameMetadata['FileID']; - readonly exeFilename: StackFrameMetadata['ExeFileName']; - readonly functionName: StackFrameMetadata['FunctionName']; -} - -interface FullFrameGroup extends BaseFrameGroup { - readonly name: FrameGroupName.FULL; - readonly exeFilename: StackFrameMetadata['ExeFileName']; - readonly functionName: StackFrameMetadata['FunctionName']; - readonly sourceFilename: StackFrameMetadata['SourceFilename']; -} - -export type FrameGroup = EmptyFrameGroup | ElfFrameGroup | FullFrameGroup; - -// createFrameGroup is the "standard" way of grouping frames, by commonly +// createFrameGroupID is the "standard" way of grouping frames, by commonly // shared group identifiers. // // For ELF-symbolized frames, group by FunctionName, ExeFileName and FileID. // For non-symbolized frames, group by FileID and AddressOrLine. // otherwise group by ExeFileName, SourceFilename and FunctionName. -export function createFrameGroup( +export function createFrameGroupID( fileID: StackFrameMetadata['FileID'], addressOrLine: StackFrameMetadata['AddressOrLine'], exeFilename: StackFrameMetadata['ExeFileName'], sourceFilename: StackFrameMetadata['SourceFilename'], functionName: StackFrameMetadata['FunctionName'] -): FrameGroup { +): FrameGroupID { if (functionName === '') { - return { - name: FrameGroupName.EMPTY, - fileID, - addressOrLine, - } as EmptyFrameGroup; + return `empty;${fileID};${addressOrLine}`; } if (sourceFilename === '') { - return { - name: FrameGroupName.ELF, - fileID, - exeFilename, - functionName, - } as ElfFrameGroup; + return `elf;${exeFilename};${functionName}`; } - return { - name: FrameGroupName.FULL, - exeFilename, - functionName, - sourceFilename, - } as FullFrameGroup; -} - -export function createFrameGroupID(frameGroup: FrameGroup): FrameGroupID { - switch (frameGroup.name) { - case FrameGroupName.EMPTY: - return `${frameGroup.name};${frameGroup.fileID};${frameGroup.addressOrLine}`; - break; - case FrameGroupName.ELF: - return `${frameGroup.name};${frameGroup.exeFilename};${frameGroup.functionName}`; - break; - case FrameGroupName.FULL: - return `${frameGroup.name};${frameGroup.exeFilename};${frameGroup.functionName};${frameGroup.sourceFilename}`; - break; - } + return `full;${exeFilename};${functionName};${sourceFilename}`; } diff --git a/x-pack/plugins/profiling/common/functions.ts b/x-pack/plugins/profiling/common/functions.ts index 5ca59163227d1..70aa7cae864d7 100644 --- a/x-pack/plugins/profiling/common/functions.ts +++ b/x-pack/plugins/profiling/common/functions.ts @@ -5,9 +5,11 @@ * 2.0. */ import * as t from 'io-ts'; -import { createFrameGroup, createFrameGroupID, FrameGroupID } from './frame_group'; +import { createFrameGroupID, FrameGroupID } from './frame_group'; import { createStackFrameMetadata, + emptyExecutable, + emptyStackFrame, emptyStackTrace, Executable, FileID, @@ -66,17 +68,16 @@ export function createTopNFunctions( const frameID = stackTrace.FrameIDs[i]; const fileID = stackTrace.FileIDs[i]; const addressOrLine = stackTrace.AddressOrLines[i]; - const frame = stackFrames.get(frameID)!; - const executable = executables.get(fileID)!; + const frame = stackFrames.get(frameID) ?? emptyStackFrame; + const executable = executables.get(fileID) ?? emptyExecutable; - const frameGroup = createFrameGroup( + const frameGroupID = createFrameGroupID( fileID, addressOrLine, executable.FileName, frame.FileName, frame.FunctionName ); - const frameGroupID = createFrameGroupID(frameGroup); let topNFunction = topNFunctions.get(frameGroupID); diff --git a/x-pack/plugins/profiling/common/profiling.ts b/x-pack/plugins/profiling/common/profiling.ts index 8017189280ddd..6779a16774959 100644 --- a/x-pack/plugins/profiling/common/profiling.ts +++ b/x-pack/plugins/profiling/common/profiling.ts @@ -28,18 +28,20 @@ export enum FrameType { JavaScript, } +const frameTypeDescriptions = { + [FrameType.Unsymbolized]: '', + [FrameType.Python]: 'Python', + [FrameType.PHP]: 'PHP', + [FrameType.Native]: 'Native', + [FrameType.Kernel]: 'Kernel', + [FrameType.JVM]: 'JVM/Hotspot', + [FrameType.Ruby]: 'Ruby', + [FrameType.Perl]: 'Perl', + [FrameType.JavaScript]: 'JavaScript', +}; + export function describeFrameType(ft: FrameType): string { - return { - [FrameType.Unsymbolized]: '', - [FrameType.Python]: 'Python', - [FrameType.PHP]: 'PHP', - [FrameType.Native]: 'Native', - [FrameType.Kernel]: 'Kernel', - [FrameType.JVM]: 'JVM/Hotspot', - [FrameType.Ruby]: 'Ruby', - [FrameType.Perl]: 'Perl', - [FrameType.JavaScript]: 'JavaScript', - }[ft]; + return frameTypeDescriptions[ft]; } export interface StackTraceEvent { @@ -69,10 +71,22 @@ export interface StackFrame { SourceType: number; } +export const emptyStackFrame: StackFrame = { + FileName: '', + FunctionName: '', + FunctionOffset: 0, + LineNumber: 0, + SourceType: 0, +}; + export interface Executable { FileName: string; } +export const emptyExecutable: Executable = { + FileName: '', +}; + export interface StackFrameMetadata { // StackTrace.FrameID FrameID: string; @@ -221,8 +235,8 @@ export function groupStackFrameMetadataByStackTrace( const frameID = trace.FrameIDs[i]; const fileID = trace.FileIDs[i]; const addressOrLine = trace.AddressOrLines[i]; - const frame = stackFrames.get(frameID)!; - const executable = executables.get(fileID)!; + const frame = stackFrames.get(frameID) ?? emptyStackFrame; + const executable = executables.get(fileID) ?? emptyExecutable; frameMetadata[i] = createStackFrameMetadata({ FrameID: frameID, diff --git a/x-pack/plugins/profiling/public/components/flamegraph.tsx b/x-pack/plugins/profiling/public/components/flamegraph.tsx index afc241394aafb..9abac27ef9fb2 100644 --- a/x-pack/plugins/profiling/public/components/flamegraph.tsx +++ b/x-pack/plugins/profiling/public/components/flamegraph.tsx @@ -226,9 +226,9 @@ export const FlameGraph: React.FC = ({ exeFileName: highlightedFrame.ExeFileName, sourceFileName: highlightedFrame.SourceFilename, functionName: highlightedFrame.FunctionName, - samples: primaryFlamegraph.Value[highlightedVmIndex], + samples: primaryFlamegraph.Samples[highlightedVmIndex], childSamples: - primaryFlamegraph.Value[highlightedVmIndex] - + primaryFlamegraph.Samples[highlightedVmIndex] - primaryFlamegraph.CountExclusive[highlightedVmIndex], } : undefined; @@ -275,7 +275,7 @@ export const FlameGraph: React.FC = ({ const valueIndex = props.values[0].valueAccessor as number; const label = primaryFlamegraph.Label[valueIndex]; - const samples = primaryFlamegraph.Value[valueIndex]; + const samples = primaryFlamegraph.Samples[valueIndex]; const countInclusive = primaryFlamegraph.CountInclusive[valueIndex]; const countExclusive = primaryFlamegraph.CountExclusive[valueIndex]; const nodeID = primaryFlamegraph.ID[valueIndex]; @@ -291,8 +291,8 @@ export const FlameGraph: React.FC = ({ comparisonCountInclusive={comparisonNode?.CountInclusive} comparisonCountExclusive={comparisonNode?.CountExclusive} totalSamples={totalSamples} - comparisonTotalSamples={comparisonFlamegraph?.Value[0]} - comparisonSamples={comparisonNode?.Value} + comparisonTotalSamples={comparisonFlamegraph?.Samples[0]} + comparisonSamples={comparisonNode?.Samples} /> ); }, diff --git a/x-pack/plugins/profiling/public/utils/get_flamegraph_model/index.ts b/x-pack/plugins/profiling/public/utils/get_flamegraph_model/index.ts index 1402897b966ac..c63a73185d26b 100644 --- a/x-pack/plugins/profiling/public/utils/get_flamegraph_model/index.ts +++ b/x-pack/plugins/profiling/public/utils/get_flamegraph_model/index.ts @@ -4,10 +4,14 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { ColumnarViewModel } from '@elastic/charts'; import d3 from 'd3'; import { sum, uniqueId } from 'lodash'; -import { ElasticFlameGraph, FlameGraphComparisonMode, rgbToRGBA } from '../../../common/flamegraph'; +import { + createColumnarViewModel, + ElasticFlameGraph, + FlameGraphComparisonMode, + rgbToRGBA, +} from '../../../common/flamegraph'; import { getInterpolationValue } from './get_interpolation_value'; const nullColumnarViewModel = { @@ -37,21 +41,19 @@ export function getFlamegraphModel({ }) { const comparisonNodesById: Record< string, - { Value: number; CountInclusive: number; CountExclusive: number } + { Samples: number; CountInclusive: number; CountExclusive: number } > = {}; if (!primaryFlamegraph || !primaryFlamegraph.Label || primaryFlamegraph.Label.length === 0) { return { key: uniqueId(), viewModel: nullColumnarViewModel, comparisonNodesById }; } - let colors: number[] | undefined = primaryFlamegraph.Color; + const viewModel = createColumnarViewModel(primaryFlamegraph, comparisonFlamegraph === undefined); if (comparisonFlamegraph) { - colors = []; - comparisonFlamegraph.ID.forEach((nodeID, index) => { comparisonNodesById[nodeID] = { - Value: comparisonFlamegraph.Value[index], + Samples: comparisonFlamegraph.Samples[index], CountInclusive: comparisonFlamegraph.CountInclusive[index], CountExclusive: comparisonFlamegraph.CountExclusive[index], }; @@ -86,8 +88,8 @@ export function getFlamegraphModel({ : primaryFlamegraph.TotalSeconds / comparisonFlamegraph.TotalSeconds; primaryFlamegraph.ID.forEach((nodeID, index) => { - const samples = primaryFlamegraph.Value[index]; - const comparisonSamples = comparisonNodesById[nodeID]?.Value as number | undefined; + const samples = primaryFlamegraph.Samples[index]; + const comparisonSamples = comparisonNodesById[nodeID]?.Samples as number | undefined; const foreground = comparisonMode === FlameGraphComparisonMode.Absolute ? samples : samples / totalSamples; @@ -110,26 +112,14 @@ export function getFlamegraphModel({ ? positiveChangeInterpolator(interpolationValue) : negativeChangeInterpolator(Math.abs(interpolationValue)); - colors!.push(...rgbToRGBA(Number(nodeColor.replace('#', '0x')))); + const rgba = rgbToRGBA(Number(nodeColor.replace('#', '0x'))); + viewModel.color.set(rgba, 4 * index); }); } - const value = new Float64Array(primaryFlamegraph.Value); - const position = new Float32Array(primaryFlamegraph.Position); - const size = new Float32Array(primaryFlamegraph.Size); - const color = new Float32Array(colors); - return { key: uniqueId(), - viewModel: { - label: primaryFlamegraph.Label, - value, - color, - position0: position, - position1: position, - size0: size, - size1: size, - } as ColumnarViewModel, + viewModel, comparisonNodesById, }; } diff --git a/x-pack/plugins/profiling/server/routes/flamechart.ts b/x-pack/plugins/profiling/server/routes/flamechart.ts index 0f37ed4886412..6d27305a82c69 100644 --- a/x-pack/plugins/profiling/server/routes/flamechart.ts +++ b/x-pack/plugins/profiling/server/routes/flamechart.ts @@ -8,12 +8,8 @@ import { schema } from '@kbn/config-schema'; import { RouteRegisterParameters } from '.'; import { getRoutePaths } from '../../common'; -import { createCallerCalleeGraph } from '../../common/callercallee'; -import { - createColumnarCallerCallee, - createFlameGraph, - ElasticFlameGraph, -} from '../../common/flamegraph'; +import { createCalleeTree } from '../../common/callee'; +import { createFlameGraph } from '../../common/flamegraph'; import { createProfilingEsClient } from '../utils/create_profiling_es_client'; import { withProfilingSpan } from '../utils/with_profiling_span'; import { getClient } from './compat'; @@ -46,55 +42,57 @@ export function registerFlameChartSearchRoute({ router, logger }: RouteRegisterP }); const totalSeconds = timeTo - timeFrom; - const { stackTraces, executables, stackFrames, eventsIndex, totalCount, stackTraceEvents } = - await getExecutablesAndStackTraces({ - logger, - client: createProfilingEsClient({ request, esClient }), - filter, - sampleSize: targetSampleSize, - }); + const { + stackTraces, + executables, + stackFrames, + eventsIndex, + totalCount, + totalFrames, + stackTraceEvents, + } = await getExecutablesAndStackTraces({ + logger, + client: createProfilingEsClient({ request, esClient }), + filter, + sampleSize: targetSampleSize, + }); const flamegraph = await withProfilingSpan('create_flamegraph', async () => { const t0 = Date.now(); - const graph = createCallerCalleeGraph( + const tree = createCalleeTree( stackTraceEvents, stackTraces, stackFrames, - executables + executables, + totalFrames ); - logger.info(`creating caller-callee graph took ${Date.now() - t0} ms`); + logger.info(`creating callee tree took ${Date.now() - t0} ms`); - const t1 = Date.now(); - const columnar = createColumnarCallerCallee(graph); - logger.info(`creating columnar caller-callee graph took ${Date.now() - t1} ms`); + // sampleRate is 1/5^N, with N being the downsampled index the events were fetched from. + // N=0: full events table (sampleRate is 1) + // N=1: downsampled by 5 (sampleRate is 0.2) + // ... - const t2 = Date.now(); - const fg = createFlameGraph(columnar); - logger.info(`creating flamegraph took ${Date.now() - t2} ms`); + // totalCount is the sum(Count) of all events in the filter range in the + // downsampled index we were looking at. + // To estimate how many events we have in the full events index: totalCount / sampleRate. + // Do the same for single entries in the events array. + + const t1 = Date.now(); + const fg = createFlameGraph( + tree, + totalSeconds, + Math.floor(totalCount / eventsIndex.sampleRate), + totalCount + ); + logger.info(`creating flamegraph took ${Date.now() - t1} ms`); return fg; }); - // sampleRate is 1/5^N, with N being the downsampled index the events were fetched from. - // N=0: full events table (sampleRate is 1) - // N=1: downsampled by 5 (sampleRate is 0.2) - // ... - - // totalCount is the sum(Count) of all events in the filter range in the - // downsampled index we were looking at. - // To estimate how many events we have in the full events index: totalCount / sampleRate. - // Do the same for single entries in the events array. - - const body: ElasticFlameGraph = { - ...flamegraph, - TotalSeconds: totalSeconds, - TotalTraces: Math.floor(totalCount / eventsIndex.sampleRate), - SampledTraces: totalCount, - }; - logger.info('returning payload response to client'); - return response.ok({ body }); + return response.ok({ body: flamegraph }); } catch (e) { logger.error(e); return response.customError({ diff --git a/x-pack/plugins/profiling/server/routes/get_executables_and_stacktraces.ts b/x-pack/plugins/profiling/server/routes/get_executables_and_stacktraces.ts index 4025022222177..2c63b82c443f7 100644 --- a/x-pack/plugins/profiling/server/routes/get_executables_and_stacktraces.ts +++ b/x-pack/plugins/profiling/server/routes/get_executables_and_stacktraces.ts @@ -68,7 +68,7 @@ export async function getExecutablesAndStackTraces({ stackTraceEvents.set(id, Math.floor(count / (eventsIndex.sampleRate * p))); } - const { stackTraces, stackFrameDocIDs, executableDocIDs } = await mgetStackTraces({ + const { stackTraces, totalFrames, stackFrameDocIDs, executableDocIDs } = await mgetStackTraces({ logger, client, events: stackTraceEvents, @@ -86,6 +86,7 @@ export async function getExecutablesAndStackTraces({ stackFrames, stackTraceEvents, totalCount, + totalFrames, eventsIndex, }; }); diff --git a/x-pack/plugins/profiling/server/routes/stacktrace.ts b/x-pack/plugins/profiling/server/routes/stacktrace.ts index fca1c56ebe711..4ae7d91596f10 100644 --- a/x-pack/plugins/profiling/server/routes/stacktrace.ts +++ b/x-pack/plugins/profiling/server/routes/stacktrace.ts @@ -18,6 +18,8 @@ import { ProfilingStackTrace, } from '../../common/elasticsearch'; import { + emptyExecutable, + emptyStackFrame, Executable, FileID, StackFrame, @@ -310,7 +312,7 @@ export async function mgetStackTraces({ ); } - return { stackTraces, stackFrameDocIDs, executableDocIDs }; + return { stackTraces, totalFrames, stackFrameDocIDs, executableDocIDs }; } export async function mgetStackFrames({ @@ -352,13 +354,7 @@ export async function mgetStackFrames({ }); framesFound++; } else { - stackFrames.set(frame._id, { - FileName: '', - FunctionName: '', - FunctionOffset: 0, - LineNumber: 0, - SourceType: 0, - }); + stackFrames.set(frame._id, emptyStackFrame); } } logger.info(`processing data took ${Date.now() - t0} ms`); @@ -403,9 +399,7 @@ export async function mgetExecutables({ }); exeFound++; } else { - executables.set(exe._id, { - FileName: '', - }); + executables.set(exe._id, emptyExecutable); } } logger.info(`processing data took ${Date.now() - t0} ms`); diff --git a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.test.ts b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.test.ts index 1b32f688ee8c0..ffcf973f028a2 100644 --- a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.test.ts +++ b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.test.ts @@ -8,11 +8,7 @@ import { of } from 'rxjs'; import { merge } from 'lodash'; import { loggerMock } from '@kbn/logging-mocks'; import { AlertConsumers } from '@kbn/rule-data-utils'; -import { - ruleRegistrySearchStrategyProvider, - EMPTY_RESPONSE, - RULE_SEARCH_STRATEGY_NAME, -} from './search_strategy'; +import { ruleRegistrySearchStrategyProvider, EMPTY_RESPONSE } from './search_strategy'; import { ruleDataServiceMock } from '../rule_data_plugin_service/rule_data_plugin_service.mock'; import { dataPluginMock } from '@kbn/data-plugin/server/mocks'; import { SearchStrategyDependencies } from '@kbn/data-plugin/server'; @@ -385,48 +381,6 @@ describe('ruleRegistrySearchStrategyProvider()', () => { ).toStrictEqual([{ test: { order: 'desc' } }]); }); - it('should reject, to the best of our ability, public requests', async () => { - (getIsKibanaRequest as jest.Mock).mockImplementation(() => { - return false; - }); - const request: RuleRegistrySearchRequest = { - featureIds: [AlertConsumers.LOGS], - sort: [ - { - test: { - order: 'desc', - }, - }, - ], - }; - const options = {}; - const deps = { - request: {}, - }; - - const strategy = ruleRegistrySearchStrategyProvider( - data, - ruleDataService, - alerting, - logger, - security, - spaces - ); - - let err = null; - try { - await strategy - .search(request, options, deps as unknown as SearchStrategyDependencies) - .toPromise(); - } catch (e) { - err = e; - } - expect(err).not.toBeNull(); - expect(err.message).toBe( - `The ${RULE_SEARCH_STRATEGY_NAME} search strategy is currently only available for internal use.` - ); - }); - it('passes the query ids if provided', async () => { const request: RuleRegistrySearchRequest = { featureIds: [AlertConsumers.SIEM], diff --git a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts index 6b9ac15cd8d6a..49a6439ef9b59 100644 --- a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts +++ b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts @@ -5,7 +5,6 @@ * 2.0. */ import { map, mergeMap, catchError } from 'rxjs/operators'; -import Boom from '@hapi/boom'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { Logger } from '@kbn/core/server'; import { from, of } from 'rxjs'; @@ -25,7 +24,6 @@ import { Dataset } from '../rule_data_plugin_service/index_options'; import { MAX_ALERT_SEARCH_SIZE } from '../../common/constants'; import { AlertAuditAction, alertAuditEvent } from '..'; import { getSpacesFilter, getAuthzFilter } from '../lib'; -import { getIsKibanaRequest } from '../lib/get_is_kibana_request'; export const EMPTY_RESPONSE: RuleRegistrySearchResponse = { rawResponse: {} as RuleRegistrySearchResponse['rawResponse'], @@ -47,13 +45,6 @@ export const ruleRegistrySearchStrategyProvider = ( const requestUserEs = data.search.getSearchStrategy(ENHANCED_ES_SEARCH_STRATEGY); return { search: (request, options, deps) => { - // We want to ensure this request came from our UI. We can't really do this - // but we have a best effort we can try - if (!getIsKibanaRequest(deps.request.headers)) { - throw Boom.notFound( - `The ${RULE_SEARCH_STRATEGY_NAME} search strategy is currently only available for internal use.` - ); - } // SIEM uses RBAC fields in their alerts but also utilizes ES DLS which // is different than every other solution so we need to special case // those requests. diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts index 8272c9220e103..cd18a28e0d373 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts @@ -90,6 +90,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", ] `); }); @@ -174,6 +175,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:alert-type/my-feature/alert/get", "alerting:1.0.0-zeta1:alert-type/my-feature/alert/find", "alerting:1.0.0-zeta1:alert-type/my-feature/alert/getAuthorizedAlertsIndices", @@ -218,6 +220,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/create", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/delete", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/update", @@ -316,6 +319,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/create", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/delete", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/update", @@ -374,6 +378,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/create", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/delete", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/update", @@ -392,6 +397,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getRuleExecutionKPI", ] `); }); @@ -480,6 +486,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/create", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/delete", "alerting:1.0.0-zeta1:alert-type/my-feature/rule/update", @@ -498,6 +505,7 @@ describe(`feature_privilege_builder`, () => { "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getAlertSummary", "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getExecutionLog", "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/find", + "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/rule/getRuleExecutionKPI", "alerting:1.0.0-zeta1:another-alert-type/my-feature/alert/get", "alerting:1.0.0-zeta1:another-alert-type/my-feature/alert/find", "alerting:1.0.0-zeta1:another-alert-type/my-feature/alert/getAuthorizedAlertsIndices", diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts index 542dfd1267d4c..a11a4fa77bcdd 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts @@ -17,7 +17,14 @@ enum AlertingEntity { } const readOperations: Record = { - rule: ['get', 'getRuleState', 'getAlertSummary', 'getExecutionLog', 'find'], + rule: [ + 'get', + 'getRuleState', + 'getAlertSummary', + 'getExecutionLog', + 'find', + 'getRuleExecutionKPI', + ], alert: ['get', 'find', 'getAuthorizedAlertsIndices'], }; diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index c56170fde9863..7358fbb33b4b2 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -113,7 +113,7 @@ export enum SecurityPageName { noPage = '', overview = 'overview', policies = 'policy', - actionHistory = 'action_history', + responseActionsHistory = 'response_actions_history', rules = 'rules', rulesCreate = 'rules-create', sessions = 'sessions', @@ -159,7 +159,7 @@ export const EVENT_FILTERS_PATH = `${MANAGEMENT_PATH}/event_filters` as const; export const HOST_ISOLATION_EXCEPTIONS_PATH = `${MANAGEMENT_PATH}/host_isolation_exceptions` as const; export const BLOCKLIST_PATH = `${MANAGEMENT_PATH}/blocklist` as const; -export const ACTION_HISTORY_PATH = `${MANAGEMENT_PATH}/action_history` as const; +export const RESPONSE_ACTIONS_HISTORY_PATH = `${MANAGEMENT_PATH}/response_actions_history` as const; export const ENTITY_ANALYTICS_PATH = '/entity_analytics' as const; export const APP_OVERVIEW_PATH = `${APP_PATH}${OVERVIEW_PATH}` as const; export const APP_LANDING_PATH = `${APP_PATH}${LANDING_PATH}` as const; @@ -183,7 +183,8 @@ export const APP_EVENT_FILTERS_PATH = `${APP_PATH}${EVENT_FILTERS_PATH}` as cons export const APP_HOST_ISOLATION_EXCEPTIONS_PATH = `${APP_PATH}${HOST_ISOLATION_EXCEPTIONS_PATH}` as const; export const APP_BLOCKLIST_PATH = `${APP_PATH}${BLOCKLIST_PATH}` as const; -export const APP_ACTION_HISTORY_PATH = `${APP_PATH}${ACTION_HISTORY_PATH}` as const; +export const APP_RESPONSE_ACTIONS_HISTORY_PATH = + `${APP_PATH}${RESPONSE_ACTIONS_HISTORY_PATH}` as const; export const APP_ENTITY_ANALYTICS_PATH = `${APP_PATH}${ENTITY_ANALYTICS_PATH}` as const; // cloud logs to exclude from default index pattern @@ -450,9 +451,6 @@ export const NEW_FEATURES_TOUR_STORAGE_KEYS = { RULE_MANAGEMENT_PAGE: 'securitySolution.rulesManagementPage.newFeaturesTour.v8.4', }; -export const RULES_MANAGEMENT_FEATURE_TOUR_STORAGE_KEY = - 'securitySolution.rulesManagementPage.newFeaturesTour.v8.4'; - export const RULE_DETAILS_EXECUTION_LOG_TABLE_SHOW_METRIC_COLUMNS_STORAGE_KEY = 'securitySolution.ruleDetails.ruleExecutionLog.showMetrics.v8.2'; @@ -465,10 +463,6 @@ export enum BulkActionsDryRunErrCode { MACHINE_LEARNING_INDEX_PATTERN = 'MACHINE_LEARNING_INDEX_PATTERN', } -export const RISKY_HOSTS_EXTERNAL_DOC_LINK = - 'https://www.github.com/elastic/detection-rules/blob/main/docs/experimental-machine-learning/host-risk-score.md'; -export const RISKY_USERS_EXTERNAL_DOC_LINK = - 'https://www.github.com/elastic/detection-rules/blob/main/docs/experimental-machine-learning/user-risk-score.md'; export const RISKY_HOSTS_DOC_LINK = 'https://www.elastic.co/guide/en/security/current/host-risk-score.html'; export const RISKY_USERS_DOC_LINK = diff --git a/x-pack/plugins/security_solution/common/detection_engine/rule_monitoring/model/execution_metrics.ts b/x-pack/plugins/security_solution/common/detection_engine/rule_monitoring/model/execution_metrics.ts index c6bb71970e599..b15c76119e441 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/rule_monitoring/model/execution_metrics.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/rule_monitoring/model/execution_metrics.ts @@ -12,8 +12,17 @@ export type DurationMetric = t.TypeOf; export const DurationMetric = PositiveInteger; export type RuleExecutionMetrics = t.TypeOf; + +/** + @property total_search_duration_ms - "total time spent performing ES searches as measured by Kibana; + includes network latency and time spent serializing/deserializing request/response", + @property total_indexing_duration_ms - "total time spent indexing documents during current rule execution cycle", + @property total_enrichment_duration_ms - total time spent enriching documents during current rule execution cycle + @property execution_gap_duration_s - "duration in seconds of execution gap" +*/ export const RuleExecutionMetrics = t.partial({ total_search_duration_ms: DurationMetric, total_indexing_duration_ms: DurationMetric, + total_enrichment_duration_ms: DurationMetric, execution_gap_duration_s: DurationMetric, }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/perform_bulk_action_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/perform_bulk_action_schema.ts index a74845721a022..0140e5f8d9262 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/perform_bulk_action_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/perform_bulk_action_schema.ts @@ -9,7 +9,6 @@ import * as t from 'io-ts'; import { NonEmptyArray, TimeDuration, enumeration } from '@kbn/securitysolution-io-ts-types'; import { - throttle, action_group as actionGroup, action_params as actionParams, action_id as actionId, @@ -41,6 +40,18 @@ export enum BulkActionEditType { 'set_schedule' = 'set_schedule', } +export const throttleForBulkActions = t.union([ + t.literal('rule'), + TimeDuration({ + allowedDurations: [ + [1, 'h'], + [1, 'd'], + [7, 'd'], + ], + }), +]); +export type ThrottleForBulkActions = t.TypeOf; + const bulkActionEditPayloadTags = t.type({ type: t.union([ t.literal(BulkActionEditType.add_tags), @@ -96,7 +107,7 @@ const bulkActionEditPayloadRuleActions = t.type({ t.literal(BulkActionEditType.set_rule_actions), ]), value: t.type({ - throttle, + throttle: throttleForBulkActions, actions: t.array(normalizedRuleAction), }), }); @@ -106,8 +117,8 @@ export type BulkActionEditPayloadRuleActions = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/endpoint/schema/actions.ts b/x-pack/plugins/security_solution/common/endpoint/schema/actions.ts index 08adac7c9ede0..8b982e6e6f463 100644 --- a/x-pack/plugins/security_solution/common/endpoint/schema/actions.ts +++ b/x-pack/plugins/security_solution/common/endpoint/schema/actions.ts @@ -28,6 +28,8 @@ export const NoParametersRequestSchema = { body: schema.object({ ...BaseActionRequestSchema }), }; +export type BaseActionRequestBody = TypeOf; + export const KillOrSuspendProcessRequestSchema = { body: schema.object({ ...BaseActionRequestSchema, diff --git a/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.test.ts b/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.test.ts index 3434e95f29b4b..b9c0dcff2054a 100644 --- a/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.test.ts +++ b/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.test.ts @@ -107,6 +107,40 @@ describe('Endpoint Authz service', () => { ); }); }); + + describe('endpoint rbac is enabled', () => { + describe('canIsolateHost', () => { + it('should be true if packagePrivilege.writeHostIsolation is true', () => { + fleetAuthz.packagePrivileges!.endpoint.actions.writeHostIsolation.executePackageAction = + true; + const authz = calculateEndpointAuthz(licenseService, fleetAuthz, userRoles, true); + expect(authz.canIsolateHost).toBe(true); + }); + + it('should be false if packagePrivilege.writeHostIsolation is false', () => { + fleetAuthz.packagePrivileges!.endpoint.actions.writeHostIsolation.executePackageAction = + false; + const authz = calculateEndpointAuthz(licenseService, fleetAuthz, userRoles, true); + expect(authz.canIsolateHost).toBe(false); + }); + }); + + describe('canUnIsolateHost', () => { + it('should be true if packagePrivilege.writeHostIsolation is true', () => { + fleetAuthz.packagePrivileges!.endpoint.actions.writeHostIsolation.executePackageAction = + true; + const authz = calculateEndpointAuthz(licenseService, fleetAuthz, userRoles, true); + expect(authz.canUnIsolateHost).toBe(true); + }); + + it('should be false if packagePrivilege.writeHostIsolation is false', () => { + fleetAuthz.packagePrivileges!.endpoint.actions.writeHostIsolation.executePackageAction = + false; + const authz = calculateEndpointAuthz(licenseService, fleetAuthz, userRoles, true); + expect(authz.canUnIsolateHost).toBe(false); + }); + }); + }); }); describe('getEndpointAuthzInitialState()', () => { diff --git a/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.ts b/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.ts index 39d99f184bd23..bc40bd11f5d79 100644 --- a/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.ts +++ b/x-pack/plugins/security_solution/common/endpoint/service/authz/authz.ts @@ -20,20 +20,26 @@ import type { MaybeImmutable } from '../../types'; */ export const calculateEndpointAuthz = ( licenseService: LicenseService, - fleetAuthz: FleetAuthz | undefined, // TODO: Remove `undefined` type when `fleetAuthz` is needed and used. - userRoles: MaybeImmutable + fleetAuthz: FleetAuthz, + userRoles: MaybeImmutable, + // to be used in follow-up PRs + isEndpointRbacEnabled: boolean = false ): EndpointAuthz => { const isPlatinumPlusLicense = licenseService.isPlatinumPlus(); const isEnterpriseLicense = licenseService.isEnterprise(); const hasEndpointManagementAccess = userRoles.includes('superuser'); + const canIsolateHost = isEndpointRbacEnabled + ? fleetAuthz.packagePrivileges?.endpoint?.actions?.writeHostIsolation?.executePackageAction || + false + : hasEndpointManagementAccess; return { canAccessFleet: fleetAuthz?.fleet.all ?? userRoles.includes('superuser'), canAccessEndpointManagement: hasEndpointManagementAccess, canCreateArtifactsByPolicy: hasEndpointManagementAccess && isPlatinumPlusLicense, // Response Actions - canIsolateHost: isPlatinumPlusLicense && hasEndpointManagementAccess, - canUnIsolateHost: hasEndpointManagementAccess, + canIsolateHost: isPlatinumPlusLicense && canIsolateHost, + canUnIsolateHost: canIsolateHost, canKillProcess: hasEndpointManagementAccess && isEnterpriseLicense, canSuspendProcess: hasEndpointManagementAccess && isEnterpriseLicense, canGetRunningProcesses: hasEndpointManagementAccess && isEnterpriseLicense, diff --git a/x-pack/plugins/security_solution/common/endpoint/types/actions.ts b/x-pack/plugins/security_solution/common/endpoint/types/actions.ts index bcbdcfb3b66b8..91eb10c5f45a2 100644 --- a/x-pack/plugins/security_solution/common/endpoint/types/actions.ts +++ b/x-pack/plugins/security_solution/common/endpoint/types/actions.ts @@ -253,6 +253,7 @@ export interface PendingActionsResponse { } export type PendingActionsRequestQuery = TypeOf; + export interface ActionDetails { /** The action id */ id: string; diff --git a/x-pack/plugins/security_solution/common/experimental_features.ts b/x-pack/plugins/security_solution/common/experimental_features.ts index db74802dcb599..aa581971e5f09 100644 --- a/x-pack/plugins/security_solution/common/experimental_features.ts +++ b/x-pack/plugins/security_solution/common/experimental_features.ts @@ -20,7 +20,6 @@ export const allowedExperimentalValues = Object.freeze({ pendingActionResponsesWithAck: true, policyListEnabled: true, policyResponseInFleetEnabled: true, - threatIntelligenceEnabled: false, /** * This is used for enabling the end-to-end tests for the security_solution telemetry. @@ -60,6 +59,11 @@ export const allowedExperimentalValues = Object.freeze({ * Enables the detection response actions in rule + alerts */ responseActionsEnabled: true, + + /** + * Enables endpoint package level rbac + */ + endpointRbacEnabled: false, }); type ExperimentalConfigKeys = Array; diff --git a/x-pack/plugins/security_solution/common/search_strategy/security_solution/risk_score/all/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/risk_score/all/index.ts index bbb2991551f26..5a773d49134da 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/risk_score/all/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/risk_score/all/index.ts @@ -97,3 +97,11 @@ export const enum RiskSeverity { export const isUserRiskScore = (risk: HostRiskScore | UserRiskScore): risk is UserRiskScore => 'user' in risk; + +export const EMPTY_SEVERITY_COUNT = { + [RiskSeverity.critical]: 0, + [RiskSeverity.high]: 0, + [RiskSeverity.low]: 0, + [RiskSeverity.moderate]: 0, + [RiskSeverity.unknown]: 0, +}; diff --git a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules.cy.ts b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules.cy.ts index 3cdb5920101d1..745c542bf247c 100644 --- a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules.cy.ts +++ b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules.cy.ts @@ -71,6 +71,7 @@ import { setScheduleIntervalTimeUnit, assertRuleScheduleValues, assertUpdateScheduleWarningExists, + assertDefaultValuesAreAppliedToScheduleFields, } from '../../tasks/rules_bulk_edit'; import { hasIndexPatterns, getDetails } from '../../tasks/rule_details'; @@ -493,6 +494,18 @@ describe('Detection rules, bulk edit', () => { }); describe('Schedule', () => { + it('Default values are applied to bulk edit schedule fields', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + clickUpdateScheduleMenuItem(); + + assertUpdateScheduleWarningExists(expectedNumberOfCustomRulesToBeEdited); + + assertDefaultValuesAreAppliedToScheduleFields({ + interval: 5, + lookback: 1, + }); + }); + it('Updates schedule for custom rules', () => { selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); clickUpdateScheduleMenuItem(); diff --git a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules_data_view.cy.ts b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules_data_view.cy.ts new file mode 100644 index 0000000000000..766c8d9483f0a --- /dev/null +++ b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/bulk_edit_rules_data_view.cy.ts @@ -0,0 +1,177 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + RULES_BULK_EDIT_DATA_VIEWS_WARNING, + RULES_BULK_EDIT_OVERWRITE_DATA_VIEW_CHECKBOX, +} from '../../screens/rules_bulk_edit'; + +import { DATA_VIEW_DETAILS, INDEX_PATTERNS_DETAILS } from '../../screens/rule_details'; + +import { + waitForRulesTableToBeLoaded, + goToRuleDetails, + selectNumberOfRules, +} from '../../tasks/alerts_detection_rules'; + +import { + typeIndexPatterns, + waitForBulkEditActionToFinish, + submitBulkEditForm, + checkOverwriteDataViewCheckbox, + checkOverwriteIndexPatternsCheckbox, + openBulkEditAddIndexPatternsForm, + openBulkEditDeleteIndexPatternsForm, +} from '../../tasks/rules_bulk_edit'; + +import { hasIndexPatterns, getDetails, assertDetailsNotExist } from '../../tasks/rule_details'; +import { login, visitWithoutDateRange } from '../../tasks/login'; + +import { SECURITY_DETECTIONS_RULES_URL } from '../../urls/navigation'; +import { + createCustomRule, + createCustomIndicatorRule, + createEventCorrelationRule, + createThresholdRule, + createNewTermsRule, + createSavedQueryRule, +} from '../../tasks/api_calls/rules'; +import { cleanKibana, deleteAlertsAndRules, postDataView } from '../../tasks/common'; + +import { + getEqlRule, + getNewThreatIndicatorRule, + getNewRule, + getNewThresholdRule, + getNewTermsRule, +} from '../../objects/rule'; + +import { esArchiverResetKibana } from '../../tasks/es_archiver'; + +const DATA_VIEW_ID = 'auditbeat'; + +const expectedIndexPatterns = ['index-1-*', 'index-2-*']; + +const expectedNumberOfCustomRulesToBeEdited = 6; + +const indexDataSource = { dataView: DATA_VIEW_ID, type: 'dataView' } as const; + +const defaultRuleData = { + dataSource: indexDataSource, +}; + +describe('Detection rules, bulk edit, data view', () => { + before(() => { + cleanKibana(); + login(); + }); + beforeEach(() => { + deleteAlertsAndRules(); + esArchiverResetKibana(); + + postDataView(DATA_VIEW_ID); + + createCustomRule({ ...getNewRule(), ...defaultRuleData }, '1'); + createEventCorrelationRule({ ...getEqlRule(), ...defaultRuleData }, '2'); + createCustomIndicatorRule({ ...getNewThreatIndicatorRule(), ...defaultRuleData }, '3'); + createThresholdRule({ ...getNewThresholdRule(), ...defaultRuleData }, '4'); + createNewTermsRule({ ...getNewTermsRule(), ...defaultRuleData }, '5'); + createSavedQueryRule({ ...getNewRule(), ...defaultRuleData, savedId: 'mocked' }, '6'); + + visitWithoutDateRange(SECURITY_DETECTIONS_RULES_URL); + + waitForRulesTableToBeLoaded(); + }); + + it('Add index patterns to custom rules with configured data view', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + + openBulkEditAddIndexPatternsForm(); + typeIndexPatterns(expectedIndexPatterns); + submitBulkEditForm(); + + waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited }); + + // check if rule still has data view and index patterns field does not exist + goToRuleDetails(); + getDetails(DATA_VIEW_DETAILS).contains(DATA_VIEW_ID); + assertDetailsNotExist(INDEX_PATTERNS_DETAILS); + }); + + it('Add index patterns to custom rules with configured data view when data view checkbox is checked', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + + openBulkEditAddIndexPatternsForm(); + typeIndexPatterns(expectedIndexPatterns); + + // click on data view overwrite checkbox, ensure warning is displayed + cy.get(RULES_BULK_EDIT_DATA_VIEWS_WARNING).should('not.exist'); + checkOverwriteDataViewCheckbox(); + cy.get(RULES_BULK_EDIT_DATA_VIEWS_WARNING).should('be.visible'); + + submitBulkEditForm(); + + waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited }); + + // check if rule has been updated with index patterns and data view does not exist + goToRuleDetails(); + hasIndexPatterns(expectedIndexPatterns.join('')); + assertDetailsNotExist(DATA_VIEW_DETAILS); + }); + + it('Overwrite index patterns in custom rules with configured data view', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + + openBulkEditAddIndexPatternsForm(); + typeIndexPatterns(expectedIndexPatterns); + checkOverwriteIndexPatternsCheckbox(); + submitBulkEditForm(); + + waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited }); + + // check if rule still has data view and index patterns field does not exist + goToRuleDetails(); + getDetails(DATA_VIEW_DETAILS).contains(DATA_VIEW_ID); + assertDetailsNotExist(INDEX_PATTERNS_DETAILS); + }); + + it('Overwrite index patterns in custom rules with configured data view when data view checkbox is checked', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + + openBulkEditAddIndexPatternsForm(); + typeIndexPatterns(expectedIndexPatterns); + checkOverwriteIndexPatternsCheckbox(); + checkOverwriteDataViewCheckbox(); + + submitBulkEditForm(); + + waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited }); + + // check if rule has been overwritten with index patterns and data view does not exist + goToRuleDetails(); + hasIndexPatterns(expectedIndexPatterns.join('')); + assertDetailsNotExist(DATA_VIEW_DETAILS); + }); + + it('Delete index patterns in custom rules with configured data view', () => { + selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited); + + openBulkEditDeleteIndexPatternsForm(); + typeIndexPatterns(expectedIndexPatterns); + + // in delete form data view checkbox is absent + cy.get(RULES_BULK_EDIT_OVERWRITE_DATA_VIEW_CHECKBOX).should('not.exist'); + + submitBulkEditForm(); + + waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited }); + + // check if rule still has data view and index patterns field does not exist + goToRuleDetails(); + getDetails(DATA_VIEW_DETAILS).contains(DATA_VIEW_ID); + }); +}); diff --git a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/custom_saved_query_rule.cy.ts b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/custom_saved_query_rule.cy.ts index 9b1d5c71a6fa9..5027fe09a8d3e 100644 --- a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/custom_saved_query_rule.cy.ts +++ b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/custom_saved_query_rule.cy.ts @@ -25,8 +25,8 @@ import { import { goToRuleDetails, editFirstRule } from '../../tasks/alerts_detection_rules'; import { createTimeline } from '../../tasks/api_calls/timelines'; -import { createSavedQuery } from '../../tasks/api_calls/saved_queries'; -import { cleanKibana, deleteAlertsAndRules, deleteSavedQueries } from '../../tasks/common'; +import { createSavedQuery, deleteSavedQueries } from '../../tasks/api_calls/saved_queries'; +import { cleanKibana, deleteAlertsAndRules } from '../../tasks/common'; import { createAndEnableRule, fillAboutRuleAndContinue, diff --git a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/related_integrations.cy.ts b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/related_integrations.cy.ts index b5c6b5cd341ec..02ccff0c265dd 100644 --- a/x-pack/plugins/security_solution/cypress/e2e/detection_rules/related_integrations.cy.ts +++ b/x-pack/plugins/security_solution/cypress/e2e/detection_rules/related_integrations.cy.ts @@ -122,14 +122,14 @@ describe('Related integrations', () => { visit(DETECTIONS_RULE_MANAGEMENT_URL); }); - it('should display a badge with the installed integrations on the rule management page', () => { + it.skip('should display a badge with the installed integrations on the rule management page', () => { cy.get(INTEGRATIONS_POPOVER).should( 'have.text', `${rule.enabledIntegrations}/${rule.integrations.length} integrations` ); }); - it('should display a popover when clicking the badge with the installed integrations on the rule management page', () => { + it.skip('should display a popover when clicking the badge with the installed integrations on the rule management page', () => { openIntegrationsPopover(); cy.get(INTEGRATIONS_POPOVER_TITLE).should( @@ -148,7 +148,7 @@ describe('Related integrations', () => { }); }); - it('should display the integrations on the definition section', () => { + it.skip('should display the integrations on the definition section', () => { goToTheRuleDetailsOf(rule.name); cy.get(INTEGRATIONS).should('have.length', rule.integrations.length); diff --git a/x-pack/plugins/security_solution/cypress/e2e/timelines/search_or_filter.cy.ts b/x-pack/plugins/security_solution/cypress/e2e/timelines/search_or_filter.cy.ts index d5a084f65fac8..39420b27e3866 100644 --- a/x-pack/plugins/security_solution/cypress/e2e/timelines/search_or_filter.cy.ts +++ b/x-pack/plugins/security_solution/cypress/e2e/timelines/search_or_filter.cy.ts @@ -16,7 +16,11 @@ import { cleanKibana } from '../../tasks/common'; import { login, visit, visitWithoutDateRange } from '../../tasks/login'; import { openTimelineUsingToggle } from '../../tasks/security_main'; -import { executeTimelineKQL } from '../../tasks/timeline'; +import { + changeTimelineQueryLanguage, + executeTimelineKQL, + executeTimelineSearch, +} from '../../tasks/timeline'; import { waitForTimelinesPanelToBeLoaded } from '../../tasks/timelines'; import { HOSTS_URL, TIMELINES_URL } from '../../urls/navigation'; @@ -38,6 +42,15 @@ describe('Timeline search and filters', () => { cy.get(SERVER_SIDE_EVENT_COUNT).should(($count) => expect(+$count.text()).to.be.gt(0)); }); + + it('executes a Lucene query', () => { + const messageProcessQuery = 'message:Process\\ zsh*'; + openTimelineUsingToggle(); + changeTimelineQueryLanguage('lucene'); + executeTimelineSearch(messageProcessQuery); + + cy.get(SERVER_SIDE_EVENT_COUNT).should(($count) => expect(+$count.text()).to.be.gt(0)); + }); }); describe('Update kqlMode for timeline', () => { diff --git a/x-pack/plugins/security_solution/cypress/screens/rules_bulk_edit.ts b/x-pack/plugins/security_solution/cypress/screens/rules_bulk_edit.ts index 341633380a3fa..6f4056034a053 100644 --- a/x-pack/plugins/security_solution/cypress/screens/rules_bulk_edit.ts +++ b/x-pack/plugins/security_solution/cypress/screens/rules_bulk_edit.ts @@ -32,6 +32,9 @@ export const RULES_BULK_EDIT_INDEX_PATTERNS = '[data-test-subj="bulkEditRulesInd export const RULES_BULK_EDIT_OVERWRITE_INDEX_PATTERNS_CHECKBOX = '[data-test-subj="bulkEditRulesOverwriteIndexPatterns"]'; +export const RULES_BULK_EDIT_OVERWRITE_DATA_VIEW_CHECKBOX = + '[data-test-subj="bulkEditRulesOverwriteRulesWithDataViews"]'; + export const RULES_BULK_EDIT_TAGS = '[data-test-subj="bulkEditRulesTags"]'; export const RULES_BULK_EDIT_OVERWRITE_TAGS_CHECKBOX = @@ -48,6 +51,9 @@ export const RULES_BULK_EDIT_TIMELINE_TEMPLATES_SELECTOR = export const RULES_BULK_EDIT_TIMELINE_TEMPLATES_WARNING = '[data-test-subj="bulkEditRulesTimelineTemplateWarning"]'; +export const RULES_BULK_EDIT_DATA_VIEWS_WARNING = + '[data-test-subj="bulkEditRulesDataViewsWarning"]'; + export const RULES_BULK_EDIT_SCHEDULES_WARNING = '[data-test-subj="bulkEditRulesSchedulesWarning"]'; export const UPDATE_SCHEDULE_INTERVAL_INPUT = @@ -56,4 +62,6 @@ export const UPDATE_SCHEDULE_INTERVAL_INPUT = export const UPDATE_SCHEDULE_LOOKBACK_INPUT = '[data-test-subj="bulkEditRulesScheduleLookbackSelector"]'; +export const UPDATE_SCHEDULE_TIME_INTERVAL = '[data-test-subj="interval"]'; + export const UPDATE_SCHEDULE_TIME_UNIT_SELECT = '[data-test-subj="timeType"]'; diff --git a/x-pack/plugins/security_solution/cypress/screens/timeline.ts b/x-pack/plugins/security_solution/cypress/screens/timeline.ts index 51ce3b38d4d6f..87d70a73dbd1f 100644 --- a/x-pack/plugins/security_solution/cypress/screens/timeline.ts +++ b/x-pack/plugins/security_solution/cypress/screens/timeline.ts @@ -215,6 +215,16 @@ export const TIMELINE_KQLMODE_SEARCH = '[data-test-subj="kqlModePopoverSearch"]' export const TIMELINE_KQLMODE_FILTER = '[data-test-subj="kqlModePopoverFilter"]'; +export const QUERYBAR_MENU_POPOVER = '[data-test-subj="queryBarMenuPopover"]'; + +export const TIMELINE_SHOWQUERYBARMENU_BUTTON = `${TIMELINE_FLYOUT} [data-test-subj="showQueryBarMenu"]`; + +export const TIMELINE_SWITCHQUERYLANGUAGE_BUTTON = '[data-test-subj="switchQueryLanguageButton"]'; + +export const TIMELINE_LUCENELANGUAGE_BUTTON = '[data-test-subj="luceneLanguageMenuItem"]'; + +export const TIMELINE_KQLLANGUAGE_BUTTON = '[data-test-subj="kqlLanguageMenuItem"]'; + export const TIMELINE_TITLE = '[data-test-subj="timeline-title"]'; export const TIMELINE_TITLE_INPUT = '[data-test-subj="save-timeline-title"]'; diff --git a/x-pack/plugins/security_solution/cypress/tasks/api_calls/rules.ts b/x-pack/plugins/security_solution/cypress/tasks/api_calls/rules.ts index 4fb076f11f445..80fb77013acbb 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/api_calls/rules.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/api_calls/rules.ts @@ -53,7 +53,8 @@ export const createCustomRule = ( severity: rule.severity.toLocaleLowerCase(), type: 'query', from: 'now-50000h', - index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : '', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, query: rule.customQuery, language: 'kuery', enabled: false, @@ -71,83 +72,80 @@ export const createCustomRule = ( }); export const createEventCorrelationRule = (rule: CustomRule, ruleId = 'rule_testing') => { - if (rule.dataSource.type === 'indexPatterns') { - cy.request({ - method: 'POST', - url: 'api/detection_engine/rules', - body: { - rule_id: ruleId, - risk_score: parseInt(rule.riskScore, 10), - description: rule.description, - interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, - from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, - name: rule.name, - severity: rule.severity.toLocaleLowerCase(), - type: 'eql', - index: rule.dataSource.index, - query: rule.customQuery, - language: 'eql', - enabled: true, - tags: rule.tags, - }, - headers: { 'kbn-xsrf': 'cypress-creds' }, - }); - } + cy.request({ + method: 'POST', + url: 'api/detection_engine/rules', + body: { + rule_id: ruleId, + risk_score: parseInt(rule.riskScore, 10), + description: rule.description, + interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, + from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, + name: rule.name, + severity: rule.severity.toLocaleLowerCase(), + type: 'eql', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, + query: rule.customQuery, + language: 'eql', + enabled: true, + tags: rule.tags, + }, + headers: { 'kbn-xsrf': 'cypress-creds' }, + }); }; export const createThresholdRule = (rule: ThresholdRule, ruleId = 'rule_testing') => { - if (rule.dataSource.type === 'indexPatterns') { - cy.request({ - method: 'POST', - url: 'api/detection_engine/rules', - body: { - rule_id: ruleId, - risk_score: parseInt(rule.riskScore, 10), - description: rule.description, - interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, - from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, - name: rule.name, - severity: rule.severity.toLocaleLowerCase(), - type: 'threshold', - index: rule.dataSource.index, - query: rule.customQuery, - threshold: { - field: [rule.thresholdField], - value: parseInt(rule.threshold, 10), - cardinality: [], - }, - enabled: true, - tags: rule.tags, + cy.request({ + method: 'POST', + url: 'api/detection_engine/rules', + body: { + rule_id: ruleId, + risk_score: parseInt(rule.riskScore, 10), + description: rule.description, + interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, + from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, + name: rule.name, + severity: rule.severity.toLocaleLowerCase(), + type: 'threshold', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, + query: rule.customQuery, + threshold: { + field: [rule.thresholdField], + value: parseInt(rule.threshold, 10), + cardinality: [], }, - headers: { 'kbn-xsrf': 'cypress-creds' }, - }); - } + enabled: true, + tags: rule.tags, + }, + headers: { 'kbn-xsrf': 'cypress-creds' }, + }); }; export const createNewTermsRule = (rule: NewTermsRule, ruleId = 'rule_testing') => { - if (rule.dataSource.type === 'indexPatterns') { - cy.request({ - method: 'POST', - url: 'api/detection_engine/rules', - body: { - rule_id: ruleId, - risk_score: parseInt(rule.riskScore, 10), - description: rule.description, - interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, - from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, - name: rule.name, - severity: rule.severity.toLocaleLowerCase(), - type: 'new_terms', - index: rule.dataSource.index, - query: rule.customQuery, - new_terms_fields: rule.newTermsFields, - history_window_start: `now-${rule.historyWindowSize.interval}${rule.historyWindowSize.type}`, - enabled: true, - tags: rule.tags, - }, - headers: { 'kbn-xsrf': 'cypress-creds' }, - }); - } + cy.request({ + method: 'POST', + url: 'api/detection_engine/rules', + body: { + rule_id: ruleId, + risk_score: parseInt(rule.riskScore, 10), + description: rule.description, + interval: `${rule.runsEvery.interval}${rule.runsEvery.type}`, + from: `now-${rule.lookBack.interval}${rule.lookBack.type}`, + name: rule.name, + severity: rule.severity.toLocaleLowerCase(), + type: 'new_terms', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, + query: rule.customQuery, + new_terms_fields: rule.newTermsFields, + history_window_start: `now-${rule.historyWindowSize.interval}${rule.historyWindowSize.type}`, + enabled: true, + tags: rule.tags, + }, + headers: { 'kbn-xsrf': 'cypress-creds' }, + }); }; export const createSavedQueryRule = ( @@ -166,7 +164,8 @@ export const createSavedQueryRule = ( severity: rule.severity.toLocaleLowerCase(), type: 'saved_query', from: 'now-50000h', - index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : '', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, saved_id: rule.savedId, language: 'kuery', enabled: false, @@ -184,49 +183,48 @@ export const createSavedQueryRule = ( }); export const createCustomIndicatorRule = (rule: ThreatIndicatorRule, ruleId = 'rule_testing') => { - if (rule.dataSource.type === 'indexPatterns') { - cy.request({ - method: 'POST', - url: 'api/detection_engine/rules', - body: { - rule_id: ruleId, - risk_score: parseInt(rule.riskScore, 10), - description: rule.description, - // Default interval is 1m, our tests config overwrite this to 1s - // See https://github.com/elastic/kibana/pull/125396 for details - interval: '10s', - name: rule.name, - severity: rule.severity.toLocaleLowerCase(), - type: 'threat_match', - timeline_id: rule.timeline.templateTimelineId, - timeline_title: rule.timeline.title, - threat_mapping: [ - { - entries: [ - { - field: rule.indicatorMappingField, - type: 'mapping', - value: rule.indicatorIndexField, - }, - ], - }, - ], - threat_query: '*:*', - threat_language: 'kuery', - threat_filters: [], - threat_index: rule.indicatorIndexPattern, - threat_indicator_path: rule.threatIndicatorPath, - from: 'now-50000h', - index: rule.dataSource.index, - query: rule.customQuery || '*:*', - language: 'kuery', - enabled: true, - tags: rule.tags, - }, - headers: { 'kbn-xsrf': 'cypress-creds' }, - failOnStatusCode: false, - }); - } + cy.request({ + method: 'POST', + url: 'api/detection_engine/rules', + body: { + rule_id: ruleId, + risk_score: parseInt(rule.riskScore, 10), + description: rule.description, + // Default interval is 1m, our tests config overwrite this to 1s + // See https://github.com/elastic/kibana/pull/125396 for details + interval: '10s', + name: rule.name, + severity: rule.severity.toLocaleLowerCase(), + type: 'threat_match', + timeline_id: rule.timeline.templateTimelineId, + timeline_title: rule.timeline.title, + threat_mapping: [ + { + entries: [ + { + field: rule.indicatorMappingField, + type: 'mapping', + value: rule.indicatorIndexField, + }, + ], + }, + ], + threat_query: '*:*', + threat_language: 'kuery', + threat_filters: [], + threat_index: rule.indicatorIndexPattern, + threat_indicator_path: rule.threatIndicatorPath, + from: 'now-50000h', + index: rule.dataSource.type === 'indexPatterns' ? rule.dataSource.index : undefined, + data_view_id: rule.dataSource.type === 'dataView' ? rule.dataSource.dataView : undefined, + query: rule.customQuery || '*:*', + language: 'kuery', + enabled: true, + tags: rule.tags, + }, + headers: { 'kbn-xsrf': 'cypress-creds' }, + failOnStatusCode: false, + }); }; export const createCustomRuleEnabled = ( diff --git a/x-pack/plugins/security_solution/cypress/tasks/api_calls/saved_queries.ts b/x-pack/plugins/security_solution/cypress/tasks/api_calls/saved_queries.ts index 8c4aea51ec045..08867cf55d4c0 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/api_calls/saved_queries.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/api_calls/saved_queries.ts @@ -33,3 +33,20 @@ export const createSavedQuery = ( }, headers: { 'kbn-xsrf': 'cypress-creds' }, }); + +export const deleteSavedQueries = () => { + const kibanaIndexUrl = `${Cypress.env('ELASTICSEARCH_URL')}/.kibana_\*`; + cy.request('POST', `${kibanaIndexUrl}/_delete_by_query?conflicts=proceed`, { + query: { + bool: { + filter: [ + { + match: { + type: 'query', + }, + }, + ], + }, + }, + }); +}; diff --git a/x-pack/plugins/security_solution/cypress/tasks/common.ts b/x-pack/plugins/security_solution/cypress/tasks/common.ts index 23f04d0fd3c2b..cd9525e95b0b2 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/common.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/common.ts @@ -179,23 +179,6 @@ export const deleteCases = () => { }); }; -export const deleteSavedQueries = () => { - const kibanaIndexUrl = `${Cypress.env('ELASTICSEARCH_URL')}/.kibana_\*`; - cy.request('POST', `${kibanaIndexUrl}/_delete_by_query?conflicts=proceed`, { - query: { - bool: { - filter: [ - { - match: { - type: 'query', - }, - }, - ], - }, - }, - }); -}; - export const postDataView = (dataSource: string) => { cy.request({ method: 'POST', diff --git a/x-pack/plugins/security_solution/cypress/tasks/rule_details.ts b/x-pack/plugins/security_solution/cypress/tasks/rule_details.ts index 75668b49aa207..0bd06911acf7d 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/rule_details.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/rule_details.ts @@ -158,6 +158,9 @@ export const goBackToAllRulesTable = () => { export const getDetails = (title: string | RegExp) => cy.get(DETAILS_TITLE).contains(title).next(DETAILS_DESCRIPTION); +export const assertDetailsNotExist = (title: string | RegExp) => + cy.get(DETAILS_TITLE).contains(title).should('not.exist'); + export const hasIndexPatterns = (indexPatterns: string) => { cy.get(DEFINITION_DETAILS).within(() => { getDetails(INDEX_PATTERNS_DETAILS).should('have.text', indexPatterns); diff --git a/x-pack/plugins/security_solution/cypress/tasks/rules_bulk_edit.ts b/x-pack/plugins/security_solution/cypress/tasks/rules_bulk_edit.ts index c3f9336e19fc7..0000a84f26683 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/rules_bulk_edit.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/rules_bulk_edit.ts @@ -30,6 +30,7 @@ import { APPLY_TIMELINE_RULE_BULK_MENU_ITEM, RULES_BULK_EDIT_OVERWRITE_TAGS_CHECKBOX, RULES_BULK_EDIT_OVERWRITE_INDEX_PATTERNS_CHECKBOX, + RULES_BULK_EDIT_OVERWRITE_DATA_VIEW_CHECKBOX, RULES_BULK_EDIT_TIMELINE_TEMPLATES_SELECTOR, UPDATE_SCHEDULE_MENU_ITEM, UPDATE_SCHEDULE_INTERVAL_INPUT, @@ -159,6 +160,14 @@ export const checkOverwriteIndexPatternsCheckbox = () => { .should('be.checked'); }; +export const checkOverwriteDataViewCheckbox = () => { + cy.get(RULES_BULK_EDIT_OVERWRITE_DATA_VIEW_CHECKBOX) + .should('have.text', 'Apply changes to rules configured with data views') + .click() + .get('input') + .should('be.checked'); +}; + export const selectTimelineTemplate = (timelineTitle: string) => { cy.get(RULES_BULK_EDIT_TIMELINE_TEMPLATES_SELECTOR).click(); cy.get(TIMELINE_SEARCHBOX).type(`${timelineTitle}{enter}`).should('not.exist'); @@ -193,6 +202,19 @@ export const typeScheduleLookback = (lookback: string) => { .blur(); }; +interface ScheduleFormFields { + interval: number; + lookback: number; +} + +export const assertDefaultValuesAreAppliedToScheduleFields = ({ + interval, + lookback, +}: ScheduleFormFields) => { + cy.get(UPDATE_SCHEDULE_INTERVAL_INPUT).find('input').should('have.value', interval); + cy.get(UPDATE_SCHEDULE_LOOKBACK_INPUT).find('input').should('have.value', lookback); +}; + type TimeUnit = 'Seconds' | 'Minutes' | 'Hours'; export const setScheduleIntervalTimeUnit = (timeUnit: TimeUnit) => { cy.get(UPDATE_SCHEDULE_INTERVAL_INPUT).within(() => { @@ -209,17 +231,15 @@ export const setScheduleLookbackTimeUnit = (timeUnit: TimeUnit) => { export const assertUpdateScheduleWarningExists = (expectedNumberOfNotMLRules: number) => { cy.get(RULES_BULK_EDIT_SCHEDULES_WARNING).should( 'have.text', - `You're about to apply changes to ${expectedNumberOfNotMLRules} selected rules. The changes you made will be overwritten to the existing Rule schedules and additional look-back time (if any).` + `You're about to apply changes to ${expectedNumberOfNotMLRules} selected rules. The changes you make will overwrite the existing rule schedules and additional look-back time (if any).` ); }; - -export const assertRuleScheduleValues = ({ - interval, - lookback, -}: { +interface RuleSchedule { interval: string; lookback: string; -}) => { +} + +export const assertRuleScheduleValues = ({ interval, lookback }: RuleSchedule) => { cy.get(SCHEDULE_DETAILS).within(() => { cy.get('dd').eq(0).should('contain.text', interval); cy.get('dd').eq(1).should('contain.text', lookback); diff --git a/x-pack/plugins/security_solution/cypress/tasks/timeline.ts b/x-pack/plugins/security_solution/cypress/tasks/timeline.ts index fda2ea08769ef..a83e1157e98d7 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/timeline.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/timeline.ts @@ -74,6 +74,11 @@ import { EMPTY_DROPPABLE_DATA_PROVIDER_GROUP, GET_TIMELINE_GRID_CELL, HOVER_ACTIONS, + TIMELINE_SWITCHQUERYLANGUAGE_BUTTON, + TIMELINE_SHOWQUERYBARMENU_BUTTON, + TIMELINE_LUCENELANGUAGE_BUTTON, + TIMELINE_KQLLANGUAGE_BUTTON, + TIMELINE_QUERY, } from '../screens/timeline'; import { REFRESH_BUTTON, TIMELINE } from '../screens/timelines'; import { drag, drop } from './common'; @@ -170,6 +175,16 @@ export const addFilter = (filter: TimelineFilter): Cypress.Chainable { + cy.get(TIMELINE_SHOWQUERYBARMENU_BUTTON).click(); + cy.get(TIMELINE_SWITCHQUERYLANGUAGE_BUTTON).click(); + if (language === 'lucene') { + cy.get(TIMELINE_LUCENELANGUAGE_BUTTON).click(); + } else { + cy.get(TIMELINE_KQLLANGUAGE_BUTTON).click(); + } +}; + export const addDataProvider = (filter: TimelineFilter): Cypress.Chainable> => { cy.get(TIMELINE_ADD_FIELD_BUTTON).click(); cy.get(LOADING_INDICATOR).should('not.exist'); @@ -280,6 +295,10 @@ export const executeTimelineKQL = (query: string) => { cy.get(`${SEARCH_OR_FILTER_CONTAINER} textarea`).type(`${query} {enter}`); }; +export const executeTimelineSearch = (query: string) => { + cy.get(TIMELINE_QUERY).type(`${query} {enter}`, { force: true }); +}; + export const expandFirstTimelineEventDetails = () => { cy.get(TOGGLE_TIMELINE_EXPAND_EVENT).first().click({ force: true }); }; diff --git a/x-pack/plugins/security_solution/public/app/deep_links/index.ts b/x-pack/plugins/security_solution/public/app/deep_links/index.ts index 99db764285ab7..170e06742dcb0 100644 --- a/x-pack/plugins/security_solution/public/app/deep_links/index.ts +++ b/x-pack/plugins/security_solution/public/app/deep_links/index.ts @@ -42,7 +42,7 @@ import { NETWORK, OVERVIEW, POLICIES, - ACTION_HISTORY, + RESPONSE_ACTIONS_HISTORY, ENTITY_ANALYTICS, RULES, TIMELINES, @@ -65,7 +65,7 @@ import { NETWORK_PATH, OVERVIEW_PATH, POLICIES_PATH, - ACTION_HISTORY_PATH, + RESPONSE_ACTIONS_HISTORY_PATH, ENTITY_ANALYTICS_PATH, RULES_CREATE_PATH, RULES_PATH, @@ -511,9 +511,9 @@ export const securitySolutionsDeepLinks: SecuritySolutionDeepLink[] = [ path: BLOCKLIST_PATH, }, { - id: SecurityPageName.actionHistory, - title: ACTION_HISTORY, - path: ACTION_HISTORY_PATH, + id: SecurityPageName.responseActionsHistory, + title: RESPONSE_ACTIONS_HISTORY, + path: RESPONSE_ACTIONS_HISTORY_PATH, }, { ...getSecuritySolutionLink('benchmarks'), diff --git a/x-pack/plugins/security_solution/public/app/home/home_navigations.ts b/x-pack/plugins/security_solution/public/app/home/home_navigations.ts index ae7c15c73a4d2..392e89fbbec0b 100644 --- a/x-pack/plugins/security_solution/public/app/home/home_navigations.ts +++ b/x-pack/plugins/security_solution/public/app/home/home_navigations.ts @@ -30,7 +30,7 @@ import { APP_USERS_PATH, APP_KUBERNETES_PATH, APP_LANDING_PATH, - APP_ACTION_HISTORY_PATH, + APP_RESPONSE_ACTIONS_HISTORY_PATH, APP_ENTITY_ANALYTICS_PATH, APP_PATH, } from '../../../common/constants'; @@ -162,10 +162,10 @@ export const navTabs: SecurityNav = { disabled: false, urlKey: 'administration', }, - [SecurityPageName.actionHistory]: { - id: SecurityPageName.actionHistory, - name: i18n.ACTION_HISTORY, - href: APP_ACTION_HISTORY_PATH, + [SecurityPageName.responseActionsHistory]: { + id: SecurityPageName.responseActionsHistory, + name: i18n.RESPONSE_ACTIONS_HISTORY, + href: APP_RESPONSE_ACTIONS_HISTORY_PATH, disabled: false, urlKey: 'administration', }, diff --git a/x-pack/plugins/security_solution/public/app/translations.ts b/x-pack/plugins/security_solution/public/app/translations.ts index 154127f469c96..0e74f701eefdf 100644 --- a/x-pack/plugins/security_solution/public/app/translations.ts +++ b/x-pack/plugins/security_solution/public/app/translations.ts @@ -120,9 +120,12 @@ export const BLOCKLIST = i18n.translate('xpack.securitySolution.navigation.block defaultMessage: 'Blocklist', }); -export const ACTION_HISTORY = i18n.translate('xpack.securitySolution.navigation.actionHistory', { - defaultMessage: 'Action history', -}); +export const RESPONSE_ACTIONS_HISTORY = i18n.translate( + 'xpack.securitySolution.navigation.responseActionsHistory', + { + defaultMessage: 'Response actions history', + } +); export const CREATE_NEW_RULE = i18n.translate('xpack.securitySolution.navigation.newRuleTitle', { defaultMessage: 'Create new rule', 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 c12643a30f943..b6a3995534d1f 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 @@ -5,16 +5,24 @@ * 2.0. */ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { shallow } from 'enzyme'; import React from 'react'; import type { DraggableStateSnapshot, DraggingStyle } from 'react-beautiful-dnd'; -import { waitFor } from '@testing-library/react'; + import '../../mock/match_media'; +import { TimelineId } from '../../../../common/types'; import { mockBrowserFields } from '../../containers/source/mock'; import { TestProviders } from '../../mock'; import { mockDataProviders } from '../../../timelines/components/timeline/data_providers/mock/mock_data_providers'; +import { ROW_RENDERER_BROWSER_EXAMPLE_TIMELINE_ID } from '../../../timelines/components/row_renderers_browser/constants'; import { DragDropContextWrapper } from './drag_drop_context_wrapper'; -import { ConditionalPortal, DraggableWrapper, getStyle } from './draggable_wrapper'; +import { + ConditionalPortal, + disableHoverActions, + DraggableWrapper, + getStyle, +} from './draggable_wrapper'; import { useMountAppended } from '../../utils/use_mount_appended'; jest.mock('../../lib/kibana'); @@ -27,6 +35,26 @@ jest.mock('@elastic/eui', () => { }; }); +const timelineIdsWithHoverActions = [ + undefined, + TimelineId.active, + TimelineId.alternateTest, + TimelineId.casePage, + TimelineId.detectionsPage, + TimelineId.detectionsRulesDetailsPage, + TimelineId.hostsPageEvents, + TimelineId.hostsPageSessions, + TimelineId.kubernetesPageSessions, + TimelineId.networkPageEvents, + TimelineId.test, + TimelineId.usersPageEvents, +]; + +const timelineIdsNoHoverActions = [ + TimelineId.rulePreview, + ROW_RENDERER_BROWSER_EXAMPLE_TIMELINE_ID, +]; + describe('DraggableWrapper', () => { const dataProvider = mockDataProviders[0]; const message = 'draggable wrapper content'; @@ -36,6 +64,15 @@ describe('DraggableWrapper', () => { jest.useFakeTimers(); }); + afterEach(() => { + const portal = document.querySelector('[data-euiportal="true"]'); + if (portal != null) { + portal.innerHTML = ''; + } + + jest.useRealTimers(); + }); + describe('rendering', () => { test('it renders against the snapshot', () => { const wrapper = shallow( @@ -103,6 +140,56 @@ describe('DraggableWrapper', () => { expect(wrapper.find('[data-test-subj="hover-actions-copy-button"]').exists()).toBe(true); }); }); + + timelineIdsWithHoverActions.forEach((timelineId) => { + test(`it renders hover actions (by default) when 'isDraggable' is false and timelineId is '${timelineId}'`, async () => { + const isDraggable = false; + + const { container } = render( + + + message} + timelineId={timelineId} + /> + + + ); + + fireEvent.mouseEnter(container.querySelector('[data-test-subj="withHoverActionsButton"]')!); + + await waitFor(() => { + expect(screen.getByTestId('hover-actions-copy-button')).toBeInTheDocument(); + }); + }); + }); + + timelineIdsNoHoverActions.forEach((timelineId) => { + test(`it does NOT render hover actions when 'isDraggable' is false and timelineId is '${timelineId}'`, async () => { + const isDraggable = false; + + const { container } = render( + + + message} + timelineId={timelineId} + /> + + + ); + + fireEvent.mouseEnter(container.querySelector('[data-test-subj="withHoverActionsButton"]')!); + + await waitFor(() => { + expect(screen.queryByTestId('hover-actions-copy-button')).not.toBeInTheDocument(); + }); + }); + }); }); describe('text truncation styling', () => { @@ -192,4 +279,18 @@ describe('ConditionalPortal', () => { expect(getStyle(style, snapshot)).toHaveProperty('transitionDuration', '0.00000001s'); }); }); + + describe('disableHoverActions', () => { + timelineIdsNoHoverActions.forEach((timelineId) => + test(`it returns true when timelineId is ${timelineId}`, () => { + expect(disableHoverActions(timelineId)).toBe(true); + }) + ); + + timelineIdsWithHoverActions.forEach((timelineId) => + test(`it returns false when timelineId is ${timelineId}`, () => { + expect(disableHoverActions(timelineId)).toBe(false); + }) + ); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.tsx index f972bcf463b5b..887f1635c08c6 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.tsx @@ -18,6 +18,7 @@ import { Draggable, Droppable } from 'react-beautiful-dnd'; import { useDispatch } from 'react-redux'; import styled from 'styled-components'; +import { TimelineId } from '../../../../common/types'; import { dragAndDropActions } from '../../store/drag_and_drop'; import type { DataProvider } from '../../../timelines/components/timeline/data_providers/data_provider'; import { ROW_RENDERER_BROWSER_EXAMPLE_TIMELINE_ID } from '../../../timelines/components/row_renderers_browser/constants'; @@ -108,6 +109,9 @@ interface Props { onFilterAdded?: () => void; } +export const disableHoverActions = (timelineId: string | undefined): boolean => + [TimelineId.rulePreview, ROW_RENDERER_BROWSER_EXAMPLE_TIMELINE_ID].includes(timelineId ?? ''); + /** * Wraps a draggable component to handle registration / unregistration of the * data provider associated with the item being dropped @@ -370,7 +374,7 @@ const DraggableWrapperComponent: React.FC = ({ diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/cti_details/host_risk_summary.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/cti_details/host_risk_summary.tsx index 369122aef39d8..68d2d9a65157e 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/cti_details/host_risk_summary.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/cti_details/host_risk_summary.tsx @@ -41,7 +41,6 @@ const HostRiskSummaryComponent: React.FC<{ values={{ hostRiskScoreDocumentationLink: ( ({ })); const useIsExperimentalFeatureEnabledMock = useIsExperimentalFeatureEnabled as jest.Mock; -const data: TimelineEventsDetailsItem[] = [ +const dataWithoutAgentType: TimelineEventsDetailsItem[] = [ { category: 'process', field: 'process.entity_id', @@ -82,6 +82,16 @@ const data: TimelineEventsDetailsItem[] = [ }, ]; +const data: TimelineEventsDetailsItem[] = [ + ...dataWithoutAgentType, + { + category: 'agent', + field: 'agent.type', + isObjectArray: false, + values: ['endpoint'], + }, +]; + describe('Insights', () => { beforeEach(() => { mockUseGetUserCasesPermissions.mockReturnValue(noCasesPermissions()); @@ -123,9 +133,11 @@ describe('Insights', () => { describe('with feature flag enabled', () => { describe('with platinum license', () => { - it('should show insights for related alerts by process ancestry', () => { + beforeAll(() => { licenseServiceMock.isPlatinumPlus.mockReturnValue(true); + }); + it('should show insights for related alerts by process ancestry', () => { render( @@ -137,6 +149,23 @@ describe('Insights', () => { screen.queryByRole('link', { name: new RegExp(i18n.ALERT_UPSELL) }) ).not.toBeInTheDocument(); }); + + describe('without process ancestry info', () => { + it('should not show the related alerts by process ancestry insights module', () => { + render( + + + + ); + + expect(screen.queryByTestId('related-alerts-by-ancestry')).not.toBeInTheDocument(); + }); + }); }); describe('without platinum license', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/insights/insights.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/insights/insights.tsx index 358b2d8833a63..520f30fb9c31d 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/insights/insights.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/insights/insights.tsx @@ -40,7 +40,6 @@ export const Insights = React.memo( 'insightsRelatedAlertsByProcessAncestry' ); const hasAtLeastPlatinum = useLicense().isPlatinumPlus(); - const processEntityField = find({ category: 'process', field: 'process.entity_id' }, data); const originalDocumentId = find( { category: 'kibana', field: 'kibana.alert.ancestors.id' }, data @@ -49,7 +48,12 @@ export const Insights = React.memo( { category: 'kibana', field: 'kibana.alert.rule.parameters.index' }, data ); - const hasProcessEntityInfo = hasData(processEntityField); + const agentTypeField = find({ category: 'agent', field: 'agent.type' }, data); + const eventModuleField = find({ category: 'event', field: 'event.module' }, data); + const processEntityField = find({ category: 'process', field: 'process.entity_id' }, data); + const hasProcessEntityInfo = + hasData(processEntityField) && + hasCorrectAgentTypeAndEventModule(agentTypeField, eventModuleField); const processSessionField = find( { category: 'process', field: 'process.entry_leader.entity_id' }, @@ -147,4 +151,17 @@ export const Insights = React.memo( } ); +function hasCorrectAgentTypeAndEventModule( + agentTypeField?: TimelineEventsDetailsItem, + eventModuleField?: TimelineEventsDetailsItem +): boolean { + return ( + hasData(agentTypeField) && + (agentTypeField.values[0] === 'endpoint' || + (agentTypeField.values[0] === 'winlogbeat' && + hasData(eventModuleField) && + eventModuleField.values[0] === 'sysmon')) + ); +} + Insights.displayName = 'Insights'; diff --git a/x-pack/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx b/x-pack/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx index 2058cd4a7c614..0b13363a653a0 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx @@ -14,6 +14,12 @@ import type { EventsQueryTabBodyComponentProps } from './events_query_tab_body'; import { EventsQueryTabBody, ALERTS_EVENTS_HISTOGRAM_ID } from './events_query_tab_body'; import { useGlobalFullScreen } from '../../containers/use_full_screen'; import * as tGridActions from '@kbn/timelines-plugin/public/store/t_grid/actions'; +import { licenseService } from '../../hooks/use_license'; + +const mockGetDefaultControlColumn = jest.fn(); +jest.mock('../../../timelines/components/timeline/body/control_columns', () => ({ + getDefaultControlColumn: (props: number) => mockGetDefaultControlColumn(props), +})); jest.mock('../../lib/kibana', () => { const original = jest.requireActual('../../lib/kibana'); @@ -47,6 +53,19 @@ jest.mock('../../containers/use_full_screen', () => ({ }), })); +jest.mock('../../hooks/use_license', () => { + const licenseServiceInstance = { + isPlatinumPlus: jest.fn(), + isEnterprise: jest.fn(() => false), + }; + return { + licenseService: licenseServiceInstance, + useLicense: () => { + return licenseServiceInstance; + }, + }; +}); + describe('EventsQueryTabBody', () => { const commonProps: EventsQueryTabBodyComponentProps = { indexNames: ['test-index'], @@ -69,6 +88,7 @@ describe('EventsQueryTabBody', () => { ); expect(queryByText('MockedStatefulEventsViewer')).toBeInTheDocument(); + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(4); }); it('renders the matrix histogram when globalFullScreen is false', () => { @@ -147,4 +167,28 @@ describe('EventsQueryTabBody', () => { expect(spy).toHaveBeenCalled(); }); + + it('only have 4 columns on Action bar for non-Enterprise user', () => { + render( + + + + ); + + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(4); + }); + + it('shows 5 columns on Action bar for Enterprise user', () => { + const licenseServiceMock = licenseService as jest.Mocked; + + licenseServiceMock.isEnterprise.mockReturnValue(true); + + render( + + + + ); + + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(5); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/index.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/index.tsx index 7b96f3886159c..0d0143eab2e32 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/index.tsx @@ -29,7 +29,7 @@ import { LabelField } from './label_field'; import OsqueryLogo from './osquery_icon/osquery.svg'; import { OsqueryFlyout } from '../../../../../detections/components/osquery/osquery_flyout'; import { BasicAlertDataContext } from '../../../event_details/investigation_guide_view'; -import { convertECSMappingToObject } from './utils'; +import { OsqueryNotAvailablePrompt } from './not_available_prompt'; const StyledEuiButton = styled(EuiButton)` > span > img { @@ -49,7 +49,12 @@ const OsqueryEditorComponent = ({ }; }>) => { const isEditMode = node != null; - const { osquery } = useKibana().services; + const { + osquery, + application: { + capabilities: { osquery: osqueryPermissions }, + }, + } = useKibana().services; const formMethods = useForm<{ label: string; query: string; @@ -70,7 +75,7 @@ const OsqueryEditorComponent = ({ { query: data.query, label: data.label, - ecs_mapping: convertECSMappingToObject(data.ecs_mapping), + ecs_mapping: data.ecs_mapping, }, (value) => !isEmpty(value) ) @@ -83,6 +88,17 @@ const OsqueryEditorComponent = ({ [onSave] ); + const noOsqueryPermissions = useMemo( + () => + (!osqueryPermissions.runSavedQueries || !osqueryPermissions.readSavedQueries) && + !osqueryPermissions.writeLiveQueries, + [ + osqueryPermissions.readSavedQueries, + osqueryPermissions.runSavedQueries, + osqueryPermissions.writeLiveQueries, + ] + ); + const OsqueryActionForm = useMemo(() => { if (osquery?.LiveQueryField) { const { LiveQueryField } = osquery; @@ -98,6 +114,10 @@ const OsqueryEditorComponent = ({ return null; }, [formMethods, osquery]); + if (noOsqueryPermissions) { + return ; + } + return ( <> diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/not_available_prompt.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/not_available_prompt.tsx new file mode 100644 index 0000000000000..90db73811bd4f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/not_available_prompt.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiCode, EuiEmptyPrompt } from '@elastic/eui'; +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n-react'; + +import { i18n } from '@kbn/i18n'; + +export const PERMISSION_DENIED = i18n.translate( + 'xpack.securitySolution.markdown.osquery.permissionDenied', + { + defaultMessage: 'Permission denied', + } +); + +export const OsqueryNotAvailablePrompt = () => ( + {PERMISSION_DENIED}} + titleSize="xs" + body={ +

+ {'osquery'}, + }} + /> +

+ } + /> +); diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/utils.ts b/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/utils.ts deleted file mode 100644 index 77e2f14c51420..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins/osquery/utils.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { isEmpty, reduce } from 'lodash'; - -export const convertECSMappingToObject = ( - ecsMapping: Array<{ - key: string; - result: { - type: string; - value: string; - }; - }> -) => - reduce( - ecsMapping, - (acc, value) => { - if (!isEmpty(value?.key) && !isEmpty(value.result?.type) && !isEmpty(value.result?.value)) { - acc[value.key] = { - [value.result.type]: value.result.value, - }; - } - - return acc; - }, - {} as Record - ); 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 84341f5321169..ebfae21d5a5e5 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 @@ -68,7 +68,7 @@ export interface NavTab { } export const securityNavKeys = [ SecurityPageName.alerts, - SecurityPageName.actionHistory, + SecurityPageName.responseActionsHistory, SecurityPageName.blocklist, SecurityPageName.detectionAndResponse, SecurityPageName.case, diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/__snapshots__/index.test.tsx.snap index 613171d5da894..ec824632e1aee 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/__snapshots__/index.test.tsx.snap @@ -251,13 +251,13 @@ Object { "onClick": [Function], }, Object { - "data-href": "securitySolutionUI/action_history", - "data-test-subj": "navigation-action_history", + "data-href": "securitySolutionUI/response_actions_history", + "data-test-subj": "navigation-response_actions_history", "disabled": false, - "href": "securitySolutionUI/action_history", - "id": "action_history", + "href": "securitySolutionUI/response_actions_history", + "id": "response_actions_history", "isSelected": false, - "name": "Action history", + "name": "Response actions history", "onClick": [Function], }, Object { diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.tsx index 3a010bdb4fd7a..0444b183e9425 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.tsx @@ -31,9 +31,6 @@ export const useSecuritySolutionNavigation = () => { const disabledNavTabs = [ ...(!useIsExperimentalFeatureEnabled('kubernetesEnabled') ? ['kubernetes'] : []), - ...(!useIsExperimentalFeatureEnabled('threatIntelligenceEnabled') - ? ['threat-intelligence'] - : []), ]; const enabledNavTabs: GenericNavRecord = omit(disabledNavTabs, navTabs); diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/use_navigation_items.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/use_navigation_items.tsx index dfef46f35a237..dc15e371ba630 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/use_navigation_items.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/use_navigation_items.tsx @@ -138,7 +138,7 @@ function usePrimaryNavigationItemsToDisplay(navTabs: Record) { ? [navTabs[SecurityPageName.hostIsolationExceptions]] : []), navTabs[SecurityPageName.blocklist], - navTabs[SecurityPageName.actionHistory], + navTabs[SecurityPageName.responseActionsHistory], navTabs[SecurityPageName.cloudSecurityPostureBenchmarks], ], }, diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/host_risk_score_disabled.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/host_risk_score_disabled.tsx index 4911aa396c0e1..a7b8cf050de61 100644 --- a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/host_risk_score_disabled.tsx +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/host_risk_score_disabled.tsx @@ -38,7 +38,7 @@ const EntityAnalyticsHostRiskScoreDisableComponent = ({ body={ <> {i18n.ENABLE_HOST_RISK_SCORE_DESCRIPTION}{' '} - + } actions={ diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/user_risk_score.disabled.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/user_risk_score.disabled.tsx index 769be20fc362c..5649c9698e361 100644 --- a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/user_risk_score.disabled.tsx +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_disabled/user_risk_score.disabled.tsx @@ -38,7 +38,7 @@ const EntityAnalyticsUserRiskScoreDisableComponent = ({ body={ <> {i18n.ENABLE_USER_RISK_SCORE_DESCRIPTION}{' '} - + } actions={ diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_doc_link.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_doc_link.tsx index 78d01879a780f..340f63e71bc74 100644 --- a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_doc_link.tsx +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_doc_link.tsx @@ -7,35 +7,22 @@ import { EuiLink } from '@elastic/eui'; import React from 'react'; -import { - RISKY_HOSTS_DOC_LINK, - RISKY_HOSTS_EXTERNAL_DOC_LINK, - RISKY_USERS_DOC_LINK, - RISKY_USERS_EXTERNAL_DOC_LINK, -} from '../../../../../common/constants'; +import { RISKY_HOSTS_DOC_LINK, RISKY_USERS_DOC_LINK } from '../../../../../common/constants'; import { RiskScoreEntity } from '../../../../../common/search_strategy'; import { LEARN_MORE } from '../../../../overview/components/entity_analytics/host_risk_score/translations'; const RiskScoreDocLinkComponent = ({ - external, riskScoreEntity, title, }: { - external: boolean; riskScoreEntity: RiskScoreEntity; title?: string | React.ReactNode; }) => { - const externalLink = - riskScoreEntity === RiskScoreEntity.user - ? RISKY_USERS_EXTERNAL_DOC_LINK - : RISKY_HOSTS_EXTERNAL_DOC_LINK; - const docLink = riskScoreEntity === RiskScoreEntity.user ? RISKY_USERS_DOC_LINK : RISKY_HOSTS_DOC_LINK; - const link = external ? externalLink : docLink; return ( - + {title ? title : LEARN_MORE} ); diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected.tsx index 3f406afeebf40..b492ee51e42af 100644 --- a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected.tsx +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected.tsx @@ -5,15 +5,23 @@ * 2.0. */ -import { EuiEmptyPrompt, EuiPanel } from '@elastic/eui'; +import { EuiEmptyPrompt, EuiPanel, EuiToolTip } from '@elastic/eui'; import React, { useMemo } from 'react'; import { RiskScoreEntity } from '../../../../../common/search_strategy'; import { HeaderSection } from '../../header_section'; import * as i18n from './translations'; import { RiskScoreHeaderTitle } from './risk_score_header_title'; +import { RiskScoreRestartButton } from './risk_score_restart_button'; +import type { inputsModel } from '../../../store'; -const RiskScoresNoDataDetectedComponent = ({ entityType }: { entityType: RiskScoreEntity }) => { +const RiskScoresNoDataDetectedComponent = ({ + entityType, + refetch, +}: { + entityType: RiskScoreEntity; + refetch: inputsModel.Refetch; +}) => { const translations = useMemo( () => ({ title: @@ -26,7 +34,15 @@ const RiskScoresNoDataDetectedComponent = ({ entityType }: { entityType: RiskSco return ( } titleSize="s" /> - {translations.title}} body={translations.body} /> + {translations.title}} + body={translations.body} + actions={ + + + + } + /> ); }; diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.test.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.test.tsx new file mode 100644 index 0000000000000..16269911f6632 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.test.tsx @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { act, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import React from 'react'; +import { RiskScoreEntity } from '../../../../../common/search_strategy'; +import { TestProviders } from '../../../mock/test_providers'; +import { RiskScoreRestartButton } from './risk_score_restart_button'; + +import { restartRiskScoreTransforms } from './utils'; + +jest.mock('./utils'); + +describe('RiskScoreRestartButton', () => { + const mockRefetch = jest.fn(); + beforeEach(() => { + jest.clearAllMocks(); + }); + describe.each([[RiskScoreEntity.host], [RiskScoreEntity.user]])('%s', (riskScoreEntity) => { + it('Renders expected children', () => { + render( + + + + ); + + expect(screen.getByTestId(`restart_${riskScoreEntity}_risk_score`)).toHaveTextContent( + 'Restart' + ); + }); + + it('calls restartRiskScoreTransforms', async () => { + render( + + + + ); + + await act(async () => { + await userEvent.click(screen.getByTestId(`restart_${riskScoreEntity}_risk_score`)); + }); + + expect(restartRiskScoreTransforms).toHaveBeenCalled(); + }); + + it('Update button state while installing', async () => { + render( + + + + ); + + userEvent.click(screen.getByTestId(`restart_${riskScoreEntity}_risk_score`)); + + await waitFor(() => { + expect(screen.getByTestId(`restart_${riskScoreEntity}_risk_score`)).toHaveProperty( + 'disabled', + true + ); + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.tsx new file mode 100644 index 0000000000000..679bbe38c8181 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_restart_button.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiButton } from '@elastic/eui'; +import React, { useCallback } from 'react'; +import { FormattedMessage } from '@kbn/i18n-react'; + +import { RiskScoreEntity } from '../../../../../common/search_strategy'; +import { useSpaceId } from '../../../hooks/use_space_id'; +import { useKibana } from '../../../lib/kibana'; +import type { inputsModel } from '../../../store'; +import { REQUEST_NAMES, useFetch } from '../../../hooks/use_fetch'; +import { useRiskScoreToastContent } from './use_risk_score_toast_content'; +import { restartRiskScoreTransforms } from './utils'; + +const RiskScoreRestartButtonComponent = ({ + refetch, + riskScoreEntity, +}: { + refetch: inputsModel.Refetch; + riskScoreEntity: RiskScoreEntity; +}) => { + const { fetch, isLoading } = useFetch( + REQUEST_NAMES.REFRESH_RISK_SCORE, + restartRiskScoreTransforms + ); + + const spaceId = useSpaceId(); + const { renderDocLink } = useRiskScoreToastContent(riskScoreEntity); + const { http, notifications, theme } = useKibana().services; + + const onClick = useCallback(async () => { + fetch({ + http, + notifications, + refetch, + renderDocLink, + riskScoreEntity: RiskScoreEntity.host, + spaceId, + theme, + }); + }, [fetch, http, notifications, refetch, renderDocLink, spaceId, theme]); + + return ( + + + + ); +}; + +export const RiskScoreRestartButton = React.memo(RiskScoreRestartButtonComponent); +RiskScoreRestartButton.displayName = 'RiskScoreRestartButton'; diff --git a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_upgrade_button.tsx b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_upgrade_button.tsx index 6f79950a65040..6ed805850ce23 100644 --- a/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_upgrade_button.tsx +++ b/x-pack/plugins/security_solution/public/common/components/risk_score/risk_score_onboarding/risk_score_upgrade_button.tsx @@ -94,7 +94,6 @@ const RiskScoreUpgradeButtonComponent = ({ onConfirm={upgradeRiskScore} cancelButtonText={ { const renderDocLink = useCallback( (message: string) => ( <> - {message} + {message} ), [riskScoreEntity] diff --git a/x-pack/plugins/security_solution/public/common/components/sessions_viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/sessions_viewer/index.test.tsx index a89a618972326..47a1bc4fa6514 100644 --- a/x-pack/plugins/security_solution/public/common/components/sessions_viewer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/sessions_viewer/index.test.tsx @@ -14,6 +14,7 @@ import { TimelineId } from '@kbn/timelines-plugin/common'; import type { SessionsComponentsProps } from './types'; import type { TimelineModel } from '../../../timelines/store/timeline/model'; import { useGetUserCasesPermissions } from '../../lib/kibana'; +import { licenseService } from '../../hooks/use_license'; jest.mock('../../lib/kibana'); @@ -47,10 +48,28 @@ type Props = Partial & { entityType: EntityType; }; +const mockGetDefaultControlColumn = jest.fn(); +jest.mock('../../../timelines/components/timeline/body/control_columns', () => ({ + getDefaultControlColumn: (props: number) => mockGetDefaultControlColumn(props), +})); + const TEST_PREFIX = 'security_solution:sessions_viewer:sessions_view'; const callFilters = jest.fn(); +jest.mock('../../hooks/use_license', () => { + const licenseServiceInstance = { + isPlatinumPlus: jest.fn(), + isEnterprise: jest.fn(() => false), + }; + return { + licenseService: licenseServiceInstance, + useLicense: () => { + return licenseServiceInstance; + }, + }; +}); + // creating a dummy component for testing TGrid to avoid mocking all the implementation details // but still test if the TGrid will render properly const SessionsViewerTGrid: React.FC = ({ columns, start, end, id, filters, entityType }) => { @@ -144,4 +163,42 @@ describe('SessionsView', () => { ]); }); }); + it('Action tab should have 4 columns for non Enterprise users', async () => { + render( + + + + ); + + await waitFor(() => { + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(4); + }); + }); + + it('Action tab should have 5 columns for Enterprise or above users', async () => { + const licenseServiceMock = licenseService as jest.Mocked; + + licenseServiceMock.isEnterprise.mockReturnValue(true); + render( + + + + ); + + await waitFor(() => { + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(5); + }); + }); + + it('Action tab should have 5 columns when accessed via K8S dahsboard', async () => { + render( + + + + ); + + await waitFor(() => { + expect(mockGetDefaultControlColumn).toHaveBeenCalledWith(5); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.test.ts b/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.test.ts index c499861e6abfb..a0d23820025b8 100644 --- a/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.test.ts @@ -7,15 +7,19 @@ import type { RenderHookResult, RenderResult } from '@testing-library/react-hooks'; import { act, renderHook } from '@testing-library/react-hooks'; -import { useCurrentUser, useKibana } from '../../../lib/kibana'; -import { useEndpointPrivileges } from './use_endpoint_privileges'; + import { securityMock } from '@kbn/security-plugin/public/mocks'; import type { AuthenticatedUser } from '@kbn/security-plugin/common'; +import { createFleetAuthzMock } from '@kbn/fleet-plugin/common'; + +import type { EndpointPrivileges } from '../../../../../common/endpoint/types'; +import { useCurrentUser, useKibana } from '../../../lib/kibana'; import { licenseService } from '../../../hooks/use_license'; +import { useEndpointPrivileges } from './use_endpoint_privileges'; import { getEndpointPrivilegesInitialStateMock } from './mocks'; -import type { EndpointPrivileges } from '../../../../../common/endpoint/types'; import { getEndpointPrivilegesInitialState } from './utils'; +const useKibanaMock = useKibana as jest.Mocked; jest.mock('../../../lib/kibana'); jest.mock('../../../hooks/use_license', () => { const licenseServiceInstance = { @@ -29,6 +33,9 @@ jest.mock('../../../hooks/use_license', () => { }, }; }); +jest.mock('../../../hooks/use_experimental_features', () => ({ + useIsExperimentalFeatureEnabled: jest.fn((feature: string) => feature === 'endpointRbacEnabled'), +})); const licenseServiceMock = licenseService as jest.Mocked; @@ -44,6 +51,7 @@ describe('When using useEndpointPrivileges hook', () => { }); (useCurrentUser as jest.Mock).mockReturnValue(authenticatedUser); + useKibanaMock().services.fleet!.authz = createFleetAuthzMock(); licenseServiceMock.isPlatinumPlus.mockReturnValue(true); diff --git a/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.ts b/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.ts index d0a1057d9f00e..7d7233312fecc 100644 --- a/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.ts +++ b/x-pack/plugins/security_solution/public/common/components/user_privileges/endpoint/use_endpoint_privileges.ts @@ -19,6 +19,7 @@ import { getEndpointAuthzInitialState, } from '../../../../../common/endpoint/service/authz'; import { useSecuritySolutionStartDependencies } from './security_solution_start_dependencies'; +import { useIsExperimentalFeatureEnabled } from '../../../hooks/use_experimental_features'; /** * Retrieve the endpoint privileges for the current user. @@ -41,17 +42,26 @@ export const useEndpointPrivileges = (): Immutable => { const [userRoles, setUserRoles] = useState>([]); const fleetServices = fleetServicesFromUseKibana ?? fleetServicesFromPluginStart; + const isEndpointRbacEnabled = useIsExperimentalFeatureEnabled('endpointRbacEnabled'); const privileges = useMemo(() => { const privilegeList: EndpointPrivileges = Object.freeze({ loading: !fleetCheckDone || !userRolesCheckDone || !user, ...(fleetAuthz - ? calculateEndpointAuthz(licenseService, fleetAuthz, userRoles) + ? calculateEndpointAuthz(licenseService, fleetAuthz, userRoles, isEndpointRbacEnabled) : getEndpointAuthzInitialState()), }); return privilegeList; - }, [fleetCheckDone, userRolesCheckDone, user, fleetAuthz, licenseService, userRoles]); + }, [ + fleetCheckDone, + userRolesCheckDone, + user, + fleetAuthz, + licenseService, + userRoles, + isEndpointRbacEnabled, + ]); // Check if user can access fleet useEffect(() => { diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/authentication.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/authentication.test.ts.snap new file mode 100644 index 0000000000000..747487203066b --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/authentication.test.ts.snap @@ -0,0 +1,276 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`authenticationLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-3fd0c5d5-f762-4a27-8c56-14eee0223e13", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-bef502be-e5ff-442f-9e3e-229f86ca2afa", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "6f4dbdc7-35b6-4e20-ac53-1272167e3919", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "3fd0c5d5-f762-4a27-8c56-14eee0223e13": Object { + "columnOrder": Array [ + "b41a2958-650b-470a-84c4-c6fd8f0c6d37", + "5417777d-d9d9-4268-9cdc-eb29b873bd65", + ], + "columns": Object { + "5417777d-d9d9-4268-9cdc-eb29b873bd65": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome : \\"success\\"", + }, + "isBucketed": false, + "label": "Success", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "b41a2958-650b-470a-84c4-c6fd8f0c6d37": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + "bef502be-e5ff-442f-9e3e-229f86ca2afa": Object { + "columnOrder": Array [ + "cded27f7-8ef8-458c-8d9b-70db48ae340d", + "a3bf9dc1-c8d2-42d6-9e60-31892a4c509e", + ], + "columns": Object { + "a3bf9dc1-c8d2-42d6-9e60-31892a4c509e": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome : \\"failure\\"", + }, + "isBucketed": false, + "label": "Failure", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "cded27f7-8ef8-458c-8d9b-70db48ae340d": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "6f4dbdc7-35b6-4e20-ac53-1272167e3919", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"must\\":[{\\"term\\":{\\"event.category\\":\\"authentication\\"}}]}}", + }, + "query": Object { + "bool": Object { + "must": Array [ + Object { + "term": Object { + "event.category": "authentication", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "layers": Array [ + Object { + "accessors": Array [ + "5417777d-d9d9-4268-9cdc-eb29b873bd65", + ], + "layerId": "3fd0c5d5-f762-4a27-8c56-14eee0223e13", + "layerType": "data", + "position": "top", + "seriesType": "bar_stacked", + "showGridlines": false, + "xAccessor": "b41a2958-650b-470a-84c4-c6fd8f0c6d37", + "yConfig": Array [ + Object { + "color": "#54b399", + "forAccessor": "5417777d-d9d9-4268-9cdc-eb29b873bd65", + }, + ], + }, + Object { + "accessors": Array [ + "a3bf9dc1-c8d2-42d6-9e60-31892a4c509e", + ], + "layerId": "bef502be-e5ff-442f-9e3e-229f86ca2afa", + "layerType": "data", + "seriesType": "bar_stacked", + "xAccessor": "cded27f7-8ef8-458c-8d9b-70db48ae340d", + "yConfig": Array [ + Object { + "color": "#da8b45", + "forAccessor": "a3bf9dc1-c8d2-42d6-9e60-31892a4c509e", + }, + ], + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "bar_stacked", + "title": "Empty XY chart", + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "Authentication", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/external_alert.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/external_alert.test.ts.snap new file mode 100644 index 0000000000000..ac42b228012fe --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/__snapshots__/external_alert.test.ts.snap @@ -0,0 +1,231 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`getExternalAlertLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-a3c54471-615f-4ff9-9fda-69b5b2ea3eef", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "723c4653-681b-4105-956e-abef287bf025", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "a04472fc-94a3-4b8d-ae05-9d30ea8fbd6a", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "a3c54471-615f-4ff9-9fda-69b5b2ea3eef": Object { + "columnOrder": Array [ + "42334c6e-98d9-47a2-b4cb-a445abb44c93", + "37bdf546-3c11-4b08-8c5d-e37debc44f1d", + "0a923af2-c880-4aa3-aa93-a0b9c2801f6d", + ], + "columns": Object { + "0a923af2-c880-4aa3-aa93-a0b9c2801f6d": Object { + "dataType": "number", + "isBucketed": false, + "label": "Count of records", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "37bdf546-3c11-4b08-8c5d-e37debc44f1d": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "42334c6e-98d9-47a2-b4cb-a445abb44c93": Object { + "dataType": "string", + "isBucketed": true, + "label": "Top values of event.dataset", + "operationType": "terms", + "params": Object { + "missingBucket": false, + "orderBy": Object { + "columnId": "0a923af2-c880-4aa3-aa93-a0b9c2801f6d", + "type": "column", + }, + "orderDirection": "desc", + "otherBucket": true, + "parentFormat": Object { + "id": "terms", + }, + "size": 10, + }, + "scale": "ordinal", + "sourceField": "event.dataset", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "a04472fc-94a3-4b8d-ae05-9d30ea8fbd6a", + "key": "event.kind", + "negate": false, + "params": Object { + "query": "alert", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "event.kind": "alert", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "layers": Array [ + Object { + "accessors": Array [ + "0a923af2-c880-4aa3-aa93-a0b9c2801f6d", + ], + "layerId": "a3c54471-615f-4ff9-9fda-69b5b2ea3eef", + "layerType": "data", + "position": "top", + "seriesType": "bar_stacked", + "showGridlines": false, + "splitAccessor": "42334c6e-98d9-47a2-b4cb-a445abb44c93", + "xAccessor": "37bdf546-3c11-4b08-8c5d-e37debc44f1d", + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "bar_stacked", + "title": "Empty XY chart", + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "External alerts", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.test.ts new file mode 100644 index 0000000000000..808789db397e9 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { authenticationLensAttributes } from './authentication'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('authenticationLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: authenticationLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.ts index 199f78d372cd8..15d7f029ae612 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/authentication.ts @@ -5,6 +5,10 @@ * 2.0. */ +import { + AUTHENCICATION_FAILURE_CHART_LABEL, + AUTHENCICATION_SUCCESS_CHART_LABEL, +} from '../../translations'; import type { LensAttributes } from '../../types'; export const authenticationLensAttributes: LensAttributes = { @@ -110,7 +114,7 @@ export const authenticationLensAttributes: LensAttributes = { }, }, '5417777d-d9d9-4268-9cdc-eb29b873bd65': { - label: 'Success', + label: AUTHENCICATION_SUCCESS_CHART_LABEL, dataType: 'number', operationType: 'count', isBucketed: false, @@ -143,7 +147,7 @@ export const authenticationLensAttributes: LensAttributes = { }, }, 'a3bf9dc1-c8d2-42d6-9e60-31892a4c509e': { - label: 'Failure', + label: AUTHENCICATION_FAILURE_CHART_LABEL, dataType: 'number', operationType: 'count', isBucketed: false, diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.test.ts new file mode 100644 index 0000000000000..da890c4d49fe0 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { getExternalAlertLensAttributes } from './external_alert'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('getExternalAlertLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + getLensAttributes: getExternalAlertLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.ts index e24db03b3302f..a815d442b043e 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/common/external_alert.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { COUNT, TOP_VALUE } from '../../translations'; import type { GetLensAttributes, LensAttributes } from '../../types'; export const getExternalAlertLensAttributes: GetLensAttributes = ( @@ -86,7 +87,7 @@ export const getExternalAlertLensAttributes: GetLensAttributes = ( }, }, '0a923af2-c880-4aa3-aa93-a0b9c2801f6d': { - label: 'Count of records', + label: COUNT, dataType: 'number', operationType: 'count', isBucketed: false, @@ -94,7 +95,7 @@ export const getExternalAlertLensAttributes: GetLensAttributes = ( sourceField: '___records___', }, '42334c6e-98d9-47a2-b4cb-a445abb44c93': { - label: `Top values of ${stackByField}`, // could be event.category + label: TOP_VALUE(`${stackByField}`), // could be event.category dataType: 'string', operationType: 'terms', scale: 'ordinal', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/event.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/event.test.ts.snap new file mode 100644 index 0000000000000..7f3fdb6c66107 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/event.test.ts.snap @@ -0,0 +1,205 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`getEventsHistogramLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-0039eb0c-9a1a-4687-ae54-0f4e239bec75", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "0039eb0c-9a1a-4687-ae54-0f4e239bec75": Object { + "columnOrder": Array [ + "34919782-4546-43a5-b668-06ac934d3acd", + "aac9d7d0-13a3-480a-892b-08207a787926", + "e09e0380-0740-4105-becc-0a4ca12e3944", + ], + "columns": Object { + "34919782-4546-43a5-b668-06ac934d3acd": Object { + "dataType": "string", + "isBucketed": true, + "label": "Top values of event.dataset", + "operationType": "terms", + "params": Object { + "missingBucket": false, + "orderBy": Object { + "columnId": "e09e0380-0740-4105-becc-0a4ca12e3944", + "type": "column", + }, + "orderDirection": "asc", + "otherBucket": true, + "parentFormat": Object { + "id": "terms", + }, + "size": 10, + }, + "scale": "ordinal", + "sourceField": "event.dataset", + }, + "aac9d7d0-13a3-480a-892b-08207a787926": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "e09e0380-0740-4105-becc-0a4ca12e3944": Object { + "dataType": "number", + "isBucketed": false, + "label": "Count of records", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "layers": Array [ + Object { + "accessors": Array [ + "e09e0380-0740-4105-becc-0a4ca12e3944", + ], + "layerId": "0039eb0c-9a1a-4687-ae54-0f4e239bec75", + "layerType": "data", + "position": "top", + "seriesType": "bar_stacked", + "showGridlines": false, + "splitAccessor": "34919782-4546-43a5-b668-06ac934d3acd", + "xAccessor": "aac9d7d0-13a3-480a-892b-08207a787926", + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "bar_stacked", + "title": "Empty XY chart", + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "Host - events", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_area.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_area.test.ts.snap new file mode 100644 index 0000000000000..c5e4e272ec9c4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_area.test.ts.snap @@ -0,0 +1,196 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiHostAreaLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-416b6fad-1923-4f6a-a2df-b223bb287e30", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "416b6fad-1923-4f6a-a2df-b223bb287e30": Object { + "columnOrder": Array [ + "5eea817b-67b7-4268-8ecb-7688d1094721", + "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + ], + "columns": Object { + "5eea817b-67b7-4268-8ecb-7688d1094721": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "b00c65ea-32be-4163-bfc8-f795b1ef9d06": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": "Unique count of host.name", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "host.name", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": false, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + ], + "layerId": "416b6fad-1923-4f6a-a2df-b223bb287e30", + "layerType": "data", + "seriesType": "area", + "xAccessor": "5eea817b-67b7-4268-8ecb-7688d1094721", + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "area", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Host] Hosts - area", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_metric.test.ts.snap new file mode 100644 index 0000000000000..3669de2d30109 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_host_metric.test.ts.snap @@ -0,0 +1,143 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiHostMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-416b6fad-1923-4f6a-a2df-b223bb287e30", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "416b6fad-1923-4f6a-a2df-b223bb287e30": Object { + "columnOrder": Array [ + "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + ], + "columns": Object { + "b00c65ea-32be-4163-bfc8-f795b1ef9d06": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "host.name", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + "layerId": "416b6fad-1923-4f6a-a2df-b223bb287e30", + "layerType": "data", + }, + }, + "title": "[Host] Hosts - metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_area.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_area.test.ts.snap new file mode 100644 index 0000000000000..acaf78556269f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_area.test.ts.snap @@ -0,0 +1,255 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniqueIpsAreaLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-ca05ecdb-0fa4-49a8-9305-b23d91012a46", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "8be0156b-d423-4a39-adf1-f54d4c9f2e69": Object { + "columnOrder": Array [ + "a0cb6400-f708-46c3-ad96-24788f12dae4", + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + ], + "columns": Object { + "a0cb6400-f708-46c3-ad96-24788f12dae4": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": "Src.", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + }, + "incompleteColumns": Object {}, + }, + "ca05ecdb-0fa4-49a8-9305-b23d91012a46": Object { + "columnOrder": Array [ + "f95e74e6-99dd-4b11-8faf-439b4d959df9", + "e7052671-fb9e-481f-8df3-7724c98cfc6f", + ], + "columns": Object { + "e7052671-fb9e-481f-8df3-7724c98cfc6f": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": "Dest.", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + "f95e74e6-99dd-4b11-8faf-439b4d959df9": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + ], + "layerId": "8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "layerType": "data", + "seriesType": "area", + "xAccessor": "a0cb6400-f708-46c3-ad96-24788f12dae4", + "yConfig": Array [ + Object { + "color": "#d36186", + "forAccessor": "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + }, + ], + }, + Object { + "accessors": Array [ + "e7052671-fb9e-481f-8df3-7724c98cfc6f", + ], + "layerId": "ca05ecdb-0fa4-49a8-9305-b23d91012a46", + "layerType": "data", + "seriesType": "area", + "xAccessor": "f95e74e6-99dd-4b11-8faf-439b4d959df9", + "yConfig": Array [ + Object { + "color": "#9170b8", + "forAccessor": "e7052671-fb9e-481f-8df3-7724c98cfc6f", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "area", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Host] Unique IPs - area", + "type": "lens", + "updated_at": "2022-02-09T17:44:03.359Z", + "version": "WzI5MTI5OSwzXQ==", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_bar.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_bar.test.ts.snap new file mode 100644 index 0000000000000..9f702ecb06412 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_bar.test.ts.snap @@ -0,0 +1,265 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniqueIpsBarLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-ec84ba70-2adb-4647-8ef0-8ad91a0e6d4e", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "8be0156b-d423-4a39-adf1-f54d4c9f2e69": Object { + "columnOrder": Array [ + "f8bfa719-5c1c-4bf2-896e-c318d77fc08e", + "32f66676-f4e1-48fd-b7f8-d4de38318601", + ], + "columns": Object { + "32f66676-f4e1-48fd-b7f8-d4de38318601": Object { + "dataType": "number", + "isBucketed": false, + "label": "Unique count of source.ip", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + "f8bfa719-5c1c-4bf2-896e-c318d77fc08e": Object { + "dataType": "string", + "isBucketed": true, + "label": "Filters", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "", + }, + "label": "Src.", + }, + ], + }, + "scale": "ordinal", + }, + }, + "incompleteColumns": Object {}, + }, + "ec84ba70-2adb-4647-8ef0-8ad91a0e6d4e": Object { + "columnOrder": Array [ + "c72aad6a-fc9c-43dc-9194-e13ca3ee8aff", + "b7e59b08-96e6-40d1-84fd-e97b977d1c47", + ], + "columns": Object { + "b7e59b08-96e6-40d1-84fd-e97b977d1c47": Object { + "dataType": "number", + "isBucketed": false, + "label": "Unique count of destination.ip", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + "c72aad6a-fc9c-43dc-9194-e13ca3ee8aff": Object { + "customLabel": true, + "dataType": "string", + "isBucketed": true, + "label": "Dest.", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "", + }, + "label": "Dest.", + }, + ], + }, + "scale": "ordinal", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "32f66676-f4e1-48fd-b7f8-d4de38318601", + ], + "layerId": "8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "layerType": "data", + "seriesType": "bar_horizontal_stacked", + "xAccessor": "f8bfa719-5c1c-4bf2-896e-c318d77fc08e", + "yConfig": Array [ + Object { + "color": "#d36186", + "forAccessor": "32f66676-f4e1-48fd-b7f8-d4de38318601", + }, + ], + }, + Object { + "accessors": Array [ + "b7e59b08-96e6-40d1-84fd-e97b977d1c47", + ], + "layerId": "ec84ba70-2adb-4647-8ef0-8ad91a0e6d4e", + "layerType": "data", + "seriesType": "bar_horizontal_stacked", + "xAccessor": "c72aad6a-fc9c-43dc-9194-e13ca3ee8aff", + "yConfig": Array [ + Object { + "color": "#9170b8", + "forAccessor": "b7e59b08-96e6-40d1-84fd-e97b977d1c47", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "bar_horizontal_stacked", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Host] Unique IPs - bar", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_destination_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_destination_metric.test.ts.snap new file mode 100644 index 0000000000000..ebeb85e27a44f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_destination_metric.test.ts.snap @@ -0,0 +1,143 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniqueIpsDestinationMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "8be0156b-d423-4a39-adf1-f54d4c9f2e69": Object { + "columnOrder": Array [ + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + ], + "columns": Object { + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + "layerId": "8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "layerType": "data", + }, + }, + "title": "[Host] Unique IPs - destination metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_source_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_source_metric.test.ts.snap new file mode 100644 index 0000000000000..f8ec7bb8c70d7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/__snapshots__/kpi_unique_ips_source_metric.test.ts.snap @@ -0,0 +1,143 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniqueIpsSourceMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "8be0156b-d423-4a39-adf1-f54d4c9f2e69": Object { + "columnOrder": Array [ + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + ], + "columns": Object { + "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.name", + "negate": false, + "params": Object { + "query": "mockHost", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.name": "mockHost", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"query\\": {\\"bool\\": {\\"filter\\": [{\\"bool\\": {\\"should\\": [{\\"exists\\": {\\"field\\": \\"host.name\\"}}],\\"minimum_should_match\\": 1}}]}}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "host.name", + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "d9a6eb6b-8b78-439e-98e7-a718f8ffbebe", + "layerId": "8be0156b-d423-4a39-adf1-f54d4c9f2e69", + "layerType": "data", + }, + }, + "title": "[Host] Unique IPs - source metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/event.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/event.test.ts new file mode 100644 index 0000000000000..107b63716f404 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/event.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { getEventsHistogramLensAttributes } from './events'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('getEventsHistogramLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + getLensAttributes: getEventsHistogramLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.test.ts new file mode 100644 index 0000000000000..5248444872942 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiHostAreaLensAttributes } from './kpi_host_area'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiHostAreaLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiHostAreaLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.ts index f4486b77390b2..64f62133e9406 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_area.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { UNIQUE_COUNT } from '../../translations'; import type { LensAttributes } from '../../types'; export const kpiHostAreaLensAttributes: LensAttributes = { @@ -32,7 +33,7 @@ export const kpiHostAreaLensAttributes: LensAttributes = { customLabel: true, dataType: 'number', isBucketed: false, - label: ' ', + label: UNIQUE_COUNT('host.name'), operationType: 'unique_count', scale: 'ratio', sourceField: 'host.name', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.test.ts new file mode 100644 index 0000000000000..06a884c15e4d6 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiHostMetricLensAttributes } from './kpi_host_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiHostMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiHostMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.ts index c5fcae45df0f0..00ab0239acb40 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_host_metric.ts @@ -40,7 +40,7 @@ export const kpiHostMetricLensAttributes: LensAttributes = { }, }, title: '[Host] Hosts - metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_area.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_area.test.ts new file mode 100644 index 0000000000000..63f50b141b5b0 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_area.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniqueIpsAreaLensAttributes } from './kpi_unique_ips_area'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniqueIpsAreaLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniqueIpsAreaLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.test.ts new file mode 100644 index 0000000000000..f04f0de2b8be7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniqueIpsBarLensAttributes } from './kpi_unique_ips_bar'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniqueIpsBarLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniqueIpsBarLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.ts index b55fcb64ba49c..cf7dbf21913b5 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_bar.ts @@ -6,7 +6,7 @@ */ import type { LensAttributes } from '../../types'; -import { SOURCE_CHART_LABEL, DESTINATION_CHART_LABEL } from '../../translations'; +import { SOURCE_CHART_LABEL, DESTINATION_CHART_LABEL, UNIQUE_COUNT } from '../../translations'; export const kpiUniqueIpsBarLensAttributes: LensAttributes = { description: '', @@ -23,7 +23,7 @@ export const kpiUniqueIpsBarLensAttributes: LensAttributes = { '32f66676-f4e1-48fd-b7f8-d4de38318601': { dataType: 'number', isBucketed: false, - label: 'Unique count of source.ip', + label: UNIQUE_COUNT('source.ip'), operationType: 'unique_count', scale: 'ratio', sourceField: 'source.ip', @@ -50,7 +50,7 @@ export const kpiUniqueIpsBarLensAttributes: LensAttributes = { 'b7e59b08-96e6-40d1-84fd-e97b977d1c47': { dataType: 'number', isBucketed: false, - label: 'Unique count of destination.ip', + label: UNIQUE_COUNT('destination.ip'), operationType: 'unique_count', scale: 'ratio', sourceField: 'destination.ip', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.test.ts new file mode 100644 index 0000000000000..9dd67a2d5ab40 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniqueIpsDestinationMetricLensAttributes } from './kpi_unique_ips_destination_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniqueIpsDestinationMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniqueIpsDestinationMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.ts index ae18c08be800c..5c4aa31f65833 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_destination_metric.ts @@ -40,7 +40,7 @@ export const kpiUniqueIpsDestinationMetricLensAttributes: LensAttributes = { }, }, title: '[Host] Unique IPs - destination metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.test.ts new file mode 100644 index 0000000000000..6e69495e63a0e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniqueIpsSourceMetricLensAttributes } from './kpi_unique_ips_source_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'hosts', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniqueIpsSourceMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniqueIpsSourceMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.ts index 8a0b778975ab9..4d308b95d796d 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/hosts/kpi_unique_ips_source_metric.ts @@ -40,7 +40,7 @@ export const kpiUniqueIpsSourceMetricLensAttributes: LensAttributes = { }, }, title: '[Host] Unique IPs - source metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/dns_top_domains.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/dns_top_domains.test.ts.snap new file mode 100644 index 0000000000000..6e0f9c2bbd516 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/dns_top_domains.test.ts.snap @@ -0,0 +1,245 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`dnsTopDomainsLensAttributes should render 1`] = ` +Object { + "description": "Security Solution Network DNS", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-b1c3efc6-c886-4fba-978f-3b6bb5e7948a", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "filter-index-pattern-0", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "b1c3efc6-c886-4fba-978f-3b6bb5e7948a": Object { + "columnOrder": Array [ + "e8842815-2a45-4c74-86de-c19a391e2424", + "d1452b87-0e9e-4fc0-a725-3727a18e0b37", + "2a4d5e20-f570-48e4-b9ab-ff3068919377", + ], + "columns": Object { + "2a4d5e20-f570-48e4-b9ab-ff3068919377": Object { + "dataType": "number", + "isBucketed": false, + "label": "Unique count of dns.question.registered_domain", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "dns.question.registered_domain", + }, + "d1452b87-0e9e-4fc0-a725-3727a18e0b37": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "e8842815-2a45-4c74-86de-c19a391e2424": Object { + "dataType": "string", + "isBucketed": true, + "label": "Top values of dns.question.name", + "operationType": "terms", + "params": Object { + "missingBucket": false, + "orderBy": Object { + "columnId": "2a4d5e20-f570-48e4-b9ab-ff3068919377", + "type": "column", + }, + "orderDirection": "desc", + "otherBucket": true, + "size": 6, + }, + "scale": "ordinal", + "sourceField": "dns.question.name", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "dns.question.type", + "negate": true, + "params": Object { + "query": "PTR", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "dns.question.type": "PTR", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "2a4d5e20-f570-48e4-b9ab-ff3068919377", + ], + "layerId": "b1c3efc6-c886-4fba-978f-3b6bb5e7948a", + "layerType": "data", + "position": "top", + "seriesType": "bar", + "showGridlines": false, + "splitAccessor": "e8842815-2a45-4c74-86de-c19a391e2424", + "xAccessor": "d1452b87-0e9e-4fc0-a725-3727a18e0b37", + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "bar", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "Top domains by dns.question.registered_domain", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_dns_queries.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_dns_queries.test.ts.snap new file mode 100644 index 0000000000000..39f16779abaf4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_dns_queries.test.ts.snap @@ -0,0 +1,189 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiDnsQueriesLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "196d783b-3779-4c39-898e-6606fe633d05", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "cea37c70-8f91-43bf-b9fe-72d8c049f6a3": Object { + "columnOrder": Array [ + "0374e520-eae0-4ac1-bcfe-37565e7fc9e3", + ], + "columns": Object { + "0374e520-eae0-4ac1-bcfe-37565e7fc9e3": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": "", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "196d783b-3779-4c39-898e-6606fe633d05", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\":\\"dns.question.name\\"}},{\\"term\\":{\\"suricata.eve.dns.type\\":{\\"value\\":\\"query\\"}}},{\\"exists\\":{\\"field\\":\\"zeek.dns.query\\"}}],\\"minimum_should_match\\":1}}", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "dns.question.name", + }, + }, + Object { + "term": Object { + "suricata.eve.dns.type": Object { + "value": "query", + }, + }, + }, + Object { + "exists": Object { + "field": "zeek.dns.query", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "0374e520-eae0-4ac1-bcfe-37565e7fc9e3", + "colorMode": "None", + "layerId": "cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "layerType": "data", + }, + }, + "title": "[Network] DNS metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_network_events.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_network_events.test.ts.snap new file mode 100644 index 0000000000000..03bacfac49ad7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_network_events.test.ts.snap @@ -0,0 +1,193 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiNetworkEventsLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-eaadfec7-deaa-4aeb-a403-3b4e516416d2", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "861af17d-be25-45a3-a82d-d6e697b76e51", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "09617767-f732-410e-af53-bebcbd0bf4b9", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "eaadfec7-deaa-4aeb-a403-3b4e516416d2": Object { + "columnOrder": Array [ + "370ebd07-5ce0-4f46-a847-0e363c50d037", + ], + "columns": Object { + "370ebd07-5ce0-4f46-a847-0e363c50d037": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "security-solution-default", + "key": "source.ip", + "negate": false, + "type": "exists", + "value": "exists", + }, + "query": Object { + "exists": Object { + "field": "source.ip", + }, + }, + }, + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "security-solution-default", + "key": "destination.ip", + "negate": false, + "type": "exists", + "value": "exists", + }, + "query": Object { + "exists": Object { + "field": "destination.ip", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "370ebd07-5ce0-4f46-a847-0e363c50d037", + "layerId": "eaadfec7-deaa-4aeb-a403-3b4e516416d2", + "layerType": "data", + }, + }, + "title": "[Network] Network events", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_tls_handshakes.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_tls_handshakes.test.ts.snap new file mode 100644 index 0000000000000..6e695484fdc0f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_tls_handshakes.test.ts.snap @@ -0,0 +1,212 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiTlsHandshakesLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-1f48a633-8eee-45ae-9471-861227e9ca03", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "1f48a633-8eee-45ae-9471-861227e9ca03": Object { + "columnOrder": Array [ + "21052b6b-5504-4084-a2e2-c17f772345cf", + ], + "columns": Object { + "21052b6b-5504-4084-a2e2-c17f772345cf": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "32ee22d9-2e77-4aee-8073-87750e92c3ee", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\":\\"source.ip\\"}},{\\"exists\\":{\\"field\\":\\"destination.ip\\"}}],\\"minimum_should_match\\":1}}", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + }, + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "1e93f984-9374-4755-a198-de57751533c6", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\":\\"tls.version\\"}},{\\"exists\\":{\\"field\\":\\"suricata.eve.tls.version\\"}},{\\"exists\\":{\\"field\\":\\"zeek.ssl.version\\"}}],\\"minimum_should_match\\":1}}", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "tls.version", + }, + }, + Object { + "exists": Object { + "field": "suricata.eve.tls.version", + }, + }, + Object { + "exists": Object { + "field": "zeek.ssl.version", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "21052b6b-5504-4084-a2e2-c17f772345cf", + "layerId": "1f48a633-8eee-45ae-9471-861227e9ca03", + "layerType": "data", + }, + }, + "title": "[Network] TLS handshakes", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_flow_ids.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_flow_ids.test.ts.snap new file mode 100644 index 0000000000000..1e3f1f63c40c8 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_flow_ids.test.ts.snap @@ -0,0 +1,176 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniqueFlowIdsLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-5d46d48f-6ce8-46be-a797-17ad50642564", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "5d46d48f-6ce8-46be-a797-17ad50642564": Object { + "columnOrder": Array [ + "a27f3503-9c73-4fc1-86bb-12461dae4b70", + ], + "columns": Object { + "a27f3503-9c73-4fc1-86bb-12461dae4b70": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "network.community_id", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "index": "c01edc8a-90ce-4d49-95f0-76954a034eb2", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\":\\"source.ip\\"}},{\\"exists\\":{\\"field\\":\\"destination.ip\\"}}],\\"minimum_should_match\\":1}}", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "a27f3503-9c73-4fc1-86bb-12461dae4b70", + "layerId": "5d46d48f-6ce8-46be-a797-17ad50642564", + "layerType": "data", + }, + }, + "title": "[Network] Unique flow IDs", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_area.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_area.test.ts.snap new file mode 100644 index 0000000000000..2415dcc6c750c --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_area.test.ts.snap @@ -0,0 +1,261 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniquePrivateIpsAreaLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-72dc4b99-b07d-4dc9-958b-081d259e11fa", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7": Object { + "columnOrder": Array [ + "662cd5e5-82bf-4325-a703-273f84b97e09", + "5f317308-cfbb-4ee5-bfb9-07653184fabf", + ], + "columns": Object { + "5f317308-cfbb-4ee5-bfb9-07653184fabf": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "\\"source.ip\\": \\"10.0.0.0/8\\" or \\"source.ip\\": \\"192.168.0.0/16\\" or \\"source.ip\\": \\"172.16.0.0/12\\" or \\"source.ip\\": \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "Src.", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + "662cd5e5-82bf-4325-a703-273f84b97e09": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + "72dc4b99-b07d-4dc9-958b-081d259e11fa": Object { + "columnOrder": Array [ + "36444b8c-7e10-4069-8298-6c1b46912be2", + "ac1eb80c-ddde-46c4-a90c-400261926762", + ], + "columns": Object { + "36444b8c-7e10-4069-8298-6c1b46912be2": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "ac1eb80c-ddde-46c4-a90c-400261926762": Object { + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "\\"destination.ip\\": \\"10.0.0.0/8\\" or \\"destination.ip\\": \\"192.168.0.0/16\\" or \\"destination.ip\\": \\"172.16.0.0/12\\" or \\"destination.ip\\": \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "Dest.", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "5f317308-cfbb-4ee5-bfb9-07653184fabf", + ], + "layerId": "38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7", + "layerType": "data", + "seriesType": "area", + "xAccessor": "662cd5e5-82bf-4325-a703-273f84b97e09", + "yConfig": Array [ + Object { + "color": "#d36186", + "forAccessor": "5f317308-cfbb-4ee5-bfb9-07653184fabf", + }, + ], + }, + Object { + "accessors": Array [ + "ac1eb80c-ddde-46c4-a90c-400261926762", + ], + "layerId": "72dc4b99-b07d-4dc9-958b-081d259e11fa", + "layerType": "data", + "seriesType": "area", + "xAccessor": "36444b8c-7e10-4069-8298-6c1b46912be2", + "yConfig": Array [ + Object { + "color": "#9170b8", + "forAccessor": "ac1eb80c-ddde-46c4-a90c-400261926762", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "area", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Network] Unique private IPs - area chart", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_bar.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_bar.test.ts.snap new file mode 100644 index 0000000000000..2ea658869183c --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_bar.test.ts.snap @@ -0,0 +1,276 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniquePrivateIpsBarLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-e406bf4f-942b-41ac-b516-edb5cef06ec8", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7": Object { + "columnOrder": Array [ + "4607c585-3af3-43b9-804f-e49b27796d79", + "d27e0966-daf9-41f4-9033-230cf1e76dc9", + ], + "columns": Object { + "4607c585-3af3-43b9-804f-e49b27796d79": Object { + "dataType": "string", + "isBucketed": true, + "label": "Filters", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "", + }, + "label": "Dest.", + }, + ], + }, + "scale": "ordinal", + }, + "d27e0966-daf9-41f4-9033-230cf1e76dc9": Object { + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "\\"destination.ip\\": \\"10.0.0.0/8\\" or \\"destination.ip\\": \\"192.168.0.0/16\\" or \\"destination.ip\\": \\"172.16.0.0/12\\" or \\"destination.ip\\": \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "Unique count of destination.ip", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + }, + "incompleteColumns": Object {}, + }, + "e406bf4f-942b-41ac-b516-edb5cef06ec8": Object { + "columnOrder": Array [ + "d9c438c5-f776-4436-9d20-d62dc8c03be8", + "5acd4c9d-dc3b-4b21-9632-e4407944c36d", + ], + "columns": Object { + "5acd4c9d-dc3b-4b21-9632-e4407944c36d": Object { + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "source.ip: \\"10.0.0.0/8\\" or source.ip: \\"192.168.0.0/16\\" or source.ip: \\"172.16.0.0/12\\" or source.ip: \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "Unique count of source.ip", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + "d9c438c5-f776-4436-9d20-d62dc8c03be8": Object { + "dataType": "string", + "isBucketed": true, + "label": "Filters", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "", + }, + "label": "Src.", + }, + ], + }, + "scale": "ordinal", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "5acd4c9d-dc3b-4b21-9632-e4407944c36d", + ], + "layerId": "e406bf4f-942b-41ac-b516-edb5cef06ec8", + "layerType": "data", + "position": "top", + "seriesType": "bar_horizontal_stacked", + "showGridlines": false, + "xAccessor": "d9c438c5-f776-4436-9d20-d62dc8c03be8", + "yConfig": Array [ + Object { + "color": "#d36186", + "forAccessor": "5acd4c9d-dc3b-4b21-9632-e4407944c36d", + }, + ], + }, + Object { + "accessors": Array [ + "d27e0966-daf9-41f4-9033-230cf1e76dc9", + ], + "layerId": "38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7", + "layerType": "data", + "seriesType": "bar_horizontal_stacked", + "xAccessor": "4607c585-3af3-43b9-804f-e49b27796d79", + "yConfig": Array [ + Object { + "color": "#9170b8", + "forAccessor": "d27e0966-daf9-41f4-9033-230cf1e76dc9", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "bar_horizontal_stacked", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Network] Unique private IPs - bar chart", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_destination_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_destination_metric.test.ts.snap new file mode 100644 index 0000000000000..37311a980c6b4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_destination_metric.test.ts.snap @@ -0,0 +1,149 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniquePrivateIpsDestinationMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "cea37c70-8f91-43bf-b9fe-72d8c049f6a3": Object { + "columnOrder": Array [ + "bd17c23e-4f83-4108-8005-2669170d064b", + ], + "columns": Object { + "bd17c23e-4f83-4108-8005-2669170d064b": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "\\"destination.ip\\": \\"10.0.0.0/8\\" or \\"destination.ip\\": \\"192.168.0.0/16\\" or \\"destination.ip\\": \\"172.16.0.0/12\\" or \\"destination.ip\\": \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "destination.ip", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "bd17c23e-4f83-4108-8005-2669170d064b", + "layerId": "cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "layerType": "data", + }, + }, + "title": "[Network] Unique private IPs - destination metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_source_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_source_metric.test.ts.snap new file mode 100644 index 0000000000000..2f7ba7d2997b1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/__snapshots__/kpi_unique_private_ips_source_metric.test.ts.snap @@ -0,0 +1,149 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUniquePrivateIpsSourceMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "cea37c70-8f91-43bf-b9fe-72d8c049f6a3": Object { + "columnOrder": Array [ + "bd17c23e-4f83-4108-8005-2669170d064b", + ], + "columns": Object { + "bd17c23e-4f83-4108-8005-2669170d064b": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "source.ip: \\"10.0.0.0/8\\" or source.ip: \\"192.168.0.0/16\\" or source.ip: \\"172.16.0.0/12\\" or source.ip: \\"fd00::/8\\"", + }, + "isBucketed": false, + "label": "", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "source.ip", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": "", + "disabled": false, + "key": "bool", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"bool\\":{\\"should\\":[{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"source.ip\\"}}],\\"minimum_should_match\\":1}},{\\"bool\\":{\\"should\\":[{\\"exists\\":{\\"field\\": \\"destination.ip\\"}}],\\"minimum_should_match\\":1}}],\\"minimum_should_match\\":1}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "source.ip", + }, + }, + ], + }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "destination.ip", + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "bd17c23e-4f83-4108-8005-2669170d064b", + "layerId": "cea37c70-8f91-43bf-b9fe-72d8c049f6a3", + "layerType": "data", + }, + }, + "title": "[Network] Unique private IPs - source metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.test.ts new file mode 100644 index 0000000000000..a726a44e34e39 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { dnsTopDomainsLensAttributes } from './dns_top_domains'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('dnsTopDomainsLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: dnsTopDomainsLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.ts index 07a3badc3b96e..ef75bea77c3e0 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/dns_top_domains.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TOP_VALUE, UNIQUE_COUNT } from '../../translations'; import type { LensAttributes } from '../../types'; /* Exported from Kibana Saved Object */ @@ -104,7 +105,7 @@ export const dnsTopDomainsLensAttributes: LensAttributes = { }, }, '2a4d5e20-f570-48e4-b9ab-ff3068919377': { - label: 'Unique count of dns.question.registered_domain', + label: UNIQUE_COUNT('dns.question.registered_domain'), dataType: 'number', operationType: 'unique_count', scale: 'ratio', @@ -112,7 +113,7 @@ export const dnsTopDomainsLensAttributes: LensAttributes = { isBucketed: false, }, 'e8842815-2a45-4c74-86de-c19a391e2424': { - label: 'Top values of dns.question.name', + label: TOP_VALUE('dns.question.name'), dataType: 'string', operationType: 'terms', scale: 'ordinal', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.test.ts new file mode 100644 index 0000000000000..b19b5c1f2f1ba --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiDnsQueriesLensAttributes } from './kpi_dns_queries'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiDnsQueriesLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiDnsQueriesLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.ts index 1d6cddb7f1b61..681cd278214b1 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_dns_queries.ts @@ -10,7 +10,7 @@ import type { LensAttributes } from '../../types'; export const kpiDnsQueriesLensAttributes: LensAttributes = { title: '[Network] DNS metric', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { layerId: 'cea37c70-8f91-43bf-b9fe-72d8c049f6a3', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.test.ts new file mode 100644 index 0000000000000..4ca26f222021a --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiNetworkEventsLensAttributes } from './kpi_network_events'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiNetworkEventsLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiNetworkEventsLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.ts index 013ad35b31ecc..534ffeb2024e6 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_network_events.ts @@ -10,7 +10,7 @@ import type { LensAttributes } from '../../types'; export const kpiNetworkEventsLensAttributes: LensAttributes = { title: '[Network] Network events', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { layerId: 'eaadfec7-deaa-4aeb-a403-3b4e516416d2', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.test.ts new file mode 100644 index 0000000000000..f06f478ca0e2b --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiTlsHandshakesLensAttributes } from './kpi_tls_handshakes'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiTlsHandshakesLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiTlsHandshakesLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.ts index 343c61dbd2be1..367fe6fd40f6f 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_tls_handshakes.ts @@ -9,7 +9,7 @@ import type { LensAttributes } from '../../types'; export const kpiTlsHandshakesLensAttributes: LensAttributes = { title: '[Network] TLS handshakes', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { layerId: '1f48a633-8eee-45ae-9471-861227e9ca03', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.test.ts new file mode 100644 index 0000000000000..64b9be02a1d18 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniqueFlowIdsLensAttributes } from './kpi_unique_flow_ids'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniqueFlowIdsLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniqueFlowIdsLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.ts index 3646e3c0a70bd..5f31645c75eca 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_flow_ids.ts @@ -10,7 +10,7 @@ import type { LensAttributes } from '../../types'; export const kpiUniqueFlowIdsLensAttributes: LensAttributes = { title: '[Network] Unique flow IDs', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { layerId: '5d46d48f-6ce8-46be-a797-17ad50642564', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.test.ts new file mode 100644 index 0000000000000..8bb98ddaf95cf --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniquePrivateIpsAreaLensAttributes } from './kpi_unique_private_ips_area'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniquePrivateIpsAreaLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniquePrivateIpsAreaLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.ts index 2d3792e399372..394bc227e871c 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_area.ts @@ -4,6 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import { DESTINATION_CHART_LABEL, SOURCE_CHART_LABEL } from '../../translations'; import type { LensAttributes } from '../../types'; export const kpiUniquePrivateIpsAreaLensAttributes: LensAttributes = { @@ -97,7 +98,7 @@ export const kpiUniquePrivateIpsAreaLensAttributes: LensAttributes = { }, }, '5f317308-cfbb-4ee5-bfb9-07653184fabf': { - label: 'Src.', + label: SOURCE_CHART_LABEL, dataType: 'number', operationType: 'unique_count', scale: 'ratio', @@ -131,7 +132,7 @@ export const kpiUniquePrivateIpsAreaLensAttributes: LensAttributes = { }, }, 'ac1eb80c-ddde-46c4-a90c-400261926762': { - label: 'Dest.', + label: DESTINATION_CHART_LABEL, dataType: 'number', operationType: 'unique_count', scale: 'ratio', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.test.ts new file mode 100644 index 0000000000000..894144d383b58 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniquePrivateIpsBarLensAttributes } from './kpi_unique_private_ips_bar'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniquePrivateIpsBarLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniquePrivateIpsBarLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.ts index bf4ad0e704081..fe4a698aedf5e 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_bar.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SOURCE_CHART_LABEL, DESTINATION_CHART_LABEL } from '../../translations'; +import { SOURCE_CHART_LABEL, DESTINATION_CHART_LABEL, UNIQUE_COUNT } from '../../translations'; import type { LensAttributes } from '../../types'; export const kpiUniquePrivateIpsBarLensAttributes: LensAttributes = { @@ -90,7 +90,7 @@ export const kpiUniquePrivateIpsBarLensAttributes: LensAttributes = { 'e406bf4f-942b-41ac-b516-edb5cef06ec8': { columns: { '5acd4c9d-dc3b-4b21-9632-e4407944c36d': { - label: SOURCE_CHART_LABEL, + label: UNIQUE_COUNT('source.ip'), dataType: 'number', isBucketed: false, operationType: 'unique_count', @@ -130,7 +130,7 @@ export const kpiUniquePrivateIpsBarLensAttributes: LensAttributes = { '38aa6532-6bf9-4c8f-b2a6-da8d32f7d0d7': { columns: { 'd27e0966-daf9-41f4-9033-230cf1e76dc9': { - label: DESTINATION_CHART_LABEL, + label: UNIQUE_COUNT('destination.ip'), dataType: 'number', isBucketed: false, operationType: 'unique_count', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.test.ts new file mode 100644 index 0000000000000..7d65e042554b3 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniquePrivateIpsDestinationMetricLensAttributes } from './kpi_unique_private_ips_destination_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniquePrivateIpsDestinationMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniquePrivateIpsDestinationMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.ts index a2bccef3b624b..6e3d440619e76 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_destination_metric.ts @@ -48,7 +48,7 @@ export const kpiUniquePrivateIpsDestinationMetricLensAttributes: LensAttributes }, }, title: '[Network] Unique private IPs - destination metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.test.ts new file mode 100644 index 0000000000000..88042d8663250 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUniquePrivateIpsSourceMetricLensAttributes } from './kpi_unique_private_ips_source_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'network', + tabName: 'events', + }, + ]), +})); + +describe('kpiUniquePrivateIpsSourceMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUniquePrivateIpsSourceMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.ts index a95745c7b96ed..3f1110d706300 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/network/kpi_unique_private_ips_source_metric.ts @@ -47,7 +47,7 @@ export const kpiUniquePrivateIpsSourceMetricLensAttributes: LensAttributes = { }, }, title: '[Network] Unique private IPs - source metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_area.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_area.test.ts.snap new file mode 100644 index 0000000000000..11df964f2eca1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_area.test.ts.snap @@ -0,0 +1,151 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiTotalUsersAreaLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-416b6fad-1923-4f6a-a2df-b223bb287e30", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "416b6fad-1923-4f6a-a2df-b223bb287e30": Object { + "columnOrder": Array [ + "5eea817b-67b7-4268-8ecb-7688d1094721", + "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + ], + "columns": Object { + "5eea817b-67b7-4268-8ecb-7688d1094721": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + "b00c65ea-32be-4163-bfc8-f795b1ef9d06": Object { + "customLabel": true, + "dataType": "number", + "isBucketed": false, + "label": "Unique count of user.name", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "user.name", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": false, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "b00c65ea-32be-4163-bfc8-f795b1ef9d06", + ], + "layerId": "416b6fad-1923-4f6a-a2df-b223bb287e30", + "layerType": "data", + "seriesType": "area", + "xAccessor": "5eea817b-67b7-4268-8ecb-7688d1094721", + }, + ], + "legend": Object { + "isVisible": true, + "position": "right", + }, + "preferredSeriesType": "area", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[User] Users - area", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_metric.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_metric.test.ts.snap new file mode 100644 index 0000000000000..b53e1bd24d303 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_total_users_metric.test.ts.snap @@ -0,0 +1,97 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiTotalUsersMetricLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-416b6fad-1923-4f6a-a2df-b223bb287e30", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "416b6fad-1923-4f6a-a2df-b223bb287e30": Object { + "columnOrder": Array [ + "3e51b035-872c-4b44-824b-fe069c222e91", + ], + "columns": Object { + "3e51b035-872c-4b44-824b-fe069c222e91": Object { + "dataType": "number", + "isBucketed": false, + "label": " ", + "operationType": "unique_count", + "scale": "ratio", + "sourceField": "user.name", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "3e51b035-872c-4b44-824b-fe069c222e91", + "layerId": "416b6fad-1923-4f6a-a2df-b223bb287e30", + "layerType": "data", + }, + }, + "title": "[User] Users - metric", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentication_metric_failure.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentication_metric_failure.test.ts.snap new file mode 100644 index 0000000000000..37c20b7e80265 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentication_metric_failure.test.ts.snap @@ -0,0 +1,126 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUserAuthenticationsMetricFailureLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "4590dafb-4ac7-45aa-8641-47a3ff0b817c": Object { + "columnOrder": Array [ + "0eb97c09-a351-4280-97da-944e4bd30dd7", + ], + "columns": Object { + "0eb97c09-a351-4280-97da-944e4bd30dd7": Object { + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome : \\"failure\\" ", + }, + "isBucketed": false, + "label": "", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"term\\":{\\"event.category\\":\\"authentication\\"}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "event.category": "authentication", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "0eb97c09-a351-4280-97da-944e4bd30dd7", + "layerId": "4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "layerType": "data", + }, + }, + "title": "[Host] User authentications - metric failure ", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_area.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_area.test.ts.snap new file mode 100644 index 0000000000000..1954bccfaffbe --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_area.test.ts.snap @@ -0,0 +1,240 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUserAuthenticationsAreaLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "{dataViewId}", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-31213ae3-905b-4e88-b987-0cccb1f3209f", + "type": "{dataViewId}", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "type": "{dataViewId}", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "31213ae3-905b-4e88-b987-0cccb1f3209f": Object { + "columnOrder": Array [ + "33a6163d-0c0a-451d-aa38-8ca6010dd5bf", + "2b27c80e-a20d-46f1-8fb2-79626ef4563c", + ], + "columns": Object { + "2b27c80e-a20d-46f1-8fb2-79626ef4563c": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome: \\"failure\\" ", + }, + "isBucketed": false, + "label": "Fail", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "33a6163d-0c0a-451d-aa38-8ca6010dd5bf": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + "4590dafb-4ac7-45aa-8641-47a3ff0b817c": Object { + "columnOrder": Array [ + "49a42fe6-ebe8-4adb-8eed-1966a5297b7e", + "0eb97c09-a351-4280-97da-944e4bd30dd7", + ], + "columns": Object { + "0eb97c09-a351-4280-97da-944e4bd30dd7": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome : \\"success\\" ", + }, + "isBucketed": false, + "label": "Succ.", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "49a42fe6-ebe8-4adb-8eed-1966a5297b7e": Object { + "dataType": "date", + "isBucketed": true, + "label": "@timestamp", + "operationType": "date_histogram", + "params": Object { + "interval": "auto", + }, + "scale": "interval", + "sourceField": "@timestamp", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"term\\":{\\"event.category\\":\\"authentication\\"}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "event.category": "authentication", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": true, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "0eb97c09-a351-4280-97da-944e4bd30dd7", + ], + "layerId": "4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "layerType": "data", + "seriesType": "area", + "xAccessor": "49a42fe6-ebe8-4adb-8eed-1966a5297b7e", + "yConfig": Array [ + Object { + "color": "#54b399", + "forAccessor": "0eb97c09-a351-4280-97da-944e4bd30dd7", + }, + ], + }, + Object { + "accessors": Array [ + "2b27c80e-a20d-46f1-8fb2-79626ef4563c", + ], + "layerId": "31213ae3-905b-4e88-b987-0cccb1f3209f", + "layerType": "data", + "seriesType": "area", + "xAccessor": "33a6163d-0c0a-451d-aa38-8ca6010dd5bf", + "yConfig": Array [ + Object { + "color": "#e7664c", + "forAccessor": "2b27c80e-a20d-46f1-8fb2-79626ef4563c", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "area", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Host] User authentications - area ", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_bar.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_bar.test.ts.snap new file mode 100644 index 0000000000000..5335dca6057a6 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_bar.test.ts.snap @@ -0,0 +1,240 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUserAuthenticationsBarLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-31213ae3-905b-4e88-b987-0cccb1f3209f", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-b9acd453-f476-4467-ad38-203e37b73e55", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "31213ae3-905b-4e88-b987-0cccb1f3209f": Object { + "columnOrder": Array [ + "430e690c-9992-414f-9bce-00812d99a5e7", + "938b445a-a291-4bbc-84fe-4f47b69c20e4", + ], + "columns": Object { + "430e690c-9992-414f-9bce-00812d99a5e7": Object { + "dataType": "string", + "isBucketed": true, + "label": "Filters", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "event.outcome : \\"success\\" ", + }, + "label": "Succ.", + }, + ], + }, + "scale": "ordinal", + }, + "938b445a-a291-4bbc-84fe-4f47b69c20e4": Object { + "dataType": "number", + "isBucketed": false, + "label": "Succ.", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + "b9acd453-f476-4467-ad38-203e37b73e55": Object { + "columnOrder": Array [ + "e959c351-a3a2-4525-b244-9623f215a8fd", + "c8165fc3-7180-4f1b-8c87-bc3ea04c6df7", + ], + "columns": Object { + "c8165fc3-7180-4f1b-8c87-bc3ea04c6df7": Object { + "dataType": "number", + "isBucketed": false, + "label": "Fail", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + "e959c351-a3a2-4525-b244-9623f215a8fd": Object { + "customLabel": true, + "dataType": "string", + "isBucketed": true, + "label": "Fail", + "operationType": "filters", + "params": Object { + "filters": Array [ + Object { + "input": Object { + "language": "kuery", + "query": "event.outcome:\\"failure\\" ", + }, + "label": "Fail", + }, + ], + }, + "scale": "ordinal", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"term\\":{\\"event.category\\":\\"authentication\\"}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "event.category": "authentication", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "axisTitlesVisibilitySettings": Object { + "x": false, + "yLeft": false, + "yRight": true, + }, + "fittingFunction": "None", + "gridlinesVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "labelsOrientation": Object { + "x": 0, + "yLeft": 0, + "yRight": 0, + }, + "layers": Array [ + Object { + "accessors": Array [ + "938b445a-a291-4bbc-84fe-4f47b69c20e4", + ], + "layerId": "31213ae3-905b-4e88-b987-0cccb1f3209f", + "layerType": "data", + "seriesType": "bar_horizontal_stacked", + "xAccessor": "430e690c-9992-414f-9bce-00812d99a5e7", + "yConfig": Array [], + }, + Object { + "accessors": Array [ + "c8165fc3-7180-4f1b-8c87-bc3ea04c6df7", + ], + "layerId": "b9acd453-f476-4467-ad38-203e37b73e55", + "layerType": "data", + "seriesType": "bar_horizontal_stacked", + "xAccessor": "e959c351-a3a2-4525-b244-9623f215a8fd", + "yConfig": Array [ + Object { + "color": "#e7664c", + "forAccessor": "c8165fc3-7180-4f1b-8c87-bc3ea04c6df7", + }, + ], + }, + ], + "legend": Object { + "isVisible": false, + "position": "right", + "showSingleSeries": false, + }, + "preferredSeriesType": "bar_horizontal_stacked", + "tickLabelsVisibilitySettings": Object { + "x": true, + "yLeft": true, + "yRight": true, + }, + "valueLabels": "hide", + "yLeftExtent": Object { + "mode": "full", + }, + "yRightExtent": Object { + "mode": "full", + }, + }, + }, + "title": "[Host] User authentications - bar ", + "visualizationType": "lnsXY", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_metric_success.test.ts.snap b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_metric_success.test.ts.snap new file mode 100644 index 0000000000000..4cadcaf19e91e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/__snapshots__/kpi_user_authentications_metric_success.test.ts.snap @@ -0,0 +1,127 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`kpiUserAuthenticationsMetricSuccessLensAttributes should render 1`] = ` +Object { + "description": "", + "references": Array [ + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern", + }, + Object { + "id": "security-solution-my-test", + "name": "indexpattern-datasource-layer-4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "type": "index-pattern", + }, + ], + "state": Object { + "datasourceStates": Object { + "indexpattern": Object { + "layers": Object { + "4590dafb-4ac7-45aa-8641-47a3ff0b817c": Object { + "columnOrder": Array [ + "0eb97c09-a351-4280-97da-944e4bd30dd7", + ], + "columns": Object { + "0eb97c09-a351-4280-97da-944e4bd30dd7": Object { + "customLabel": true, + "dataType": "number", + "filter": Object { + "language": "kuery", + "query": "event.outcome : \\"success\\" ", + }, + "isBucketed": false, + "label": " ", + "operationType": "count", + "scale": "ratio", + "sourceField": "___records___", + }, + }, + "incompleteColumns": Object {}, + }, + }, + }, + }, + "filters": Array [ + Object { + "$state": Object { + "store": "appState", + }, + "meta": Object { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "query", + "negate": false, + "type": "custom", + "value": "{\\"bool\\":{\\"filter\\":[{\\"term\\":{\\"event.category\\":\\"authentication\\"}}]}}", + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "event.category": "authentication", + }, + }, + ], + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "host.id", + "negate": false, + "params": Object { + "query": "123", + }, + "type": "phrase", + }, + "query": Object { + "match_phrase": Object { + "host.id": "123", + }, + }, + }, + Object { + "meta": Object { + "alias": null, + "disabled": false, + "key": "_index", + "negate": false, + "params": Array [ + "auditbeat-mytest-*", + ], + "type": "phrases", + }, + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "_index": "auditbeat-mytest-*", + }, + }, + ], + }, + }, + }, + ], + "query": Object { + "language": "kql", + "query": "host.name: *", + }, + "visualization": Object { + "accessor": "0eb97c09-a351-4280-97da-944e4bd30dd7", + "layerId": "4590dafb-4ac7-45aa-8641-47a3ff0b817c", + "layerType": "data", + }, + }, + "title": "[Host] User authentications - metric success ", + "visualizationType": "lnsLegacyMetric", +} +`; diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.test.ts new file mode 100644 index 0000000000000..43cb5be3a9735 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiTotalUsersAreaLensAttributes } from './kpi_total_users_area'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiTotalUsersAreaLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiTotalUsersAreaLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.ts index d958f9304b8ab..c97748077a6be 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_area.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { UNIQUE_COUNT } from '../../translations'; import type { LensAttributes } from '../../types'; export const kpiTotalUsersAreaLensAttributes: LensAttributes = { @@ -32,7 +33,7 @@ export const kpiTotalUsersAreaLensAttributes: LensAttributes = { customLabel: true, dataType: 'number', isBucketed: false, - label: ' ', + label: UNIQUE_COUNT('user.name'), operationType: 'unique_count', scale: 'ratio', sourceField: 'user.name', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.test.ts new file mode 100644 index 0000000000000..0a5ec9891d26f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiTotalUsersMetricLensAttributes } from './kpi_total_users_metric'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiTotalUsersMetricLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiTotalUsersMetricLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.ts index 08e5756337dce..faa6b62e18b65 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_total_users_metric.ts @@ -19,7 +19,7 @@ export const kpiTotalUsersMetricLensAttributes: LensAttributes = { '3e51b035-872c-4b44-824b-fe069c222e91': { dataType: 'number', isBucketed: false, - label: 'Unique count of user.name', + label: ' ', operationType: 'unique_count', scale: 'ratio', sourceField: 'user.name', @@ -39,7 +39,7 @@ export const kpiTotalUsersMetricLensAttributes: LensAttributes = { }, }, title: '[User] Users - metric', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', references: [ { id: '{dataViewId}', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.test.ts new file mode 100644 index 0000000000000..e251ccf51c5e5 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUserAuthenticationsMetricFailureLensAttributes } from './kpi_user_authentication_metric_failure'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiUserAuthenticationsMetricFailureLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUserAuthenticationsMetricFailureLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.ts index e4690f66998c8..3f421f8a1c30a 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentication_metric_failure.ts @@ -10,7 +10,7 @@ import type { LensAttributes } from '../../types'; export const kpiUserAuthenticationsMetricFailureLensAttributes: LensAttributes = { title: '[Host] User authentications - metric failure ', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { accessor: '0eb97c09-a351-4280-97da-944e4bd30dd7', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.test.ts new file mode 100644 index 0000000000000..b51d3e474a705 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUserAuthenticationsAreaLensAttributes } from './kpi_user_authentications_area'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiUserAuthenticationsAreaLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUserAuthenticationsAreaLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.ts index cf9902bb2413a..d96ea21489bb2 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_area.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { FAIL_CHART_LABEL, SUCCESS_CHART_LABEL } from '../../translations'; import type { LensAttributes } from '../../types'; export const kpiUserAuthenticationsAreaLensAttributes: LensAttributes = { @@ -124,7 +125,7 @@ export const kpiUserAuthenticationsAreaLensAttributes: LensAttributes = { query: 'event.outcome: "failure" ', }, isBucketed: false, - label: 'Fail', + label: FAIL_CHART_LABEL, operationType: 'count', scale: 'ratio', sourceField: '___records___', @@ -157,7 +158,7 @@ export const kpiUserAuthenticationsAreaLensAttributes: LensAttributes = { query: 'event.outcome : "success" ', }, isBucketed: false, - label: 'Succ.', + label: SUCCESS_CHART_LABEL, operationType: 'count', scale: 'ratio', sourceField: '___records___', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_bar.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_bar.test.ts new file mode 100644 index 0000000000000..41590d330cd45 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_bar.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUserAuthenticationsBarLensAttributes } from './kpi_user_authentications_bar'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiUserAuthenticationsBarLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUserAuthenticationsBarLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.test.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.test.ts new file mode 100644 index 0000000000000..570e03325ec34 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react-hooks'; +import { wrapper } from '../../mocks'; + +import { useLensAttributes } from '../../use_lens_attributes'; + +import { kpiUserAuthenticationsMetricSuccessLensAttributes } from './kpi_user_authentications_metric_success'; + +jest.mock('../../../../containers/sourcerer', () => ({ + useSourcererDataView: jest.fn().mockReturnValue({ + selectedPatterns: ['auditbeat-mytest-*'], + dataViewId: 'security-solution-my-test', + }), +})); + +jest.mock('../../../../utils/route/use_route_spy', () => ({ + useRouteSpy: jest.fn().mockReturnValue([ + { + detailName: 'mockHost', + pageName: 'users', + tabName: 'events', + }, + ]), +})); + +describe('kpiUserAuthenticationsMetricSuccessLensAttributes', () => { + it('should render', () => { + const { result } = renderHook( + () => + useLensAttributes({ + lensAttributes: kpiUserAuthenticationsMetricSuccessLensAttributes, + stackByField: 'event.dataset', + }), + { wrapper } + ); + + expect(result?.current).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.ts index 66f30bf2378a8..3af6f5734d458 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/lens_attributes/users/kpi_user_authentications_metric_success.ts @@ -10,7 +10,7 @@ import type { LensAttributes } from '../../types'; export const kpiUserAuthenticationsMetricSuccessLensAttributes: LensAttributes = { title: '[Host] User authentications - metric success ', description: '', - visualizationType: 'lnsMetric', + visualizationType: 'lnsLegacyMetric', state: { visualization: { accessor: '0eb97c09-a351-4280-97da-944e4bd30dd7', diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/mocks.tsx b/x-pack/plugins/security_solution/public/common/components/visualization_actions/mocks.tsx new file mode 100644 index 0000000000000..7f4e7e4e6d6eb --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/mocks.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import React from 'react'; +import { cloneDeep } from 'lodash/fp'; + +import { + TestProviders, + mockGlobalState, + SUB_PLUGINS_REDUCER, + kibanaObservable, + createSecuritySolutionStorageMock, +} from '../../mock'; +import type { State } from '../../store'; +import { createStore } from '../../store'; + +export const queryFromSearchBar = { + query: 'host.name: *', + language: 'kql', +}; + +export const filterFromSearchBar = [ + { + meta: { + alias: null, + negate: false, + disabled: false, + type: 'phrase', + key: 'host.id', + params: { + query: '123', + }, + }, + query: { + match_phrase: { + 'host.id': '123', + }, + }, + }, +]; + +export const mockCreateStoreWithQueryFilters = () => { + const { storage } = createSecuritySolutionStorageMock(); + + const state: State = mockGlobalState; + + const myState = cloneDeep(state); + + myState.inputs = { + ...myState.inputs, + global: { + ...myState.inputs.global, + query: queryFromSearchBar, + filters: filterFromSearchBar, + }, + }; + return createStore(myState, SUB_PLUGINS_REDUCER, kibanaObservable, storage); +}; + +export const wrapper = ({ children }: { children: React.ReactElement }) => ( + {children} +); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/translations.ts b/x-pack/plugins/security_solution/public/common/components/visualization_actions/translations.ts index 9814a98817ef4..4dcceb29323b1 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/translations.ts @@ -67,9 +67,41 @@ export const SUCCESS_CHART_LABEL = i18n.translate( } ); +export const AUTHENCICATION_SUCCESS_CHART_LABEL = i18n.translate( + 'xpack.securitySolution.visualizationActions.userAuthentications.authentication.successChartLabel', + { + defaultMessage: 'Success', + } +); + export const FAIL_CHART_LABEL = i18n.translate( 'xpack.securitySolution.visualizationActions.userAuthentications.failChartLabel', { defaultMessage: 'Fail', } ); + +export const AUTHENCICATION_FAILURE_CHART_LABEL = i18n.translate( + 'xpack.securitySolution.visualizationActions.userAuthentications.authentication.failureChartLabel', + { + defaultMessage: 'Failure', + } +); + +export const UNIQUE_COUNT = (field: string) => + i18n.translate('xpack.securitySolution.visualizationActions.uniqueCountLabel', { + values: { field }, + + defaultMessage: 'Unique count of {field}', + }); + +export const TOP_VALUE = (field: string) => + i18n.translate('xpack.securitySolution.visualizationActions.topValueLabel', { + values: { field }, + + defaultMessage: 'Top values of {field}', + }); + +export const COUNT = i18n.translate('xpack.securitySolution.visualizationActions.countLabel', { + defaultMessage: 'Count of records', +}); diff --git a/x-pack/plugins/security_solution/public/common/components/visualization_actions/use_lens_attributes.test.tsx b/x-pack/plugins/security_solution/public/common/components/visualization_actions/use_lens_attributes.test.tsx index 7db97ab5526a4..76e2f54c62cea 100644 --- a/x-pack/plugins/security_solution/public/common/components/visualization_actions/use_lens_attributes.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/visualization_actions/use_lens_attributes.test.tsx @@ -6,21 +6,12 @@ */ import { renderHook } from '@testing-library/react-hooks'; -import React from 'react'; -import { cloneDeep } from 'lodash/fp'; -import { - TestProviders, - mockGlobalState, - SUB_PLUGINS_REDUCER, - kibanaObservable, - createSecuritySolutionStorageMock, -} from '../../mock'; import { getExternalAlertLensAttributes } from './lens_attributes/common/external_alert'; import { useLensAttributes } from './use_lens_attributes'; import { hostNameExistsFilter, getHostDetailsPageFilter, getIndexFilters } from './utils'; -import type { State } from '../../store'; -import { createStore } from '../../store'; + +import { filterFromSearchBar, queryFromSearchBar, wrapper } from './mocks'; jest.mock('../../containers/sourcerer', () => ({ useSourcererDataView: jest.fn().mockReturnValue({ @@ -40,51 +31,7 @@ jest.mock('../../utils/route/use_route_spy', () => ({ })); describe('useLensAttributes', () => { - const state: State = mockGlobalState; - const { storage } = createSecuritySolutionStorageMock(); - const queryFromSearchBar = { - query: 'host.name: *', - language: 'kql', - }; - - const filterFromSearchBar = [ - { - meta: { - alias: null, - negate: false, - disabled: false, - type: 'phrase', - key: 'host.id', - params: { - query: '123', - }, - }, - query: { - match_phrase: { - 'host.id': '123', - }, - }, - }, - ]; - let store = createStore(state, SUB_PLUGINS_REDUCER, kibanaObservable, storage); - - beforeEach(() => { - const myState = cloneDeep(state); - myState.inputs = { - ...myState.inputs, - global: { - ...myState.inputs.global, - query: queryFromSearchBar, - filters: filterFromSearchBar, - }, - }; - store = createStore(myState, SUB_PLUGINS_REDUCER, kibanaObservable, storage); - }); - it('should add query', () => { - const wrapper = ({ children }: { children: React.ReactElement }) => ( - {children} - ); const { result } = renderHook( () => useLensAttributes({ @@ -94,13 +41,10 @@ describe('useLensAttributes', () => { { wrapper } ); - expect(result?.current?.state.query).toEqual({ query: 'host.name: *', language: 'kql' }); + expect(result?.current?.state.query).toEqual(queryFromSearchBar); }); it('should add filters', () => { - const wrapper = ({ children }: { children: React.ReactElement }) => ( - {children} - ); const { result } = renderHook( () => useLensAttributes({ @@ -120,9 +64,6 @@ describe('useLensAttributes', () => { }); it('should add data view id to references', () => { - const wrapper = ({ children }: { children: React.ReactElement }) => ( - {children} - ); const { result } = renderHook( () => useLensAttributes({ diff --git a/x-pack/plugins/security_solution/public/common/hooks/translations.ts b/x-pack/plugins/security_solution/public/common/hooks/translations.ts index 1f939282b5c72..54ed3a79d017f 100644 --- a/x-pack/plugins/security_solution/public/common/hooks/translations.ts +++ b/x-pack/plugins/security_solution/public/common/hooks/translations.ts @@ -39,10 +39,3 @@ export const EQL_TIME_INTERVAL_NOT_DEFINED = i18n.translate( defaultMessage: 'Time intervals are not defined.', } ); - -export const SAVED_QUERY_LOAD_ERROR_TOAST = i18n.translate( - 'xpack.securitySolution.hooks.useGetSavedQuery.errorToastMessage', - { - defaultMessage: 'Failed to load the saved query', - } -); diff --git a/x-pack/plugins/security_solution/public/common/hooks/use_fetch/request_names.ts b/x-pack/plugins/security_solution/public/common/hooks/use_fetch/request_names.ts index 523578777f282..2d6c414090367 100644 --- a/x-pack/plugins/security_solution/public/common/hooks/use_fetch/request_names.ts +++ b/x-pack/plugins/security_solution/public/common/hooks/use_fetch/request_names.ts @@ -12,6 +12,7 @@ export const REQUEST_NAMES = { GET_RISK_SCORE_DEPRECATED: `${APP_UI_ID} fetch is risk score deprecated`, GET_SAVED_QUERY: `${APP_UI_ID} fetch saved query`, ENABLE_RISK_SCORE: `${APP_UI_ID} fetch enable risk score`, + REFRESH_RISK_SCORE: `${APP_UI_ID} fetch refresh risk score`, UPGRADE_RISK_SCORE: `${APP_UI_ID} fetch upgrade risk score`, } as const; diff --git a/x-pack/plugins/security_solution/public/common/hooks/use_refetch_queries.ts b/x-pack/plugins/security_solution/public/common/hooks/use_refetch_queries.ts new file mode 100644 index 0000000000000..64e8d10ec2c21 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/hooks/use_refetch_queries.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useMemo } from 'react'; +import { queriesSelector } from '../components/super_date_picker/selectors'; +import type { State, inputsModel } from '../store'; +import { InputsModelId } from '../store/inputs/constants'; +import { useDeepEqualSelector } from './use_selector'; + +export const useRefetchQueries = () => { + const getQueriesSelector = useMemo(() => queriesSelector(), []); + const queries = useDeepEqualSelector((state: State) => + getQueriesSelector(state, InputsModelId.global) + ); + + const refetchPage = useCallback(() => { + queries.forEach((q) => q.refetch && (q.refetch as inputsModel.Refetch)()); + }, [queries]); + + return refetchPage; +}; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/throttle_description.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/throttle_description.tsx index 69110b2e53602..c0b6780ea8bc5 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/throttle_description.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/throttle_description.tsx @@ -6,10 +6,13 @@ */ import { find } from 'lodash/fp'; -import { THROTTLE_OPTIONS, DEFAULT_THROTTLE_OPTION } from '../throttle_select_field'; +import { + THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING, + DEFAULT_THROTTLE_OPTION, +} from '../throttle_select_field'; export const buildThrottleDescription = (value = DEFAULT_THROTTLE_OPTION.value, title: string) => { - const throttleOption = find(['value', value], THROTTLE_OPTIONS); + const throttleOption = find(['value', value], THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING); return { title, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/query_bar/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/query_bar/index.tsx index a5316eabb11f9..7d7c9534c1688 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/query_bar/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/query_bar/index.tsx @@ -70,6 +70,7 @@ const savedQueryToFieldValue = (savedQuery: SavedQuery): FieldValueQueryBar => ( filters: savedQuery.attributes.filters ?? [], query: savedQuery.attributes.query, saved_id: savedQuery.id, + title: savedQuery.attributes.title, }); export const QueryBarDefineRule = ({ 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 23042cd1165ec..21bf8125540b4 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 @@ -739,8 +739,8 @@ const StepDefineRuleComponent: FC = ({ <> = ({ 'data-test-subj': 'detectionEngineStepDefineRuleShouldLoadQueryDynamically', euiFieldProps: { disabled: isLoading, + label: formQuery?.title + ? i18n.getSavedQueryCheckboxLabel(formQuery.title) + : undefined, }, }} /> diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/schema.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/schema.tsx index bc3937013b6ae..b23b496eae82e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/schema.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/schema.tsx @@ -629,12 +629,6 @@ export const schema: FormSchema = { }, shouldLoadQueryDynamically: { type: FIELD_TYPES.CHECKBOX, - label: i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldShouldLoadQueryDynamicallyLabel', - { - defaultMessage: 'Load the saved query dynamically on each rule execution', - } - ), defaultValue: false, }, }; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/translations.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/translations.tsx index b28d06777fd3c..4650da2ce603a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/translations.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/translations.tsx @@ -78,13 +78,22 @@ export const EQL_QUERY_BAR_LABEL = i18n.translate( } ); -export const SAVED_QUERY_CHECKBOX_LABEL = i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.SavedQueryCheckboxLabel', +export const SAVED_QUERY_FORM_ROW_LABEL = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.SavedQueryFormRowLabel', { defaultMessage: 'Saved query', } ); +export const getSavedQueryCheckboxLabel = (savedQueryName: string) => + i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.fieldShouldLoadQueryDynamicallyLabel', + { + defaultMessage: 'Load saved query "{savedQueryName}" dynamically on each rule execution', + values: { savedQueryName }, + } + ); + export const THREAT_MATCH_INDEX_HELPER_TEXT = i18n.translate( 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.threatMatchingIcesHelperDescription', { 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 5cdf89df572cf..fe2c5d8fa4ee0 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 @@ -33,7 +33,7 @@ import { Form, UseField, useForm, useFormData } from '../../../../shared_imports import { StepContentWrapper } from '../step_content_wrapper'; import { ThrottleSelectField, - THROTTLE_OPTIONS, + THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING, DEFAULT_THROTTLE_OPTION, } from '../throttle_select_field'; import { RuleActionsField } from '../rule_actions_field'; @@ -62,11 +62,14 @@ const GhostFormField = () => <>; const getThrottleOptions = (throttle?: string | null) => { // Add support for throttle options set by the API - if (throttle && findIndex(['value', throttle], THROTTLE_OPTIONS) < 0) { - return [...THROTTLE_OPTIONS, { value: throttle, text: throttle }]; + if ( + throttle && + findIndex(['value', throttle], THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING) < 0 + ) { + return [...THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING, { value: throttle, text: throttle }]; } - return THROTTLE_OPTIONS; + return THROTTLE_OPTIONS_FOR_RULE_CREATION_AND_EDITING; }; const DisplayActionsHeader = () => { 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 c42e5e4b45976..04ad3a490c89a 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 @@ -95,6 +95,7 @@ const StepScheduleRuleComponent: FC = ({ idAria: 'detectionEngineStepScheduleRuleInterval', isDisabled: isLoading, dataTestSubj: 'detectionEngineStepScheduleRuleInterval', + minimumValue: 1, }} /> { const { data, isValid } = await form.submit(); @@ -121,7 +125,7 @@ const RuleActionsFormComponent = ({ rulesCount, onClose, onConfirm }: RuleAction dataTestSubj: 'bulkEditRulesRuleActionThrottle', hasNoInitialSelection: false, euiFieldProps: { - options: THROTTLE_OPTIONS, + options: THROTTLE_OPTIONS_FOR_BULK_RULE_ACTIONS, }, }), [] @@ -129,8 +133,6 @@ const RuleActionsFormComponent = ({ rulesCount, onClose, onConfirm }: RuleAction const messageVariables = useMemo(() => getAllActionMessageParams(), []); - const showActionsSelect = throttle !== NOTIFICATION_THROTTLE_NO_ACTIONS; - return ( -
  • - - - - ), - overwriteActionsCheckbox: ( - - - - ), - }} - /> -
  • {i18n.RULE_VARIABLES_DETAIL}
  • @@ -193,18 +171,14 @@ const RuleActionsFormComponent = ({ rulesCount, onClose, onConfirm }: RuleAction /> - {showActionsSelect && ( - <> - - - - )} + + ( ), diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/use_columns.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/use_columns.tsx index 3b413cf67e4d5..c5032a1eb9b72 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/use_columns.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/use_columns.tsx @@ -9,6 +9,7 @@ import type { EuiBasicTableColumn, EuiTableActionsColumnType } from '@elastic/eu import { EuiBadge, EuiLink, EuiText, EuiToolTip } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import React, { useMemo } from 'react'; +import moment from 'moment'; import { IntegrationsPopover } from '../../../../components/rules/related_integrations/integrations_popover'; import { DEFAULT_RELATIVE_DATE_THRESHOLD, @@ -387,7 +388,7 @@ export const useMonitoringColumns = ({ hasPermissions }: ColumnsProps): TableCol ), render: (value: DurationMetric | undefined) => ( - {value != null ? value.toFixed() : getEmptyTagValue()} + {value != null ? moment.duration(value, 'seconds').humanize() : getEmptyTagValue()} ), sortable: !!isInMemorySorting, 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 e91756ce74db4..5149269c57d9c 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 @@ -116,7 +116,7 @@ import { ExecutionLogTable } from './execution_log_table/execution_log_table'; import * as detectionI18n from '../../translations'; import * as ruleI18n from '../translations'; import { RuleDetailsContextProvider } from './rule_details_context'; -import { useGetSavedQuery } from '../../../../../common/hooks/use_get_saved_query'; +import { useGetSavedQuery } from './use_get_saved_query'; import * as i18n from './translations'; import { NeedAdminForUpdateRulesCallOut } from '../../../../components/callouts/need_admin_for_update_callout'; import { MissingPrivilegesCallOut } from '../../../../components/callouts/missing_privileges_callout'; @@ -307,6 +307,8 @@ const RuleDetailsPageComponent: React.FC = ({ const [dataViewOptions, setDataViewOptions] = useState<{ [x: string]: DataViewListItem }>({}); // load saved query only if rule type === 'saved_query', as other rule types still can have saved_id property that is not used + // Rule schema allows to save any rule with saved_id property, but it only used for saved_query rule type + // In future we might look in possibility to restrict rule schema (breaking change!) and remove saved_id from the rest of rules through migration const savedQueryId = rule?.type === 'saved_query' ? rule?.saved_id : undefined; const { isSavedQueryLoading, savedQueryBar } = useGetSavedQuery(savedQueryId); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/translations.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/translations.ts index 1a50d570ea179..b1c7e0033f5f4 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/translations.ts @@ -69,3 +69,10 @@ export const DELETED_RULE = i18n.translate( defaultMessage: 'Deleted rule', } ); + +export const SAVED_QUERY_LOAD_ERROR_TOAST = i18n.translate( + 'xpack.securitySolution.hooks.useGetSavedQuery.errorToastMessage', + { + defaultMessage: 'Failed to load the saved query', + } +); diff --git a/x-pack/plugins/security_solution/public/common/hooks/use_get_saved_query.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/use_get_saved_query.ts similarity index 81% rename from x-pack/plugins/security_solution/public/common/hooks/use_get_saved_query.ts rename to x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/use_get_saved_query.ts index 932fe61e2ce47..4c3c4c6c42fe0 100644 --- a/x-pack/plugins/security_solution/public/common/hooks/use_get_saved_query.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/use_get_saved_query.ts @@ -7,12 +7,13 @@ import { useEffect, useMemo } from 'react'; -import { useSavedQueryServices } from '../utils/saved_query_services'; -import type { DefineStepRule } from '../../detections/pages/detection_engine/rules/types'; +import { useSavedQueryServices } from '../../../../../common/utils/saved_query_services'; +import type { DefineStepRule } from '../types'; + +import { useFetch, REQUEST_NAMES } from '../../../../../common/hooks/use_fetch'; +import { useAppToasts } from '../../../../../common/hooks/use_app_toasts'; -import { useFetch, REQUEST_NAMES } from './use_fetch'; import { SAVED_QUERY_LOAD_ERROR_TOAST } from './translations'; -import { useAppToasts } from './use_app_toasts'; export const useGetSavedQuery = (savedQueryId: string | undefined) => { const savedQueryServices = useSavedQueryServices(); 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 f771eb46814da..997f40e918cb2 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 @@ -42,7 +42,6 @@ import { useInvalidateRules } from '../../../containers/detection_engine/rules/u import { useBoolState } from '../../../../common/hooks/use_bool_state'; import { RULES_TABLE_ACTIONS } from '../../../../common/lib/apm/user_actions'; import { useStartTransaction } from '../../../../common/lib/apm/use_start_transaction'; -import { RulesPageTourComponent } from './tour'; const RulesPageComponent: React.FC = () => { const [isImportModalVisible, showImportModal, hideImportModal] = useBoolState(); @@ -231,19 +230,17 @@ const RulesPageComponent: React.FC = () => { {i18n.IMPORT_RULE} - - - - {i18n.ADD_NEW_RULE} - - - + + + {i18n.ADD_NEW_RULE} + + {(prePackagedRuleStatus === 'ruleNeedUpdate' || diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/tour.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/tour.tsx deleted file mode 100644 index c13f6a7f67d40..0000000000000 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/tour.tsx +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { EuiText, EuiTourStep } from '@elastic/eui'; -import React, { useCallback, useEffect, useState } from 'react'; -import { RULES_MANAGEMENT_FEATURE_TOUR_STORAGE_KEY } from '../../../../../common/constants'; -import { useKibana } from '../../../../common/lib/kibana'; -import * as i18n from './translations'; - -export interface Props { - children: React.ReactElement; -} - -export const RulesPageTourComponent: React.FC = ({ children }) => { - const tourConfig = { - currentTourStep: 1, - isTourActive: true, - tourPopoverWidth: 300, - }; - - const { storage } = useKibana().services; - - const [tourState, setTourState] = useState(() => { - const restoredTourState = storage.get(RULES_MANAGEMENT_FEATURE_TOUR_STORAGE_KEY); - - if (restoredTourState != null) { - return restoredTourState; - } - return tourConfig; - }); - - const demoTourSteps = [ - { - step: 1, - title: i18n.NEW_TERMS_TOUR_TITLE, - content: {i18n.NEW_TERMS_TOUR_CONTENT}, - }, - ]; - const finishTour = useCallback(() => { - setTourState({ - ...tourState, - isTourActive: false, - }); - }, [tourState]); - - useEffect(() => { - storage.set(RULES_MANAGEMENT_FEATURE_TOUR_STORAGE_KEY, tourState); - }, [tourState, storage]); - - return ( - - {children} - - ); -}; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts index 1a5d16f719eba..f49e4695731bc 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts @@ -1084,20 +1084,6 @@ export const RULES_BULK_EDIT_FAILURE_DESCRIPTION = (rulesCount: number) => } ); -export const NEW_TERMS_TOUR_TITLE = i18n.translate( - 'xpack.securitySolution.detectionEngine.rules.tour.newTermsTitle', - { - defaultMessage: 'A new Security Rule type is available!', - } -); - -export const NEW_TERMS_TOUR_CONTENT = i18n.translate( - 'xpack.securitySolution.detectionEngine.rules.tour.newTermsContent', - { - defaultMessage: '"New Terms" rules alert on values that have not previously been seen', - } -); - export const RULE_PREVIEW_TITLE = i18n.translate( 'xpack.securitySolution.detectionEngine.createRule.rulePreviewTitle', { diff --git a/x-pack/plugins/security_solution/public/hosts/components/host_risk_information/index.tsx b/x-pack/plugins/security_solution/public/hosts/components/host_risk_information/index.tsx index 9ef78fe893aa7..361d982df180f 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/host_risk_information/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/host_risk_information/index.tsx @@ -131,7 +131,6 @@ const HostRiskInformationFlyout = ({ handleOnClose }: { handleOnClose: () => voi values={{ HostRiskScoreDocumentationLink: ( ( ({ filterQuery, from, indexNames, to, setQuery, skip, updateDateRange }) => { - const [loading, { isLicenseValid, isModuleEnabled }] = useHostRiskScore(); + const spaceId = useSpaceId(); + const defaultIndex = spaceId ? getHostRiskIndex(spaceId) : undefined; + const { isEnabled, isLicenseValid, isLoading } = useRiskScoreFeatureStatus( + RiskQueries.hostsRiskScore, + defaultIndex + ); return ( <> - {isLicenseValid && !isModuleEnabled && !loading && ( + {isLicenseValid && !isEnabled && !isLoading && ( <> ( <> {i18n.LEARN_MORE}{' '} diff --git a/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_score_tab_body.tsx b/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_score_tab_body.tsx index 27434a7b92b7b..25826de978b2c 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_score_tab_body.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_score_tab_body.tsx @@ -21,7 +21,7 @@ import { useHostRiskScoreKpi, } from '../../../risk_score/containers'; import { useQueryToggle } from '../../../common/containers/query_toggle'; -import { RiskScoreEntity } from '../../../../common/search_strategy'; +import { EMPTY_SEVERITY_COUNT, RiskScoreEntity } from '../../../../common/search_strategy'; import { EntityAnalyticsHostRiskScoreDisable } from '../../../common/components/risk_score/risk_score_disabled/host_risk_score_disabled'; import { RiskScoresNoDataDetected } from '../../../common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected'; @@ -60,6 +60,7 @@ export const HostRiskScoreQueryTabBody = ({ setQuerySkip(!toggleStatus); }, [toggleStatus]); const { from, to } = useGlobalTime(); + const timerange = useMemo(() => ({ from, to }), [from, to]); const [ loading, @@ -69,7 +70,7 @@ export const HostRiskScoreQueryTabBody = ({ skip: querySkip, pagination, sort, - timerange: { from, to }, + timerange, }); const { severityCount, loading: isKpiLoading } = useHostRiskScoreKpi({ @@ -77,13 +78,11 @@ export const HostRiskScoreQueryTabBody = ({ skip: querySkip, }); - const timerange = useMemo(() => ({ from, to }), [from, to]); - if (!isModuleEnabled && !loading) { return ; } - if (isDeprecated) { + if (isDeprecated && !loading) { return ( ; + if ( + !loading && + isModuleEnabled && + severitySelectionRedux.length === 0 && + data && + data.length === 0 + ) { + return ; } return ( @@ -109,7 +114,7 @@ export const HostRiskScoreQueryTabBody = ({ refetch={refetch} setQuery={setQuery} setQuerySkip={setQuerySkip} - severityCount={severityCount} + severityCount={severityCount ?? EMPTY_SEVERITY_COUNT} totalCount={totalCount} type={type} /> diff --git a/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_tab_body.tsx b/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_tab_body.tsx index adb4e97ad13be..84b4399c1dccf 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_tab_body.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/navigation/host_risk_tab_body.tsx @@ -69,7 +69,6 @@ const HostRiskTabBodyComponent: React.FC< useQueryToggle(`${QUERY_ID} overTime`); const { toggleStatus: contributorsToggleStatus, setToggleStatus: setContributorsToggleStatus } = useQueryToggle(`${QUERY_ID} contributors`); - const [loading, { data, refetch, inspect, isDeprecated, isModuleEnabled }] = useHostRiskScore({ filterQuery, onlyLatest: false, @@ -106,7 +105,7 @@ const HostRiskTabBodyComponent: React.FC< return ; } - if (isDeprecated) { + if (isDeprecated && !loading) { return ( ; + return ; } return ( diff --git a/x-pack/plugins/security_solution/public/jest.config.js b/x-pack/plugins/security_solution/public/jest.config.js index 5eb349b2c16e9..afa3e1b47efd4 100644 --- a/x-pack/plugins/security_solution/public/jest.config.js +++ b/x-pack/plugins/security_solution/public/jest.config.js @@ -14,7 +14,17 @@ module.exports = { coverageDirectory: '/target/kibana-coverage/jest/x-pack/plugins/security_solution/public', coverageReporters: ['text', 'html'], - collectCoverageFrom: ['/x-pack/plugins/security_solution/public/**/*.{ts,tsx}'], + collectCoverageFrom: [ + '/x-pack/plugins/security_solution/public/**/*.{ts,tsx}', + '!/x-pack/plugins/security_solution/public/*.test.{ts,tsx}', + '!/x-pack/plugins/security_solution/public/{__test__,__snapshots__,__examples__,*mock*,tests,test_helpers,integration_tests,types}/**/*', + '!/x-pack/plugins/security_solution/public/*mock*.{ts,tsx}', + '!/x-pack/plugins/security_solution/public/*.test.{ts,tsx}', + '!/x-pack/plugins/security_solution/public/*.d.ts', + '!/x-pack/plugins/security_solution/public/*.config.ts', + '!/x-pack/plugins/security_solution/public/index.{js,ts,tsx}', + ], + // See: https://github.com/elastic/kibana/issues/117255, the moduleNameMapper creates mocks to avoid memory leaks from kibana core. moduleNameMapper: { 'core/server$': '/x-pack/plugins/security_solution/server/__mocks__/core.mock.ts', diff --git a/x-pack/plugins/security_solution/public/management/common/breadcrumbs.ts b/x-pack/plugins/security_solution/public/management/common/breadcrumbs.ts index 12dfa0f28208a..8bb985df9610d 100644 --- a/x-pack/plugins/security_solution/public/management/common/breadcrumbs.ts +++ b/x-pack/plugins/security_solution/public/management/common/breadcrumbs.ts @@ -9,7 +9,11 @@ import type { ChromeBreadcrumb } from '@kbn/core/public'; import { AdministrationSubTab } from '../types'; import { ENDPOINTS_TAB, EVENT_FILTERS_TAB, POLICIES_TAB, TRUSTED_APPS_TAB } from './translations'; import type { AdministrationRouteSpyState } from '../../common/utils/route/types'; -import { HOST_ISOLATION_EXCEPTIONS, BLOCKLIST, ACTION_HISTORY } from '../../app/translations'; +import { + HOST_ISOLATION_EXCEPTIONS, + BLOCKLIST, + RESPONSE_ACTIONS_HISTORY, +} from '../../app/translations'; const TabNameMappedToI18nKey: Record = { [AdministrationSubTab.endpoints]: ENDPOINTS_TAB, @@ -18,7 +22,7 @@ const TabNameMappedToI18nKey: Record = { [AdministrationSubTab.eventFilters]: EVENT_FILTERS_TAB, [AdministrationSubTab.hostIsolationExceptions]: HOST_ISOLATION_EXCEPTIONS, [AdministrationSubTab.blocklist]: BLOCKLIST, - [AdministrationSubTab.actionHistory]: ACTION_HISTORY, + [AdministrationSubTab.responseActionsHistory]: RESPONSE_ACTIONS_HISTORY, }; export function getTrailingBreadcrumbs(params: AdministrationRouteSpyState): ChromeBreadcrumb[] { 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 afad5b78e9f4e..edaaa2d21a409 100644 --- a/x-pack/plugins/security_solution/public/management/common/constants.ts +++ b/x-pack/plugins/security_solution/public/management/common/constants.ts @@ -23,7 +23,7 @@ export const MANAGEMENT_ROUTING_TRUSTED_APPS_PATH = `${MANAGEMENT_PATH}/:tabName export const MANAGEMENT_ROUTING_EVENT_FILTERS_PATH = `${MANAGEMENT_PATH}/:tabName(${AdministrationSubTab.eventFilters})`; export const MANAGEMENT_ROUTING_HOST_ISOLATION_EXCEPTIONS_PATH = `${MANAGEMENT_PATH}/:tabName(${AdministrationSubTab.hostIsolationExceptions})`; export const MANAGEMENT_ROUTING_BLOCKLIST_PATH = `${MANAGEMENT_PATH}/:tabName(${AdministrationSubTab.blocklist})`; -export const MANAGEMENT_ROUTING_ACTION_HISTORY_PATH = `${MANAGEMENT_PATH}/:tabName(${AdministrationSubTab.actionHistory})`; +export const MANAGEMENT_ROUTING_RESPONSE_ACTIONS_HISTORY_PATH = `${MANAGEMENT_PATH}/:tabName(${AdministrationSubTab.responseActionsHistory})`; // --[ STORE ]--------------------------------------------------------------------------- /** The SIEM global store namespace where the management state will be mounted */ diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.test.tsx b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.test.tsx index 9160732e32b3e..6780335312251 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.test.tsx @@ -12,7 +12,7 @@ import { act, fireEvent, waitFor, waitForElementToBeRemoved } from '@testing-lib import userEvent from '@testing-library/user-event'; import type { ArtifactListPageRenderingSetup } from './mocks'; import { getArtifactListPageRenderingSetup } from './mocks'; -import { getDeferred } from '../mocks'; +import { getDeferred } from '../../mocks/utils'; jest.mock('../../../common/components/user_privileges'); diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.tsx b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.tsx index fc687282cccac..0586034d15550 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.tsx +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/artifact_list_page.tsx @@ -11,6 +11,7 @@ import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-t import { EuiButton, EuiSpacer, EuiText } from '@elastic/eui'; import type { EuiFlyoutSize } from '@elastic/eui/src/components/flyout/flyout'; import { useLocation } from 'react-router-dom'; +import { useIsMounted } from '@kbn/securitysolution-hook-utils'; import type { ServerApiError } from '../../../common/types'; import { AdministrationListPage } from '../administration_list_page'; @@ -45,7 +46,6 @@ import { useToasts } from '../../../common/lib/kibana'; import { useMemoizedRouteState } from '../../common/hooks'; import { BackToExternalAppSecondaryButton } from '../back_to_external_app_secondary_button'; import { BackToExternalAppButton } from '../back_to_external_app_button'; -import { useIsMounted } from '../../hooks/use_is_mounted'; type ArtifactEntryCardType = typeof ArtifactEntryCard; @@ -221,7 +221,7 @@ export const ArtifactListPage = memo( ); const handleArtifactDeleteModalOnSuccess = useCallback(() => { - if (isMounted) { + if (isMounted()) { setSelectedItemForDelete(undefined); refetchListData(); } diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_delete_modal.test.ts b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_delete_modal.test.ts index d0fb3e3c59dfa..57ea165f0b85f 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_delete_modal.test.ts +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_delete_modal.test.ts @@ -11,7 +11,7 @@ import type { ArtifactListPageRenderingSetup } from '../mocks'; import { getArtifactListPageRenderingSetup } from '../mocks'; import { act, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { getDeferred } from '../../mocks'; +import { getDeferred } from '../../../mocks/utils'; describe('When displaying the Delete artifact modal in the Artifact List Page', () => { let renderResult: ReturnType; diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx index ee3ac4a907ee4..5179bb7b76be6 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx @@ -19,7 +19,7 @@ import type { trustedAppsAllHttpMocks } from '../../../mocks'; import { useUserPrivileges as _useUserPrivileges } from '../../../../common/components/user_privileges'; import { entriesToConditionEntries } from '../../../../common/utils/exception_list_items/mappers'; import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { getDeferred } from '../../mocks'; +import { getDeferred } from '../../../mocks/utils'; jest.mock('../../../../common/components/user_privileges'); const useUserPrivileges = _useUserPrivileges as jest.Mock; diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.tsx b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.tsx index 4d9f53c73341e..1261d01c7af44 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.tsx +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.tsx @@ -24,6 +24,7 @@ import { import type { EuiFlyoutSize } from '@elastic/eui/src/components/flyout/flyout'; import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { useIsMounted } from '@kbn/securitysolution-hook-utils'; import { useUrlParams } from '../../../hooks/use_url_params'; import { useIsFlyoutOpened } from '../hooks/use_is_flyout_opened'; import { useTestIdGenerator } from '../../../hooks/use_test_id_generator'; @@ -39,7 +40,6 @@ import { useKibana, useToasts } from '../../../../common/lib/kibana'; import { createExceptionListItemForCreate } from '../../../../../common/endpoint/service/artifacts/utils'; import { useWithArtifactSubmitData } from '../hooks/use_with_artifact_submit_data'; import { useIsArtifactAllowedPerPolicyUsage } from '../hooks/use_is_artifact_allowed_per_policy_usage'; -import { useIsMounted } from '../../../hooks/use_is_mounted'; import { useGetArtifact } from '../../../hooks/artifacts'; import type { PolicyData } from '../../../../../common/endpoint/types'; @@ -271,7 +271,7 @@ export const ArtifactFlyout = memo( const handleFormComponentOnChange: ArtifactFormComponentProps['onChange'] = useCallback( ({ item: updatedItem, isValid }) => { - if (isMounted) { + if (isMounted()) { setFormState({ item: updatedItem, isValid, @@ -289,7 +289,7 @@ export const ArtifactFlyout = memo( : labels.flyoutCreateSubmitSuccess(result) ); - if (isMounted) { + if (isMounted()) { // Close the flyout // `undefined` will cause params to be dropped from url setUrlParams({ ...urlParams, itemId: undefined, show: undefined }, true); @@ -307,12 +307,12 @@ export const ArtifactFlyout = memo( submitHandler(formState.item, formMode) .then(handleSuccess) .catch((submitHandlerError) => { - if (isMounted) { + if (isMounted()) { setExternalSubmitHandlerError(submitHandlerError); } }) .finally(() => { - if (isMounted) { + if (isMounted()) { setExternalIsSubmittingData(false); } }); @@ -326,7 +326,7 @@ export const ArtifactFlyout = memo( useEffect(() => { if (isEditFlow && !hasItemDataForEdit && !error && isInitializing && !isLoadingItemForEdit) { fetchItemForEdit().then(({ data: editItemData }) => { - if (editItemData && isMounted) { + if (editItemData && isMounted()) { setFormState(createFormInitialState(apiClient.listId, editItemData)); } }); diff --git a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/hooks/use_with_artifact_list_data.ts b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/hooks/use_with_artifact_list_data.ts index 813e205b64c9a..ddae258fef895 100644 --- a/x-pack/plugins/security_solution/public/management/components/artifact_list_page/hooks/use_with_artifact_list_data.ts +++ b/x-pack/plugins/security_solution/public/management/components/artifact_list_page/hooks/use_with_artifact_list_data.ts @@ -8,8 +8,8 @@ import { useEffect, useMemo, useState } from 'react'; import type { Pagination } from '@elastic/eui'; import { useQuery } from '@tanstack/react-query'; +import { useIsMounted } from '@kbn/securitysolution-hook-utils'; import type { ServerApiError } from '../../../../common/types'; -import { useIsMounted } from '../../../hooks/use_is_mounted'; import { MANAGEMENT_PAGE_SIZE_OPTIONS } from '../../../common/constants'; import { useUrlParams } from '../../../hooks/use_url_params'; import type { ExceptionsListApiClient } from '../../../services/exceptions_list/exceptions_list_api_client'; @@ -98,7 +98,7 @@ export const useWithArtifactListData = ( // Once we know if data exists, update the page initializing state. // This should only ever happen at most once; useEffect(() => { - if (isMounted) { + if (isMounted()) { if (isPageInitializing && !isLoadingDataExists) { setIsPageInitializing(false); } @@ -107,7 +107,7 @@ export const useWithArtifactListData = ( // Update the uiPagination once the query succeeds useEffect(() => { - if (isMounted && listData && !isLoadingListData && isSuccessListData) { + if (isMounted() && listData && !isLoadingListData && isSuccessListData) { setUiPagination((prevState) => { return { ...prevState, @@ -134,7 +134,7 @@ export const useWithArtifactListData = ( // >> Check if data exists again (which should return true useEffect(() => { if ( - isMounted && + isMounted() && !isLoadingListData && !isLoadingDataExists && !listDataError && diff --git a/x-pack/plugins/security_solution/public/management/components/console/types.ts b/x-pack/plugins/security_solution/public/management/components/console/types.ts index 2d863e7878be2..5b90a18f27ce1 100644 --- a/x-pack/plugins/security_solution/public/management/components/console/types.ts +++ b/x-pack/plugins/security_solution/public/management/components/console/types.ts @@ -168,7 +168,7 @@ export type CommandExecutionComponent< /** The arguments that could have been entered by the user */ TArgs extends SupportedArguments = any, /** Internal store for the Command execution */ - TStore extends object = Record, + TStore extends object = any, /** The metadata defined on the Command Definition */ TMeta = any > = ComponentType>; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/action_log_button.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/action_log_button.tsx index 85a5f2655dd68..655bc0a6c8911 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/action_log_button.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/action_log_button.tsx @@ -29,8 +29,8 @@ export const ActionLogButton = memo((p data-test-subj="responderShowActionLogButton" > {showActionLogFlyout && ( diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.test.tsx index 29b6fd0446577..97689a790afa1 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.test.tsx @@ -129,7 +129,7 @@ describe('When using processes action from response actions console', () => { enterConsoleCommand(renderResult, 'processes'); await waitFor(() => { - expect(renderResult.getByTestId('getProcessesErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('getProcesses-actionFailure').textContent).toMatch( /error one \| error two/ ); }); @@ -145,7 +145,7 @@ describe('When using processes action from response actions console', () => { enterConsoleCommand(renderResult, 'processes'); await waitFor(() => { - expect(renderResult.getByTestId('performGetProcessesErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('getProcesses-apiFailure').textContent).toMatch( /this is an error/ ); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.tsx index c778f03fcb5f5..d7b05ae721abd 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/get_processes_action.tsx @@ -5,21 +5,17 @@ * 2.0. */ -import React, { memo, useEffect, useMemo } from 'react'; +import React, { memo, useMemo } from 'react'; import styled from 'styled-components'; import { EuiBasicTable } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; -import { FormattedMessage } from '@kbn/i18n-react'; +import { useConsoleActionSubmitter } from './hooks/use_console_action_submitter'; import type { - ActionDetails, GetProcessesActionOutputContent, + ProcessesRequestBody, } from '../../../../common/endpoint/types'; -import { useGetActionDetails } from '../../hooks/endpoint/use_get_action_details'; -import type { EndpointCommandDefinitionMeta } from './types'; -import type { CommandExecutionComponentProps } from '../console/types'; import { useSendGetEndpointProcessesRequest } from '../../hooks/endpoint/use_send_get_endpoint_processes_request'; -import { ActionError } from './action_error'; +import type { ActionRequestComponentProps } from './types'; // @ts-expect-error TS2769 const StyledEuiBasicTable = styled(EuiBasicTable)` @@ -43,181 +39,90 @@ const StyledEuiBasicTable = styled(EuiBasicTable)` } `; -export const GetProcessesActionResult = memo< - CommandExecutionComponentProps< - { comment?: string }, - { - actionId?: string; - actionRequestSent?: boolean; - completedActionDetails?: ActionDetails; - apiError?: IHttpFetchError; - }, - EndpointCommandDefinitionMeta - > ->(({ command, setStore, store, status, setStatus, ResultComponent }) => { - const endpointId = command.commandDefinition?.meta?.endpointId; - const { actionId, completedActionDetails, apiError } = store; - - const isPending = status === 'pending'; - const isError = status === 'error'; - const actionRequestSent = Boolean(store.actionRequestSent); - - const { - mutate: getProcesses, - data: getProcessesData, - isSuccess: isGetProcessesSuccess, - error: processesActionRequestError, - } = useSendGetEndpointProcessesRequest(); - - const { data: actionDetails } = useGetActionDetails( - actionId ?? '-', - { - enabled: Boolean(actionId) && isPending, - refetchInterval: isPending ? 3000 : false, - } - ); - - // Send get processes request if not yet done - useEffect(() => { - if (!actionRequestSent && endpointId) { - getProcesses({ - endpoint_ids: [endpointId], - comment: command.args.args?.comment?.[0], - }); - - setStore((prevState) => { - return { ...prevState, actionRequestSent: true }; - }); - } - }, [actionRequestSent, command.args.args?.comment, endpointId, getProcesses, setStore]); +export const GetProcessesActionResult = memo( + ({ command, setStore, store, status, setStatus, ResultComponent }) => { + const endpointId = command.commandDefinition?.meta?.endpointId; + const actionCreator = useSendGetEndpointProcessesRequest(); + + const actionRequestBody = useMemo(() => { + return endpointId + ? { + endpoint_ids: [endpointId], + comment: command.args.args?.comment?.[0], + } + : undefined; + }, [command.args.args?.comment, endpointId]); + + const { result, actionDetails: completedActionDetails } = useConsoleActionSubmitter< + ProcessesRequestBody, + GetProcessesActionOutputContent + >({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator, + actionRequestBody, + dataTestSubj: 'getProcesses', + }); + + const columns = useMemo( + () => [ + { + field: 'user', + name: i18n.translate( + 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.user', + { defaultMessage: 'USER' } + ), + width: '10%', + }, + { + field: 'pid', + name: i18n.translate( + 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.pid', + { defaultMessage: 'PID' } + ), + width: '5%', + }, + { + field: 'entity_id', + name: i18n.translate( + 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.enityId', + { defaultMessage: 'ENTITY ID' } + ), + width: '30%', + }, + + { + field: 'command', + name: i18n.translate( + 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.command', + { defaultMessage: 'COMMAND' } + ), + width: '55%', + }, + ], + [] + ); - // If get processes request was created, store the action id if necessary - useEffect(() => { - if (isPending) { - if (isGetProcessesSuccess && actionId !== getProcessesData?.data.id) { - setStore((prevState) => { - return { ...prevState, actionId: getProcessesData?.data.id }; - }); - } else if (processesActionRequestError) { - setStatus('error'); - setStore((prevState) => { - return { ...prevState, apiError: processesActionRequestError }; - }); + const tableEntries = useMemo(() => { + if (endpointId) { + return completedActionDetails?.outputs?.[endpointId]?.content.entries ?? []; } - } - }, [ - actionId, - getProcessesData?.data.id, - processesActionRequestError, - isGetProcessesSuccess, - setStatus, - setStore, - isPending, - ]); - - useEffect(() => { - if (actionDetails?.data.isCompleted && isPending) { - setStatus('success'); - setStore((prevState) => { - return { - ...prevState, - completedActionDetails: actionDetails?.data, - }; - }); - } - }, [actionDetails?.data, setStatus, setStore, isPending]); - - const columns = useMemo( - () => [ - { - field: 'user', - name: i18n.translate( - 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.user', - { defaultMessage: 'USER' } - ), - width: '10%', - }, - { - field: 'pid', - name: i18n.translate( - 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.pid', - { defaultMessage: 'PID' } - ), - width: '5%', - }, - { - field: 'entity_id', - name: i18n.translate( - 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.enityId', - { defaultMessage: 'ENTITY ID' } - ), - width: '30%', - }, - - { - field: 'command', - name: i18n.translate( - 'xpack.securitySolution.endpointResponseActions.getProcesses.table.header.command', - { defaultMessage: 'COMMAND' } - ), - width: '55%', - }, - ], - [] - ); + return []; + }, [completedActionDetails?.outputs, endpointId]); - const tableEntries = useMemo(() => { - if (endpointId) { - return completedActionDetails?.outputs?.[endpointId]?.content.entries ?? []; + if (!completedActionDetails || !completedActionDetails.wasSuccessful) { + return result; } - return []; - }, [completedActionDetails?.outputs, endpointId]); - - // Show nothing if still pending - if (isPending) { - return ; - } - // Show errors if perform action fails - if (isError && apiError) { + // Show results return ( - - + + ); } - - // Show errors - if (completedActionDetails?.errors) { - return ( - - ); - } - - // Show results - return ( - - - - ); -}); +); GetProcessesActionResult.displayName = 'GetProcessesActionResult'; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks.tsx deleted file mode 100644 index bbc390bb2ba53..0000000000000 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks.tsx +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { useEffect, useRef } from 'react'; -import { useIsMounted } from '../../hooks/use_is_mounted'; -import { useGetActionDetails } from '../../hooks/endpoint/use_get_action_details'; -import { ACTION_DETAILS_REFRESH_INTERVAL } from './constants'; -import type { ActionRequestState, ActionRequestComponentProps } from './types'; -import type { useSendIsolateEndpointRequest } from '../../hooks/endpoint/use_send_isolate_endpoint_request'; -import type { useSendReleaseEndpointRequest } from '../../hooks/endpoint/use_send_release_endpoint_request'; - -export const useUpdateActionState = ({ - actionRequestApi, - actionRequest, - command, - endpointId, - setStatus, - setStore, - isPending, -}: Pick & { - actionRequestApi: ReturnType< - typeof useSendIsolateEndpointRequest | typeof useSendReleaseEndpointRequest - >; - actionRequest?: ActionRequestState; - endpointId?: string; - isPending: boolean; -}) => { - const isMounted = useIsMounted(); - const actionRequestSent = Boolean(actionRequest?.requestSent); - const { data: actionDetails } = useGetActionDetails(actionRequest?.actionId ?? '-', { - enabled: Boolean(actionRequest?.actionId) && isPending, - refetchInterval: isPending ? ACTION_DETAILS_REFRESH_INTERVAL : false, - }); - - // keep a reference to track the console's mounted state - // in order to update the store and cause a re-render on action request API response - const latestIsMounted = useRef(false); - latestIsMounted.current = isMounted; - - // Create action request - useEffect(() => { - if (!actionRequestSent && endpointId && isMounted) { - const request: ActionRequestState = { - requestSent: true, - actionId: undefined, - }; - - actionRequestApi - .mutateAsync({ - endpoint_ids: [endpointId], - comment: command.args.args?.comment?.[0], - }) - .then((response) => { - request.actionId = response.data.id; - - if (latestIsMounted.current) { - setStore((prevState) => { - return { ...prevState, actionRequest: { ...request } }; - }); - } - }); - - setStore((prevState) => { - return { ...prevState, actionRequest: request }; - }); - } - }, [ - actionRequestApi, - actionRequestSent, - command.args.args?.comment, - endpointId, - isMounted, - setStore, - ]); - - useEffect(() => { - // update the console's mounted state ref - latestIsMounted.current = isMounted; - // set to false when unmounted/console is hidden - return () => { - latestIsMounted.current = false; - }; - }, [isMounted]); - - useEffect(() => { - if (actionDetails?.data.isCompleted && isPending) { - setStatus('success'); - setStore((prevState) => { - return { - ...prevState, - completedActionDetails: actionDetails.data, - }; - }); - } - }, [actionDetails?.data, actionDetails?.data.isCompleted, setStatus, setStore, isPending]); -}; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.test.tsx new file mode 100644 index 0000000000000..7ef506ea30f32 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.test.tsx @@ -0,0 +1,275 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { + UseConsoleActionSubmitterOptions, + ConsoleActionSubmitter, + CommandResponseActionApiState, +} from './use_console_action_submitter'; +import { useConsoleActionSubmitter } from './use_console_action_submitter'; +import type { AppContextTestRender } from '../../../../common/mock/endpoint'; +import { createAppRootMockRenderer } from '../../../../common/mock/endpoint'; +import { EndpointActionGenerator } from '../../../../../common/endpoint/data_generators/endpoint_action_generator'; +import React, { useState } from 'react'; +import type { CommandExecutionResultProps } from '../../console'; +import type { DeferredInterface } from '../../../mocks/utils'; +import { getDeferred } from '../../../mocks/utils'; +import type { ActionDetails } from '../../../../../common/endpoint/types'; +import { act, waitFor } from '@testing-library/react'; +import { responseActionsHttpMocks } from '../../../mocks/response_actions_http_mocks'; + +describe('When using `useConsoleActionSubmitter()` hook', () => { + let render: () => ReturnType; + let renderResult: ReturnType; + let renderArgs: UseConsoleActionSubmitterOptions; + let updateHookRenderArgs: () => void; + let hookRenderResultStorage: jest.Mock<(args: ConsoleActionSubmitter) => void>; + let releaseSuccessActionRequestApiResponse: DeferredInterface['resolve']; + let releaseFailedActionRequestApiResponse: DeferredInterface['reject']; + let apiMocks: ReturnType; + + const ActionSubmitterTestComponent = () => { + const [hookOptions, setHookOptions] = useState(renderArgs); + + updateHookRenderArgs = () => { + new Promise((r) => { + setTimeout(r, 1); + }).then(() => { + setHookOptions({ + ...renderArgs, + }); + }); + }; + + const { result, actionDetails } = useConsoleActionSubmitter(hookOptions); + + hookRenderResultStorage({ result, actionDetails }); + + return
    {result}
    ; + }; + + const getOutputTextContent = (): string => { + return renderResult.getByTestId('testContainer').textContent ?? ''; + }; + + beforeEach(() => { + const { render: renderComponent, coreStart } = createAppRootMockRenderer(); + const actionGenerator = new EndpointActionGenerator(); + const deferred = getDeferred(); + + apiMocks = responseActionsHttpMocks(coreStart.http); + + hookRenderResultStorage = jest.fn(); + releaseSuccessActionRequestApiResponse = () => + deferred.resolve(actionGenerator.generateActionDetails({ id: '123' })); + releaseFailedActionRequestApiResponse = deferred.reject; + + let status: UseConsoleActionSubmitterOptions['status'] = 'pending'; + let commandStore: CommandResponseActionApiState = {}; + + renderArgs = { + dataTestSubj: 'test', + actionRequestBody: { + endpoint_ids: ['123'], + }, + actionCreator: { + mutateAsync: jest.fn(async () => { + return { + data: await deferred.promise, + }; + }), + } as unknown as UseConsoleActionSubmitterOptions['actionCreator'], + get status() { + return status; + }, + setStatus: jest.fn((newStatus) => { + status = newStatus; + updateHookRenderArgs(); + }), + get store() { + return commandStore; + }, + setStore: jest.fn((newStoreOrCallback: object | ((prevStore: object) => object)) => { + if (typeof newStoreOrCallback === 'function') { + commandStore = newStoreOrCallback(commandStore); + } else { + commandStore = newStoreOrCallback; + } + + updateHookRenderArgs(); + }), + ResultComponent: jest.fn( + ({ children, showAs, 'data-test-subj': dataTestSubj }: CommandExecutionResultProps) => { + return ( +
    + {children} +
    + ); + } + ), + }; + + render = () => { + renderResult = renderComponent(); + return renderResult; + }; + }); + + afterEach(() => { + renderResult.unmount(); + }); + + it('should return expected interface while its still pending', () => { + render(); + + expect(hookRenderResultStorage).toHaveBeenLastCalledWith({ + result: expect.anything(), + action: undefined, + }); + + expect(renderResult.getByTestId('test-pending')).not.toBeNull(); + }); + + it('should update command state when request is sent', () => { + render(); + + expect(renderArgs.store?.actionApiState?.request.sent).toBe(true); + expect(renderArgs.store?.actionApiState?.request.actionId).toBe(undefined); + }); + + it('should store the action id when action request api is successful', async () => { + render(); + + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + expect(renderArgs.store?.actionApiState?.request.actionId).toBe('123'); + }); + }); + + it('should store action request api error', async () => { + render(); + const error = new Error('oh oh. request failed'); + + act(() => { + releaseFailedActionRequestApiResponse(error); + }); + + await waitFor(() => { + expect(renderArgs.store?.actionApiState?.request.actionId).toBe(undefined); + expect(renderArgs.store?.actionApiState?.request.error).toBe(error); + }); + + await waitFor(() => { + expect(getOutputTextContent()).toEqual( + 'The following error was encountered:oh oh. request failed' + ); + }); + }); + + it('should still store the action id if component is unmounted while action request API is in flight', async () => { + render(); + renderResult.unmount(); + + expect(renderArgs.store.actionApiState?.request.sent).toBe(true); + + const requestState = renderArgs.store.actionApiState?.request; + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + // this check just ensure that we mutated the state when the api returned success instead of + // dispatching a `setStore()`. + expect(renderArgs.store.actionApiState?.request === requestState).toBe(true); + + expect(renderArgs.store.actionApiState?.request.actionId).toEqual('123'); + }); + }); + + it('should call action details api once we have an action id', async () => { + render(); + + expect(apiMocks.responseProvider.actionDetails).not.toHaveBeenCalled(); + + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + expect(apiMocks.responseProvider.actionDetails).toHaveBeenCalledWith({ + path: '/api/endpoint/action/123', + }); + }); + }); + + it('should continue to show pending message until action completes', async () => { + apiMocks.responseProvider.actionDetails.mockImplementation(() => { + return { + data: new EndpointActionGenerator().generateActionDetails({ + id: '123', + isCompleted: false, + }), + }; + }); + render(); + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + expect(apiMocks.responseProvider.actionDetails).toHaveBeenCalledWith({ + path: '/api/endpoint/action/123', + }); + }); + + expect(renderResult.getByTestId('test-pending')).not.toBeNull(); + + expect(hookRenderResultStorage).toHaveBeenLastCalledWith({ + result: expect.anything(), + actionDetails: undefined, + }); + }); + + it('should store action details api error', async () => { + const error = new Error('on oh. getting action details failed'); + apiMocks.responseProvider.actionDetails.mockImplementation(() => { + throw error; + }); + + render(); + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + expect(apiMocks.responseProvider.actionDetails).toHaveBeenCalledWith({ + path: '/api/endpoint/action/123', + }); + }); + + expect(renderArgs.store.actionApiState?.actionDetailsError).toBe(error); + + expect(renderResult.getByTestId('test-apiFailure').textContent).toEqual( + 'The following error was encountered:on oh. getting action details failed' + ); + }); + + it('should store action details once action completes', async () => { + const actionDetails = new EndpointActionGenerator().generateActionDetails({ id: '123' }); + apiMocks.responseProvider.actionDetails.mockReturnValue({ data: actionDetails }); + + render(); + releaseSuccessActionRequestApiResponse(); + + await waitFor(() => { + expect(apiMocks.responseProvider.actionDetails).toHaveBeenCalledWith({ + path: '/api/endpoint/action/123', + }); + }); + + expect(renderArgs.store.actionApiState?.actionDetails).toBe(actionDetails); + expect(hookRenderResultStorage).toHaveBeenLastCalledWith({ + result: expect.anything(), + actionDetails, + }); + + expect(renderResult.getByTestId('test-success').textContent).toEqual(''); + }); +}); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.tsx new file mode 100644 index 0000000000000..7183b5cc61ef7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/hooks/use_console_action_submitter.tsx @@ -0,0 +1,292 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useEffect, useMemo } from 'react'; +import type { UseMutationResult } from '@tanstack/react-query'; +import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { useIsMounted } from '@kbn/securitysolution-hook-utils'; +import { useTestIdGenerator } from '../../../hooks/use_test_id_generator'; +import type { BaseActionRequestBody } from '../../../../../common/endpoint/schema/actions'; +import { ActionSuccess } from '../action_success'; +import { ActionError } from '../action_error'; +import { FormattedError } from '../../formatted_error'; +import { useGetActionDetails } from '../../../hooks/endpoint/use_get_action_details'; +import { ACTION_DETAILS_REFRESH_INTERVAL } from '../constants'; +import type { + ActionDetails, + Immutable, + ResponseActionApiResponse, +} from '../../../../../common/endpoint/types'; +import type { CommandExecutionComponentProps } from '../../console'; + +export interface ConsoleActionSubmitter { + /** + * The ui to be returned to the console. This UI will display different states of the action, + * including pending, error conditions and generic success messages. + */ + result: JSX.Element; + actionDetails: Immutable> | undefined; +} + +/** + * Command store state for response action api state. + */ +export interface CommandResponseActionApiState { + actionApiState?: { + request: { + sent: boolean; + actionId: string | undefined; + error: IHttpFetchError | undefined; + }; + actionDetails: ActionDetails | undefined; + actionDetailsError: IHttpFetchError | undefined; + }; +} + +export interface UseConsoleActionSubmitterOptions< + TReqBody extends BaseActionRequestBody = BaseActionRequestBody, + TActionOutputContent extends object = object +> extends Pick< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + CommandExecutionComponentProps>, + 'ResultComponent' | 'setStore' | 'store' | 'status' | 'setStatus' + > { + actionCreator: UseMutationResult; + /** + * The API request body. If `undefined`, then API will not be called. + */ + actionRequestBody: TReqBody | undefined; + + dataTestSubj?: string; +} + +/** + * generic hook for use with Response Action commands. It will create the action, store its ID and + * continuously pull the Action's Details until it completes. It handles all aspects of UI display + * for the different states of the command (pending -> success/failure) + * + * @param actionCreator + * @param actionRequestBody + * @param setStatus + * @param status + * @param setStore + * @param store + * @param ResultComponent + * @param dataTestSubj + */ +export const useConsoleActionSubmitter = < + TReqBody extends BaseActionRequestBody = BaseActionRequestBody, + TActionOutputContent extends object = object +>({ + actionCreator, + actionRequestBody, + setStatus, + status, + setStore, + store, + ResultComponent, + dataTestSubj, +}: UseConsoleActionSubmitterOptions< + TReqBody, + TActionOutputContent +>): ConsoleActionSubmitter => { + const isMounted = useIsMounted(); + const getTestId = useTestIdGenerator(dataTestSubj); + const isPending = status === 'pending'; + + const currentActionState = useMemo< + Immutable>['actionApiState']> + >( + () => + store.actionApiState ?? { + request: { + sent: false, + error: undefined, + actionId: undefined, + }, + actionDetails: undefined, + actionDetailsError: undefined, + }, + [store.actionApiState] + ); + + const { actionDetails, actionDetailsError } = currentActionState; + const { + actionId, + sent: actionRequestSent, + error: actionRequestError, + } = currentActionState.request; + + const { data: apiActionDetailsResponse, error: apiActionDetailsError } = + useGetActionDetails(actionId ?? '-', { + enabled: Boolean(actionId) && isPending, + refetchInterval: isPending ? ACTION_DETAILS_REFRESH_INTERVAL : false, + }); + + // Create the action request if not yet done + useEffect(() => { + if (!actionRequestSent && actionRequestBody && isMounted()) { + const updatedRequestState: Required< + CommandResponseActionApiState + >['actionApiState']['request'] = { + ...( + currentActionState as Required< + CommandResponseActionApiState + >['actionApiState'] + ).request, + sent: true, + }; + + // The object defined above (`updatedRequestState`) is saved to the command state right away. + // the creation of the Action request (below) will mutate this object to store the Action ID + // once the API response is received. We do this to ensure that the action is not created more + // than once if the user happens to close the console prior to the response being returned. + // Once a response is received, we check if the component is mounted, and if so, then we send + // another update to the command store which will cause it to re-render and start checking for + // action completion. + actionCreator + .mutateAsync(actionRequestBody) + .then((response) => { + updatedRequestState.actionId = response.data.id; + }) + .catch((err) => { + updatedRequestState.error = err; + }) + .finally(() => { + // If the component is mounted, then set the store with the updated data (causes a rerender) + if (isMounted()) { + setStore((prevState) => { + return { + ...prevState, + actionApiState: { + ...(prevState.actionApiState ?? currentActionState), + request: { ...updatedRequestState }, + }, + }; + }); + } + }); + + setStore((prevState) => { + return { + ...prevState, + actionApiState: { + ...(prevState.actionApiState ?? currentActionState), + request: updatedRequestState, + }, + }; + }); + } + }, [ + actionCreator, + actionRequestBody, + actionRequestSent, + currentActionState, + isMounted, + setStore, + ]); + + // If an error was returned while attempting to create the action request, + // then set command status to error + useEffect(() => { + if (actionRequestError && isPending) { + setStatus('error'); + } + }, [actionRequestError, isPending, setStatus]); + + // If an error was return by the Action Details API, then store it and set the status to error + useEffect(() => { + if (apiActionDetailsError && isPending) { + setStatus('error'); + setStore((prevState) => { + return { + ...prevState, + actionApiState: { + ...(prevState.actionApiState ?? currentActionState), + actionDetails: undefined, + actionDetailsError: apiActionDetailsError, + }, + }; + }); + } + }, [apiActionDetailsError, currentActionState, isPending, setStatus, setStore]); + + // If the action details indicates complete, then update the action's console state and set the status to success + useEffect(() => { + if (apiActionDetailsResponse?.data.isCompleted && isPending) { + setStatus(apiActionDetailsResponse?.data.wasSuccessful ? 'success' : 'error'); + setStore((prevState) => { + return { + ...prevState, + actionApiState: { + ...(prevState.actionApiState ?? currentActionState), + actionDetails: apiActionDetailsResponse.data, + }, + // Unclear why I needed to cast this here. For some reason the `ActionDetails['outputs']` is + // reporting a type error for the `content` property, although the types seem to line up. + } as typeof prevState; + }); + } + }, [apiActionDetailsResponse, currentActionState, isPending, setStatus, setStore]); + + // Calculate the action's UI result based on the different API responses + const result = useMemo(() => { + if (isPending) { + return ; + } + + const apiError = actionRequestError || actionDetailsError; + + if (apiError) { + return ( + + + + + ); + } + + if (actionDetails) { + // Response action failures + if (actionDetails.errors) { + return ( + + ); + } + + return ( + + ); + } + + return <>; + }, [ + isPending, + actionRequestError, + actionDetailsError, + actionDetails, + ResultComponent, + getTestId, + ]); + + return { + result, + actionDetails: currentActionState.actionDetails, + }; +}; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.test.tsx index 63e05d420deaf..110ddbb53b1b0 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.test.tsx @@ -16,9 +16,9 @@ import { getEndpointResponseActionsConsoleCommands } from './endpoint_response_a import { responseActionsHttpMocks } from '../../mocks/response_actions_http_mocks'; import { enterConsoleCommand } from '../console/mocks'; import { waitFor } from '@testing-library/react'; -import { getDeferred } from '../mocks'; import type { ResponderCapabilities } from '../../../../common/endpoint/constants'; import { RESPONDER_CAPABILITIES } from '../../../../common/endpoint/constants'; +import { getDeferred } from '../../mocks/utils'; describe('When using isolate action from response actions console', () => { let render: ( @@ -115,7 +115,7 @@ describe('When using isolate action from response actions console', () => { enterConsoleCommand(renderResult, 'isolate'); await waitFor(() => { - expect(renderResult.getByTestId('isolateSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('isolate-success')).toBeTruthy(); }); }); @@ -130,7 +130,7 @@ describe('When using isolate action from response actions console', () => { enterConsoleCommand(renderResult, 'isolate'); await waitFor(() => { - expect(renderResult.getByTestId('isolateErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('isolate-actionFailure').textContent).toMatch( /error one \| error two/ ); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.tsx index ec11d022650ca..8df7692cf3ac2 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/isolate_action.tsx @@ -5,47 +5,37 @@ * 2.0. */ -import React, { memo } from 'react'; +import { memo, useMemo } from 'react'; +import { useConsoleActionSubmitter } from './hooks/use_console_action_submitter'; import type { ActionRequestComponentProps } from './types'; import { useSendIsolateEndpointRequest } from '../../hooks/endpoint/use_send_isolate_endpoint_request'; -import { ActionError } from './action_error'; -import { useUpdateActionState } from './hooks'; export const IsolateActionResult = memo( ({ command, setStore, store, status, setStatus, ResultComponent }) => { - const endpointId = command.commandDefinition?.meta?.endpointId; - const { completedActionDetails, actionRequest } = store; - const isPending = status === 'pending'; const isolateHostApi = useSendIsolateEndpointRequest(); - useUpdateActionState({ - actionRequestApi: isolateHostApi, - actionRequest, - command, - endpointId, - setStatus, - setStore, - isPending, - }); - - // Show nothing if still pending - if (isPending) { - return ; - } + const actionRequestBody = useMemo(() => { + const endpointId = command.commandDefinition?.meta?.endpointId; + const comment = command.args.args?.comment?.[0]; - // Show errors - if (completedActionDetails?.errors) { - return ( - - ); - } + return endpointId + ? { + endpoint_ids: [endpointId], + comment, + } + : undefined; + }, [command.args.args?.comment, command.commandDefinition?.meta?.endpointId]); - // Show Success - return ; + return useConsoleActionSubmitter({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator: isolateHostApi, + actionRequestBody, + dataTestSubj: 'isolate', + }).result; } ); IsolateActionResult.displayName = 'IsolateActionResult'; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.test.tsx index 827a4d6191754..f888df2099b13 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.test.tsx @@ -195,7 +195,7 @@ describe('When using the kill-process action from response actions console', () enterConsoleCommand(renderResult, 'kill-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('killProcessSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('killProcess-success')).toBeTruthy(); }); }); @@ -204,7 +204,7 @@ describe('When using the kill-process action from response actions console', () enterConsoleCommand(renderResult, 'kill-process --entityId 123wer'); await waitFor(() => { - expect(renderResult.getByTestId('killProcessSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('killProcess-success')).toBeTruthy(); }); }); @@ -219,7 +219,7 @@ describe('When using the kill-process action from response actions console', () enterConsoleCommand(renderResult, 'kill-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('killProcessErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('killProcess-actionFailure').textContent).toMatch( /error one \| error two/ ); }); @@ -234,7 +234,7 @@ describe('When using the kill-process action from response actions console', () enterConsoleCommand(renderResult, 'kill-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('killProcessAPIErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('killProcess-apiFailure').textContent).toMatch( /this is an error/ ); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.tsx index 3e4dcf61d1690..bf501c31b9e85 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/kill_process_action.tsx @@ -5,130 +5,40 @@ * 2.0. */ -import React, { memo, useEffect } from 'react'; -import { FormattedMessage } from '@kbn/i18n-react'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { memo, useMemo } from 'react'; +import type { KillOrSuspendProcessRequestBody } from '../../../../common/endpoint/types'; import { parsedPidOrEntityIdParameter } from './utils'; -import { ActionSuccess } from './action_success'; -import type { - ActionDetails, - KillProcessActionOutputContent, -} from '../../../../common/endpoint/types'; -import { useGetActionDetails } from '../../hooks/endpoint/use_get_action_details'; -import type { EndpointCommandDefinitionMeta } from './types'; import { useSendKillProcessRequest } from '../../hooks/endpoint/use_send_kill_process_endpoint_request'; -import type { CommandExecutionComponentProps } from '../console/types'; -import { ActionError } from './action_error'; -import { ACTION_DETAILS_REFRESH_INTERVAL } from './constants'; +import type { ActionRequestComponentProps } from './types'; +import { useConsoleActionSubmitter } from './hooks/use_console_action_submitter'; export const KillProcessActionResult = memo< - CommandExecutionComponentProps< - { comment?: string; pid?: string; entityId?: string }, - { - actionId?: string; - actionRequestSent?: boolean; - completedActionDetails?: ActionDetails; - apiError?: IHttpFetchError; - }, - EndpointCommandDefinitionMeta - > + ActionRequestComponentProps<{ pid?: string[]; entityId?: string[] }> >(({ command, setStore, store, status, setStatus, ResultComponent }) => { - const endpointId = command.commandDefinition?.meta?.endpointId; - const { actionId, completedActionDetails, apiError } = store; - const isPending = status === 'pending'; - const isError = status === 'error'; - const actionRequestSent = Boolean(store.actionRequestSent); + const actionCreator = useSendKillProcessRequest(); - const { mutate, data, isSuccess, error } = useSendKillProcessRequest(); - - const { data: actionDetails } = useGetActionDetails( - actionId ?? '-', - { - enabled: Boolean(actionId) && isPending, - refetchInterval: isPending ? ACTION_DETAILS_REFRESH_INTERVAL : false, - } - ); - - // Send Kill request if not yet done - useEffect(() => { + const actionRequestBody = useMemo(() => { + const endpointId = command.commandDefinition?.meta?.endpointId; const parameters = parsedPidOrEntityIdParameter(command.args.args); - if (!actionRequestSent && endpointId && parameters) { - mutate({ - endpoint_ids: [endpointId], - comment: command.args.args?.comment?.[0], - parameters, - }); - setStore((prevState) => { - return { ...prevState, actionRequestSent: true }; - }); - } - }, [actionRequestSent, command.args.args, endpointId, mutate, setStore]); - - // If kill-process request was created, store the action id if necessary - useEffect(() => { - if (isPending) { - if (isSuccess && actionId !== data.data.id) { - setStore((prevState) => { - return { ...prevState, actionId: data.data.id }; - }); - } else if (error) { - setStatus('error'); - setStore((prevState) => { - return { ...prevState, apiError: error }; - }); - } - } - }, [actionId, data?.data.id, isSuccess, error, setStore, setStatus, isPending]); - - useEffect(() => { - if (actionDetails?.data.isCompleted && isPending) { - setStatus('success'); - setStore((prevState) => { - return { - ...prevState, - completedActionDetails: actionDetails.data, - }; - }); - } - }, [actionDetails?.data, setStatus, setStore, isPending]); - - // Show API errors if perform action fails - if (isError && apiError) { - return ( - - - - ); - } - - // Show nothing if still pending - if (isPending || !completedActionDetails) { - return ; - } - - // Show errors - if (completedActionDetails?.errors) { - return ( - - ); - } - - // Show Success - return ( - - ); + return endpointId + ? { + endpoint_ids: [endpointId], + comment: command.args.args?.comment?.[0], + parameters, + } + : undefined; + }, [command.args.args, command.commandDefinition?.meta?.endpointId]); + + return useConsoleActionSubmitter({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator, + actionRequestBody, + dataTestSubj: 'killProcess', + }).result; }); KillProcessActionResult.displayName = 'KillProcessActionResult'; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.test.tsx index 19e3be94469eb..d1c1ea264f863 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.test.tsx @@ -16,9 +16,9 @@ import { getEndpointResponseActionsConsoleCommands } from './endpoint_response_a import { enterConsoleCommand } from '../console/mocks'; import { waitFor } from '@testing-library/react'; import { responseActionsHttpMocks } from '../../mocks/response_actions_http_mocks'; -import { getDeferred } from '../mocks'; import type { ResponderCapabilities } from '../../../../common/endpoint/constants'; import { RESPONDER_CAPABILITIES } from '../../../../common/endpoint/constants'; +import { getDeferred } from '../../mocks/utils'; describe('When using the release action from response actions console', () => { let render: ( @@ -116,7 +116,7 @@ describe('When using the release action from response actions console', () => { enterConsoleCommand(renderResult, 'release'); await waitFor(() => { - expect(renderResult.getByTestId('releaseSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('release-success')).toBeTruthy(); }); }); @@ -131,7 +131,7 @@ describe('When using the release action from response actions console', () => { enterConsoleCommand(renderResult, 'release'); await waitFor(() => { - expect(renderResult.getByTestId('releaseErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('release-actionFailure').textContent).toMatch( /error one \| error two/ ); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.tsx index f789b48671324..9b0f371ca003f 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/release_action.tsx @@ -5,48 +5,37 @@ * 2.0. */ -import React, { memo } from 'react'; +import { memo, useMemo } from 'react'; import type { ActionRequestComponentProps } from './types'; import { useSendReleaseEndpointRequest } from '../../hooks/endpoint/use_send_release_endpoint_request'; -import { ActionError } from './action_error'; -import { useUpdateActionState } from './hooks'; +import { useConsoleActionSubmitter } from './hooks/use_console_action_submitter'; export const ReleaseActionResult = memo( ({ command, setStore, store, status, setStatus, ResultComponent }) => { - const endpointId = command.commandDefinition?.meta?.endpointId; - const { completedActionDetails, actionRequest } = store; - const isPending = status === 'pending'; - const releaseHostApi = useSendReleaseEndpointRequest(); - useUpdateActionState({ - actionRequestApi: releaseHostApi, - actionRequest, - command, - endpointId, - setStatus, - setStore, - isPending, - }); - - // Show nothing if still pending - if (isPending) { - return ; - } + const actionRequestBody = useMemo(() => { + const endpointId = command.commandDefinition?.meta?.endpointId; + const comment = command.args.args?.comment?.[0]; - // Show errors - if (completedActionDetails?.errors) { - return ( - - ); - } + return endpointId + ? { + endpoint_ids: [endpointId], + comment, + } + : undefined; + }, [command.args.args?.comment, command.commandDefinition?.meta?.endpointId]); - // Show Success - return ; + return useConsoleActionSubmitter({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator: releaseHostApi, + actionRequestBody, + dataTestSubj: 'release', + }).result; } ); ReleaseActionResult.displayName = 'ReleaseActionResult'; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.test.tsx index 9446fb5dcba6a..7479e52edfb07 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.test.tsx @@ -186,7 +186,7 @@ describe('When using the suspend-process action from response actions console', enterConsoleCommand(renderResult, 'suspend-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('suspendProcessSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('suspendProcess-success')).toBeTruthy(); }); }); @@ -195,7 +195,7 @@ describe('When using the suspend-process action from response actions console', enterConsoleCommand(renderResult, 'suspend-process --entityId 123wer'); await waitFor(() => { - expect(renderResult.getByTestId('suspendProcessSuccessCallout')).toBeTruthy(); + expect(renderResult.getByTestId('suspendProcess-success')).toBeTruthy(); }); }); @@ -210,7 +210,7 @@ describe('When using the suspend-process action from response actions console', enterConsoleCommand(renderResult, 'suspend-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('suspendProcessErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('suspendProcess-actionFailure').textContent).toMatch( /error one \| error two/ ); }); @@ -225,7 +225,7 @@ describe('When using the suspend-process action from response actions console', enterConsoleCommand(renderResult, 'suspend-process --pid 123'); await waitFor(() => { - expect(renderResult.getByTestId('suspendProcessAPIErrorCallout').textContent).toMatch( + expect(renderResult.getByTestId('suspendProcess-apiFailure').textContent).toMatch( /this is an error/ ); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.tsx index a60e7eb6bd65b..f8401a81fa114 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/suspend_process_action.tsx @@ -5,130 +5,46 @@ * 2.0. */ -import React, { memo, useEffect } from 'react'; -import { FormattedMessage } from '@kbn/i18n-react'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { memo, useMemo } from 'react'; import { parsedPidOrEntityIdParameter } from './utils'; -import { ActionSuccess } from './action_success'; import type { - ActionDetails, SuspendProcessActionOutputContent, + KillOrSuspendProcessRequestBody, } from '../../../../common/endpoint/types'; -import { useGetActionDetails } from '../../hooks/endpoint/use_get_action_details'; -import type { EndpointCommandDefinitionMeta } from './types'; import { useSendSuspendProcessRequest } from '../../hooks/endpoint/use_send_suspend_process_endpoint_request'; -import type { CommandExecutionComponentProps } from '../console/types'; -import { ActionError } from './action_error'; -import { ACTION_DETAILS_REFRESH_INTERVAL } from './constants'; +import type { ActionRequestComponentProps } from './types'; +import { useConsoleActionSubmitter } from './hooks/use_console_action_submitter'; export const SuspendProcessActionResult = memo< - CommandExecutionComponentProps< - { comment?: string; pid?: string; entityId?: string }, - { - actionId?: string; - actionRequestSent?: boolean; - completedActionDetails?: ActionDetails; - apiError?: IHttpFetchError; - }, - EndpointCommandDefinitionMeta - > + ActionRequestComponentProps<{ pid?: string[]; entityId?: string[] }> >(({ command, setStore, store, status, setStatus, ResultComponent }) => { - const endpointId = command.commandDefinition?.meta?.endpointId; - const { actionId, completedActionDetails, apiError } = store; - const isPending = status === 'pending'; - const isError = status === 'error'; - const actionRequestSent = Boolean(store.actionRequestSent); + const actionCreator = useSendSuspendProcessRequest(); - const { mutate, data, isSuccess, error } = useSendSuspendProcessRequest(); - - const { data: actionDetails } = useGetActionDetails( - actionId ?? '-', - { - enabled: Boolean(actionId) && isPending, - refetchInterval: isPending ? ACTION_DETAILS_REFRESH_INTERVAL : false, - } - ); - - // Send Suspend request if not yet done - useEffect(() => { + const actionRequestBody = useMemo(() => { + const endpointId = command.commandDefinition?.meta?.endpointId; const parameters = parsedPidOrEntityIdParameter(command.args.args); - if (!actionRequestSent && endpointId && parameters) { - mutate({ - endpoint_ids: [endpointId], - comment: command.args.args?.comment?.[0], - parameters, - }); - setStore((prevState) => { - return { ...prevState, actionRequestSent: true }; - }); - } - }, [actionRequestSent, command.args.args, endpointId, mutate, setStore]); - - // If suspend-process request was created, store the action id if necessary - useEffect(() => { - if (isPending) { - if (isSuccess && actionId !== data.data.id) { - setStore((prevState) => { - return { ...prevState, actionId: data.data.id }; - }); - } else if (error) { - setStatus('error'); - setStore((prevState) => { - return { ...prevState, apiError: error }; - }); - } - } - }, [actionId, data?.data.id, isSuccess, error, setStore, setStatus, isPending]); - - useEffect(() => { - if (actionDetails?.data.isCompleted && isPending) { - setStatus('success'); - setStore((prevState) => { - return { - ...prevState, - completedActionDetails: actionDetails.data, - }; - }); - } - }, [actionDetails?.data, setStatus, setStore, isPending]); - - // Show API errors if perform action fails - if (isError && apiError) { - return ( - - - - ); - } - - // Show nothing if still pending - if (isPending || !completedActionDetails) { - return ; - } - - // Show errors - if (completedActionDetails?.errors) { - return ( - - ); - } - - // Show Success - return ( - - ); + return endpointId + ? { + endpoint_ids: [endpointId], + comment: command.args.args?.comment?.[0], + parameters, + } + : undefined; + }, [command.args.args, command.commandDefinition?.meta?.endpointId]); + + return useConsoleActionSubmitter< + KillOrSuspendProcessRequestBody, + SuspendProcessActionOutputContent + >({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator, + actionRequestBody, + dataTestSubj: 'suspendProcess', + }).result; }); SuspendProcessActionResult.displayName = 'SuspendProcessActionResult'; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/types.ts b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/types.ts index 34c306ed0a116..92cc3e8c9017a 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/types.ts +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/types.ts @@ -5,8 +5,9 @@ * 2.0. */ +import type { CommandResponseActionApiState } from './hooks/use_console_action_submitter'; import type { ManagedConsoleExtensionComponentProps } from '../console'; -import type { ActionDetails, HostMetadata } from '../../../../common/endpoint/types'; +import type { HostMetadata } from '../../../../common/endpoint/types'; import type { CommandExecutionComponentProps } from '../console/types'; export interface EndpointCommandDefinitionMeta { @@ -17,16 +18,9 @@ export type EndpointResponderExtensionComponentProps = ManagedConsoleExtensionCo endpoint: HostMetadata; }>; -export interface ActionRequestState { - requestSent: boolean; - actionId?: string; -} - -export type ActionRequestComponentProps = CommandExecutionComponentProps< - { comment?: string }, - { - actionRequest?: ActionRequestState; - completedActionDetails?: ActionDetails; - }, - EndpointCommandDefinitionMeta ->; +export type ActionRequestComponentProps = + CommandExecutionComponentProps< + { comment?: string } & TArgs, + CommandResponseActionApiState, + EndpointCommandDefinitionMeta + >; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.test.ts b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.test.ts index ab84e9de959f0..48b6753645c92 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.test.ts +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.test.ts @@ -19,9 +19,9 @@ describe('Endpoint Responder - Utilities', () => { expect(parameters).toEqual({ entity_id: '123qwe' }); }); - it('should return undefined if no params are defined', () => { + it('should return entity id with emtpy string if no params are defined', () => { const parameters = parsedPidOrEntityIdParameter({}); - expect(parameters).toEqual(undefined); + expect(parameters).toEqual({ entity_id: '' }); }); }); }); diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.ts b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.ts index 9ebcd090bd2a0..0b8e59d0353f7 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.ts +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_responder/utils.ts @@ -4,17 +4,17 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { EndpointActionDataParameterTypes } from '../../../../common/endpoint/types'; +import type { ResponseActionParametersWithPidOrEntityId } from '../../../../common/endpoint/types'; export const parsedPidOrEntityIdParameter = (parameters: { pid?: string[]; entityId?: string[]; -}): EndpointActionDataParameterTypes => { +}): ResponseActionParametersWithPidOrEntityId => { if (parameters.pid) { return { pid: Number(parameters.pid[0]) }; - } else if (parameters.entityId) { - return { entity_id: parameters.entityId[0] }; } - return undefined; + return { + entity_id: parameters?.entityId?.[0] ?? '', + }; }; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/actions_log_empty_state.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/actions_log_empty_state.tsx index a5a6f15f2de9d..c5838570eeae0 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/actions_log_empty_state.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/actions_log_empty_state.tsx @@ -26,14 +26,14 @@ export const ActionsLogEmptyState = memo( iconType="editorUnorderedList" title={

    - {i18n.translate('xpack.securitySolution.actions_log.empty.title', { - defaultMessage: 'Actions history is empty', + {i18n.translate('xpack.securitySolution.responseActionsHistory.empty.title', { + defaultMessage: 'Response actions history is empty', })}

    } body={
    - {i18n.translate('xpack.securitySolution.actions_log.empty.content', { + {i18n.translate('xpack.securitySolution.responseActionsHistory.empty.content', { defaultMessage: 'No response actions performed', })}
    @@ -44,7 +44,7 @@ export const ActionsLogEmptyState = memo( href={docLinks?.links.securitySolution.responseActions} target="_blank" > - {i18n.translate('xpack.securitySolution.actions_log.empty.link', { + {i18n.translate('xpack.securitySolution.responseActionsHistory.empty.link', { defaultMessage: 'Read more about response actions', })}
    , diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/hooks.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/hooks.tsx index bb2c1b7761d5a..34cc5a3ca0f99 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/hooks.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/hooks.tsx @@ -159,7 +159,6 @@ export const getCommandKey = ( } }; -// TODO: add more filter names here export type FilterName = keyof typeof FILTER_NAMES; export const useActionsLogFilter = ({ filterName, diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.test.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.test.tsx index 549b03fedfbf1..556c765296337 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.test.tsx @@ -114,7 +114,7 @@ jest.mock('../../hooks/endpoint/use_get_endpoints_list'); const mockUseGetEndpointsList = useGetEndpointsList as jest.Mock; -describe('Response Actions Log', () => { +describe('Response actions history', () => { const testPrefix = 'response-actions-list'; let render: ( @@ -393,6 +393,26 @@ describe('Response Actions Log', () => { expect(noTrays).toEqual([]); }); + it('should contain relevant details in each expanded row', async () => { + render(); + const { getAllByTestId } = renderResult; + + const expandButtons = getAllByTestId(`${testPrefix}-expand-button`); + expandButtons.map((button) => userEvent.click(button)); + const trays = getAllByTestId(`${testPrefix}-details-tray`); + expect(trays).toBeTruthy(); + expect(Array.from(trays[0].querySelectorAll('dt')).map((title) => title.textContent)).toEqual( + [ + 'Command placed', + 'Execution started on', + 'Execution completed', + 'Input', + 'Parameters', + 'Output:', + ] + ); + }); + it('should refresh data when autoRefresh is toggled on', async () => { render(); const { getByTestId } = renderResult; diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.tsx index d7b923dec5058..ac9a0829bb7b8 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/response_actions_log.tsx @@ -5,112 +5,29 @@ * 2.0. */ -import { - EuiAvatar, - EuiBasicTable, - EuiButtonIcon, - EuiDescriptionList, - EuiEmptyPrompt, - EuiFacetButton, - EuiFlexGroup, - EuiFlexItem, - EuiHorizontalRule, - EuiScreenReaderOnly, - EuiI18nNumber, - EuiText, - EuiCodeBlock, - EuiToolTip, - RIGHT_ALIGNMENT, -} from '@elastic/eui'; -import { euiStyled, css } from '@kbn/kibana-react-plugin/common'; +import { EuiBasicTable, EuiEmptyPrompt, EuiFlexItem, EuiHorizontalRule } from '@elastic/eui'; -import type { HorizontalAlignment, CriteriaWithPagination } from '@elastic/eui'; +import type { CriteriaWithPagination } from '@elastic/eui'; import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; import type { ResponseActions, ResponseActionStatus, } from '../../../../common/endpoint/service/response_actions/constants'; -import { getEmptyValue } from '../../../common/components/empty_value'; -import { FormattedDate } from '../../../common/components/formatted_date'; + import type { ActionListApiResponse } from '../../../../common/endpoint/types'; import type { EndpointActionListRequestQuery } from '../../../../common/endpoint/schema/actions'; import { ManagementEmptyStateWrapper } from '../management_empty_state_wrapper'; import { useGetEndpointActionList } from '../../hooks'; -import { OUTPUT_MESSAGES, TABLE_COLUMN_NAMES, UX_MESSAGES } from './translations'; -import { MANAGEMENT_PAGE_SIZE_OPTIONS } from '../../common/constants'; +import { UX_MESSAGES } from './translations'; import { useTestIdGenerator } from '../../hooks/use_test_id_generator'; import { ActionsLogFilters } from './components/actions_log_filters'; -import { - getActionStatus, - getUiCommand, - getCommandKey, - useDateRangePicker, -} from './components/hooks'; -import { StatusBadge } from './components/status_badge'; +import { getCommandKey, useDateRangePicker } from './components/hooks'; import { useActionHistoryUrlParams } from './components/use_action_history_url_params'; import { useUrlPagination } from '../../hooks/use_url_pagination'; import { ManagementPageLoader } from '../management_page_loader'; import { ActionsLogEmptyState } from './components/actions_log_empty_state'; - -const emptyValue = getEmptyValue(); - -// Truncated usernames -const StyledFacetButton = euiStyled(EuiFacetButton)` - .euiText { - margin-top: 0.38rem; - overflow-y: visible !important; - } -`; - -const customDescriptionListCss = css` - &.euiDescriptionList { - > .euiDescriptionList__title { - color: ${(props) => props.theme.eui.euiColorDarkShade}; - font-size: ${(props) => props.theme.eui.euiFontSizeXS}; - margin-top: ${(props) => props.theme.eui.euiSizeS}; - } - - > .euiDescriptionList__description { - font-weight: ${(props) => props.theme.eui.euiFontWeightSemiBold}; - margin-top: ${(props) => props.theme.eui.euiSizeS}; - } - } -`; - -const StyledDescriptionList = euiStyled(EuiDescriptionList).attrs({ - compressed: true, - type: 'column', -})` - ${customDescriptionListCss} -`; - -// output section styles -const topSpacingCss = css` - ${(props) => `${props.theme.eui.euiCodeBlockPaddingModifiers.paddingMedium} 0`} -`; -const dashedBorderCss = css` - ${(props) => `1px dashed ${props.theme.eui.euiColorDisabled}`}; -`; -const StyledDescriptionListOutput = euiStyled(EuiDescriptionList).attrs({ compressed: true })` - ${customDescriptionListCss} - dd { - margin: ${topSpacingCss}; - padding: ${topSpacingCss}; - border-top: ${dashedBorderCss}; - border-bottom: ${dashedBorderCss}; - } -`; - -// code block styles -const StyledEuiCodeBlock = euiStyled(EuiCodeBlock).attrs({ - transparentBackground: true, - paddingSize: 'none', -})` - code { - color: ${(props) => props.theme.eui.euiColorDarkShade} !important; - } -`; +import { useResponseActionsLogTable } from './use_response_actions_log_table'; export const ResponseActionsLog = memo< Pick & { @@ -131,9 +48,6 @@ export const ResponseActionsLog = memo< } = useActionHistoryUrlParams(); const getTestId = useTestIdGenerator('response-actions-list'); - const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState<{ - [k: ActionListApiResponse['data'][number]['id']]: React.ReactNode; - }>({}); // Used to decide if display global loader or not (only the fist time tha page loads) const [isFirstAttempt, setIsFirstAttempt] = useState(true); @@ -183,6 +97,19 @@ export const ResponseActionsLog = memo< { retry: false } ); + // total actions + const totalItemCount = useMemo(() => actionList?.total ?? 0, [actionList]); + + // table columns and expanded row state + const { itemIdToExpandedRowMap, recordRangeLabel, responseActionListColumns, tablePagination } = + useResponseActionsLogTable({ + showHostNames, + pageIndex: isFlyout ? (queryParams.page || 1) - 1 : paginationFromUrlParams.page - 1, + pageSize: isFlyout ? queryParams.pageSize || 10 : paginationFromUrlParams.pageSize, + queryParams, + totalItemCount, + }); + // Hide page header when there is no actions index calling the setIsDataInResponse with false value. // Otherwise, it shows the page header calling the setIsDataInResponse with true value and it also keeps track // if the API request was done for the first time. @@ -248,310 +175,6 @@ export const ResponseActionsLog = memo< [setQueryParams] ); - // total actions - const totalItemCount = useMemo(() => actionList?.total ?? 0, [actionList]); - - // expanded tray contents - const toggleDetails = useCallback( - (item: ActionListApiResponse['data'][number]) => { - const itemIdToExpandedRowMapValues = { ...itemIdToExpandedRowMap }; - if (itemIdToExpandedRowMapValues[item.id]) { - delete itemIdToExpandedRowMapValues[item.id]; - } else { - const { - startedAt, - completedAt, - isCompleted, - wasSuccessful, - isExpired, - command: _command, - parameters, - } = item; - - const parametersList = parameters - ? Object.entries(parameters).map(([key, value]) => { - return `${key}:${value}`; - }) - : undefined; - - const command = getUiCommand(_command); - const dataList = [ - { - title: OUTPUT_MESSAGES.expandSection.placedAt, - description: `${startedAt}`, - }, - { - title: OUTPUT_MESSAGES.expandSection.startedAt, - description: `${startedAt}`, - }, - { - title: OUTPUT_MESSAGES.expandSection.completedAt, - description: `${completedAt ?? emptyValue}`, - }, - { - title: OUTPUT_MESSAGES.expandSection.input, - description: `${command}`, - }, - { - title: OUTPUT_MESSAGES.expandSection.parameters, - description: parametersList ? parametersList : emptyValue, - }, - ].map(({ title, description }) => { - return { - title: {title}, - description: {description}, - }; - }); - - const outputList = [ - { - title: ( - {`${OUTPUT_MESSAGES.expandSection.output}:`} - ), - description: ( - // codeblock for output - - {isExpired - ? OUTPUT_MESSAGES.hasExpired(command) - : isCompleted - ? wasSuccessful - ? OUTPUT_MESSAGES.wasSuccessful(command) - : OUTPUT_MESSAGES.hasFailed(command) - : OUTPUT_MESSAGES.isPending(command)} - - ), - }, - ]; - - itemIdToExpandedRowMapValues[item.id] = ( - <> - - - - - - - - - - ); - } - setItemIdToExpandedRowMap(itemIdToExpandedRowMapValues); - }, - [getTestId, itemIdToExpandedRowMap] - ); - // memoized callback for toggleDetails - const onClickCallback = useCallback( - (actionListDataItem: ActionListApiResponse['data'][number]) => () => - toggleDetails(actionListDataItem), - [toggleDetails] - ); - - // table column - const responseActionListColumns = useMemo(() => { - const columns = [ - { - field: 'startedAt', - name: TABLE_COLUMN_NAMES.time, - width: !showHostNames ? '21%' : '15%', - truncateText: true, - render: (startedAt: ActionListApiResponse['data'][number]['startedAt']) => { - return ( - - ); - }, - }, - { - field: 'command', - name: TABLE_COLUMN_NAMES.command, - width: !showHostNames ? '21%' : '10%', - truncateText: true, - render: (_command: ActionListApiResponse['data'][number]['command']) => { - const command = getUiCommand(_command); - return ( - - - {command} - - - ); - }, - }, - { - field: 'createdBy', - name: TABLE_COLUMN_NAMES.user, - width: !showHostNames ? '21%' : '14%', - truncateText: true, - render: (userId: ActionListApiResponse['data'][number]['createdBy']) => { - return ( - - } - > - - - {userId} - - - - ); - }, - }, - // conditional hostnames column - { - field: 'hosts', - name: TABLE_COLUMN_NAMES.hosts, - width: '20%', - truncateText: true, - render: (_hosts: ActionListApiResponse['data'][number]['hosts']) => { - const hosts = _hosts && Object.values(_hosts); - // join hostnames if the action is for multiple agents - // and skip empty strings for names if any - const _hostnames = hosts - .reduce((acc, host) => { - if (host.name.trim()) { - acc.push(host.name); - } - return acc; - }, []) - .join(', '); - - let hostnames = _hostnames; - if (!_hostnames) { - if (hosts.length > 1) { - // when action was for a single agent and no host name - hostnames = UX_MESSAGES.unenrolled.hosts; - } else if (hosts.length === 1) { - // when action was for a multiple agents - // and none of them have a host name - hostnames = UX_MESSAGES.unenrolled.host; - } - } - return ( - - - {hostnames} - - - ); - }, - }, - { - field: 'comment', - name: TABLE_COLUMN_NAMES.comments, - width: !showHostNames ? '21%' : '30%', - truncateText: true, - render: (comment: ActionListApiResponse['data'][number]['comment']) => { - return ( - - - {comment ?? emptyValue} - - - ); - }, - }, - { - field: 'status', - name: TABLE_COLUMN_NAMES.status, - width: !showHostNames ? '15%' : '10%', - render: (_status: ActionListApiResponse['data'][number]['status']) => { - const status = getActionStatus(_status); - - return ( - - - - ); - }, - }, - { - field: '', - align: RIGHT_ALIGNMENT as HorizontalAlignment, - width: '40px', - isExpander: true, - name: ( - - {UX_MESSAGES.screenReaderExpand} - - ), - render: (actionListDataItem: ActionListApiResponse['data'][number]) => { - return ( - - ); - }, - }, - ]; - // filter out the `hosts` column - // if showHostNames is FALSE - if (!showHostNames) { - return columns.filter((column) => column.field !== 'hosts'); - } - return columns; - }, [showHostNames, getTestId, itemIdToExpandedRowMap, onClickCallback]); - - // table pagination - const tablePagination = useMemo(() => { - const pageIndex = isFlyout ? (queryParams.page || 1) - 1 : paginationFromUrlParams.page - 1; - const pageSize = isFlyout ? queryParams.pageSize || 10 : paginationFromUrlParams.pageSize; - return { - // this controls the table UI page - // to match 0-based table paging - pageIndex, - pageSize, - totalItemCount, - pageSizeOptions: MANAGEMENT_PAGE_SIZE_OPTIONS as number[], - }; - }, [ - isFlyout, - paginationFromUrlParams.page, - paginationFromUrlParams.pageSize, - queryParams.page, - queryParams.pageSize, - totalItemCount, - ]); - // handle onChange const handleTableOnChange = useCallback( ({ page: _page }: CriteriaWithPagination) => { @@ -563,16 +186,12 @@ export const ResponseActionsLog = memo< page: index + 1, pageSize: size, }; - if (isFlyout) { - setQueryParams((prevState) => ({ - ...prevState, - ...pagingArgs, - })); - } else { - setQueryParams((prevState) => ({ - ...prevState, - ...pagingArgs, - })); + + setQueryParams((prevState) => ({ + ...prevState, + ...pagingArgs, + })); + if (!isFlyout) { setPaginationOnUrlParams({ ...pagingArgs, }); @@ -582,42 +201,6 @@ export const ResponseActionsLog = memo< [isFlyout, reFetchEndpointActionList, setQueryParams, setPaginationOnUrlParams] ); - // compute record ranges - const pagedResultsCount = useMemo(() => { - const page = queryParams.page ?? 1; - const perPage = queryParams?.pageSize ?? 10; - - const totalPages = Math.ceil(totalItemCount / perPage); - const fromCount = perPage * page - perPage + 1; - const toCount = - page === totalPages || totalPages === 1 ? totalItemCount : fromCount + perPage - 1; - return { fromCount, toCount }; - }, [queryParams.page, queryParams.pageSize, totalItemCount]); - - // create range label to display - const recordRangeLabel = useMemo( - () => ( - - - - {'-'} - - - ), - total: , - recordsLabel: {UX_MESSAGES.recordsLabel(totalItemCount)}, - }} - /> - - ), - [getTestId, pagedResultsCount.fromCount, pagedResultsCount.toCount, totalItemCount] - ); - if (error?.body?.statusCode === 404 && error?.body?.message === 'index_not_found_exception') { return ; } else if (isFetching && isFirstAttempt) { @@ -649,7 +232,7 @@ export const ResponseActionsLog = memo<

    } @@ -657,7 +240,7 @@ export const ResponseActionsLog = memo<

    } @@ -675,7 +258,7 @@ export const ResponseActionsLog = memo< columns={responseActionListColumns} itemId="id" itemIdToExpandedRowMap={itemIdToExpandedRowMap} - isExpandable={true} + isExpandable pagination={tablePagination} onChange={handleTableOnChange} loading={isFetching} diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/translations.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/translations.tsx index 542f0d72bf0be..a90f12bc2d246 100644 --- a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/translations.tsx +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/translations.tsx @@ -92,7 +92,7 @@ export const TABLE_COLUMN_NAMES = Object.freeze({ export const UX_MESSAGES = Object.freeze({ flyoutTitle: (hostname: string) => i18n.translate('xpack.securitySolution.responseActionsList.flyout.title', { - defaultMessage: `Actions log : {hostname}`, + defaultMessage: `Response actions history : {hostname}`, values: { hostname }, }), pageSubTitle: i18n.translate('xpack.securitySolution.responseActionsList.list.pageSubTitle', { diff --git a/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/use_response_actions_log_table.tsx b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/use_response_actions_log_table.tsx new file mode 100644 index 0000000000000..e4dd30b468127 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/components/endpoint_response_actions_list/use_response_actions_log_table.tsx @@ -0,0 +1,441 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import React, { useCallback, useMemo, useState } from 'react'; +import type { HorizontalAlignment } from '@elastic/eui'; + +import { + EuiI18nNumber, + EuiAvatar, + EuiButtonIcon, + EuiCodeBlock, + EuiDescriptionList, + EuiFacetButton, + EuiFlexGroup, + EuiFlexItem, + RIGHT_ALIGNMENT, + EuiScreenReaderOnly, + EuiText, + EuiToolTip, +} from '@elastic/eui'; +import { css, euiStyled } from '@kbn/kibana-react-plugin/common'; +import { FormattedMessage } from '@kbn/i18n-react'; + +import type { ActionListApiResponse } from '../../../../common/endpoint/types'; +import type { EndpointActionListRequestQuery } from '../../../../common/endpoint/schema/actions'; +import { FormattedDate } from '../../../common/components/formatted_date'; +import { OUTPUT_MESSAGES, TABLE_COLUMN_NAMES, UX_MESSAGES } from './translations'; +import { getActionStatus, getUiCommand } from './components/hooks'; +import { getEmptyValue } from '../../../common/components/empty_value'; +import { StatusBadge } from './components/status_badge'; +import { useTestIdGenerator } from '../../hooks/use_test_id_generator'; +import { MANAGEMENT_PAGE_SIZE_OPTIONS } from '../../common/constants'; + +const emptyValue = getEmptyValue(); + +// Truncated usernames +const StyledFacetButton = euiStyled(EuiFacetButton)` + .euiText { + margin-top: 0.38rem; + overflow-y: visible !important; + } +`; + +const customDescriptionListCss = css` + &.euiDescriptionList { + > .euiDescriptionList__title { + color: ${(props) => props.theme.eui.euiColorDarkShade}; + font-size: ${(props) => props.theme.eui.euiFontSizeXS}; + margin-top: ${(props) => props.theme.eui.euiSizeS}; + } + + > .euiDescriptionList__description { + font-weight: ${(props) => props.theme.eui.euiFontWeightSemiBold}; + margin-top: ${(props) => props.theme.eui.euiSizeS}; + } + } +`; + +const StyledDescriptionList = euiStyled(EuiDescriptionList).attrs({ + compressed: true, + type: 'column', +})` + ${customDescriptionListCss} +`; + +// output section styles +const topSpacingCss = css` + ${(props) => `${props.theme.eui.euiCodeBlockPaddingModifiers.paddingMedium} 0`} +`; +const dashedBorderCss = css` + ${(props) => `1px dashed ${props.theme.eui.euiColorDisabled}`}; +`; +const StyledDescriptionListOutput = euiStyled(EuiDescriptionList).attrs({ compressed: true })` + ${customDescriptionListCss} + dd { + margin: ${topSpacingCss}; + padding: ${topSpacingCss}; + border-top: ${dashedBorderCss}; + border-bottom: ${dashedBorderCss}; + } +`; + +// code block styles +const StyledEuiCodeBlock = euiStyled(EuiCodeBlock).attrs({ + transparentBackground: true, + paddingSize: 'none', +})` + code { + color: ${(props) => props.theme.eui.euiColorDarkShade} !important; + } +`; + +export const useResponseActionsLogTable = ({ + pageIndex, + pageSize, + queryParams, + showHostNames, + totalItemCount, +}: { + pageIndex: number; + pageSize: number; + queryParams: EndpointActionListRequestQuery; + showHostNames: boolean; + totalItemCount: number; +}) => { + const getTestId = useTestIdGenerator('response-actions-list'); + + const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState<{ + [k: ActionListApiResponse['data'][number]['id']]: React.ReactNode; + }>({}); + + // expanded tray contents + const toggleDetails = useCallback( + (item: ActionListApiResponse['data'][number]) => { + const itemIdToExpandedRowMapValues = { ...itemIdToExpandedRowMap }; + if (itemIdToExpandedRowMapValues[item.id]) { + delete itemIdToExpandedRowMapValues[item.id]; + } else { + const { + startedAt, + completedAt, + isCompleted, + wasSuccessful, + isExpired, + command: _command, + parameters, + } = item; + + const parametersList = parameters + ? Object.entries(parameters).map(([key, value]) => { + return `${key}:${value}`; + }) + : undefined; + + const command = getUiCommand(_command); + const dataList = [ + { + title: OUTPUT_MESSAGES.expandSection.placedAt, + description: `${startedAt}`, + }, + { + title: OUTPUT_MESSAGES.expandSection.startedAt, + description: `${startedAt}`, + }, + { + title: OUTPUT_MESSAGES.expandSection.completedAt, + description: `${completedAt ?? emptyValue}`, + }, + { + title: OUTPUT_MESSAGES.expandSection.input, + description: `${command}`, + }, + { + title: OUTPUT_MESSAGES.expandSection.parameters, + description: parametersList ? parametersList : emptyValue, + }, + ].map(({ title, description }) => { + return { + title: {title}, + description: {description}, + }; + }); + + const outputList = [ + { + title: ( + {`${OUTPUT_MESSAGES.expandSection.output}:`} + ), + description: ( + // codeblock for output + + {isExpired + ? OUTPUT_MESSAGES.hasExpired(command) + : isCompleted + ? wasSuccessful + ? OUTPUT_MESSAGES.wasSuccessful(command) + : OUTPUT_MESSAGES.hasFailed(command) + : OUTPUT_MESSAGES.isPending(command)} + + ), + }, + ]; + + itemIdToExpandedRowMapValues[item.id] = ( + <> + + + + + + + + + + ); + } + setItemIdToExpandedRowMap(itemIdToExpandedRowMapValues); + }, + [getTestId, itemIdToExpandedRowMap] + ); + // memoized callback for toggleDetails + const onClickCallback = useCallback( + (actionListDataItem: ActionListApiResponse['data'][number]) => () => + toggleDetails(actionListDataItem), + [toggleDetails] + ); + + const responseActionListColumns = useMemo(() => { + const columns = [ + { + field: 'startedAt', + name: TABLE_COLUMN_NAMES.time, + width: !showHostNames ? '21%' : '15%', + truncateText: true, + render: (startedAt: ActionListApiResponse['data'][number]['startedAt']) => { + return ( + + ); + }, + }, + { + field: 'command', + name: TABLE_COLUMN_NAMES.command, + width: !showHostNames ? '21%' : '10%', + truncateText: true, + render: (_command: ActionListApiResponse['data'][number]['command']) => { + const command = getUiCommand(_command); + return ( + + + {command} + + + ); + }, + }, + { + field: 'createdBy', + name: TABLE_COLUMN_NAMES.user, + width: !showHostNames ? '21%' : '14%', + truncateText: true, + render: (userId: ActionListApiResponse['data'][number]['createdBy']) => { + return ( + + } + > + + + {userId} + + + + ); + }, + }, + // conditional hostnames column + { + field: 'hosts', + name: TABLE_COLUMN_NAMES.hosts, + width: '20%', + truncateText: true, + render: (_hosts: ActionListApiResponse['data'][number]['hosts']) => { + const hosts = _hosts && Object.values(_hosts); + // join hostnames if the action is for multiple agents + // and skip empty strings for names if any + const _hostnames = hosts + .reduce((acc, host) => { + if (host.name.trim()) { + acc.push(host.name); + } + return acc; + }, []) + .join(', '); + + let hostnames = _hostnames; + if (!_hostnames) { + if (hosts.length > 1) { + // when action was for a single agent and no host name + hostnames = UX_MESSAGES.unenrolled.hosts; + } else if (hosts.length === 1) { + // when action was for a multiple agents + // and none of them have a host name + hostnames = UX_MESSAGES.unenrolled.host; + } + } + return ( + + + {hostnames} + + + ); + }, + }, + { + field: 'comment', + name: TABLE_COLUMN_NAMES.comments, + width: !showHostNames ? '21%' : '30%', + truncateText: true, + render: (comment: ActionListApiResponse['data'][number]['comment']) => { + return ( + + + {comment ?? emptyValue} + + + ); + }, + }, + { + field: 'status', + name: TABLE_COLUMN_NAMES.status, + width: !showHostNames ? '15%' : '10%', + render: (_status: ActionListApiResponse['data'][number]['status']) => { + const status = getActionStatus(_status); + + return ( + + + + ); + }, + }, + { + field: '', + align: RIGHT_ALIGNMENT as HorizontalAlignment, + width: '40px', + isExpander: true, + name: ( + + {UX_MESSAGES.screenReaderExpand} + + ), + render: (actionListDataItem: ActionListApiResponse['data'][number]) => { + return ( + + ); + }, + }, + ]; + // filter out the `hosts` column + // if showHostNames is FALSE + if (!showHostNames) { + return columns.filter((column) => column.field !== 'hosts'); + } + return columns; + }, [showHostNames, getTestId, itemIdToExpandedRowMap, onClickCallback]); + + // table pagination + const tablePagination = useMemo(() => { + return { + pageIndex, + pageSize, + totalItemCount, + pageSizeOptions: MANAGEMENT_PAGE_SIZE_OPTIONS as number[], + }; + }, [pageIndex, pageSize, totalItemCount]); + + // compute record ranges + const pagedResultsCount = useMemo(() => { + const page = queryParams.page ?? 1; + const perPage = queryParams?.pageSize ?? 10; + + const totalPages = Math.ceil(totalItemCount / perPage); + const fromCount = perPage * page - perPage + 1; + const toCount = + page === totalPages || totalPages === 1 ? totalItemCount : fromCount + perPage - 1; + return { fromCount, toCount }; + }, [queryParams.page, queryParams.pageSize, totalItemCount]); + + // create range label to display + const recordRangeLabel = useMemo( + () => ( + + + + {'-'} + + + ), + total: , + recordsLabel: {UX_MESSAGES.recordsLabel(totalItemCount)}, + }} + /> + + ), + [getTestId, pagedResultsCount.fromCount, pagedResultsCount.toCount, totalItemCount] + ); + + return { itemIdToExpandedRowMap, responseActionListColumns, recordRangeLabel, tablePagination }; +}; diff --git a/x-pack/plugins/security_solution/public/management/components/page_overlay/page_overlay.tsx b/x-pack/plugins/security_solution/public/management/components/page_overlay/page_overlay.tsx index b5c7629b76aa6..2d3a9c9cb7f07 100644 --- a/x-pack/plugins/security_solution/public/management/components/page_overlay/page_overlay.tsx +++ b/x-pack/plugins/security_solution/public/management/components/page_overlay/page_overlay.tsx @@ -13,6 +13,7 @@ import classnames from 'classnames'; import { useLocation } from 'react-router-dom'; import type { EuiPortalProps } from '@elastic/eui/src/components/portal/portal'; import type { EuiTheme } from '@kbn/kibana-react-plugin/common'; +import { useIsMounted } from '@kbn/securitysolution-hook-utils'; import { useHasFullScreenContent } from '../../../common/containers/use_full_screen'; import { FULL_SCREEN_CONTENT_OVERRIDES_CSS_STYLESHEET, @@ -22,7 +23,6 @@ import { SELECTOR_TIMELINE_IS_VISIBLE_CSS_CLASS_NAME, TIMELINE_EUI_THEME_ZINDEX_LEVEL, } from '../../../timelines/components/timeline/styles'; -import { useIsMounted } from '../../hooks/use_is_mounted'; const OverlayRootContainer = styled.div` border: none; @@ -246,7 +246,7 @@ export const PageOverlay = memo( // Capture the URL `pathname` that the overlay was opened for useEffect(() => { - if (isMounted) { + if (isMounted()) { setOpenedOnPathName((prevState) => { if (isHidden) { return null; @@ -270,7 +270,7 @@ export const PageOverlay = memo( // If `hideOnUrlPathNameChange` is true, then determine if the pathname changed and if so, call `onHide()` useEffect(() => { if ( - isMounted && + isMounted() && onHide && hideOnUrlPathnameChange && !isHidden && @@ -283,7 +283,7 @@ export const PageOverlay = memo( // Handle adding class names to the `document.body` DOM element useEffect(() => { - if (isMounted) { + if (isMounted()) { if (isHidden) { unSetDocumentBodyOverlayIsVisible(); unSetDocumentBodyLock(); diff --git a/x-pack/plugins/security_solution/public/management/hooks/endpoint/use_get_endpoints_list.test.ts b/x-pack/plugins/security_solution/public/management/hooks/endpoint/use_get_endpoints_list.test.ts index 0804bef55b3e7..cdb1041cda7ed 100644 --- a/x-pack/plugins/security_solution/public/management/hooks/endpoint/use_get_endpoints_list.test.ts +++ b/x-pack/plugins/security_solution/public/management/hooks/endpoint/use_get_endpoints_list.test.ts @@ -11,6 +11,8 @@ import { useGetEndpointsList } from './use_get_endpoints_list'; import { HOST_METADATA_LIST_ROUTE } from '../../../../common/endpoint/constants'; import { useQuery as _useQuery } from '@tanstack/react-query'; import { endpointMetadataHttpMocks } from '../../pages/endpoint_hosts/mocks'; +import { EndpointStatus, HostStatus } from '../../../../common/endpoint/types'; +import { EndpointDocGenerator } from '../../../../common/endpoint/generate_data'; const useQueryMock = _useQuery as jest.Mock; @@ -107,4 +109,127 @@ describe('useGetEndpointsList hook', () => { }) ); }); + + it('should also list inactive agents', async () => { + const getApiResponse = apiMocks.responseProvider.metadataList.getMockImplementation(); + + // set a few of the agents as inactive/unenrolled + apiMocks.responseProvider.metadataList.mockImplementation(() => { + if (getApiResponse) { + return { + ...getApiResponse(), + data: getApiResponse().data.map((item, i) => { + const isInactiveIndex = [0, 1, 3].includes(i); + return { + ...item, + host_status: isInactiveIndex ? HostStatus.INACTIVE : item.host_status, + metadata: { + ...item.metadata, + host: { + ...item.metadata.host, + hostname: isInactiveIndex + ? `${item.metadata.host.hostname}-inactive` + : item.metadata.host.hostname, + }, + Endpoint: { + ...item.metadata.Endpoint, + status: isInactiveIndex + ? EndpointStatus.unenrolled + : item.metadata.Endpoint.status, + }, + }, + }; + }), + }; + } + throw new Error('some error'); + }); + + // verify useGetEndpointsList hook returns the same inactive agents + const res = await renderReactQueryHook(() => useGetEndpointsList({ searchString: 'inactive' })); + expect( + res.data?.map((host) => host.name.split('-')[2]).filter((name) => name === 'inactive').length + ).toEqual(3); + }); + + it('should only list 50 agents when more than 50 in the metadata list API', async () => { + const getApiResponse = apiMocks.responseProvider.metadataList.getMockImplementation(); + + apiMocks.responseProvider.metadataList.mockImplementation(() => { + if (getApiResponse) { + const generator = new EndpointDocGenerator('seed'); + const total = 60; + const data = Array.from({ length: total }, () => { + const endpoint = { + metadata: generator.generateHostMetadata(), + host_status: HostStatus.UNHEALTHY, + }; + + generator.updateCommonInfo(); + + return endpoint; + }); + + return { + ...getApiResponse(), + data, + page: 0, + // this page size is not used by the hook (it uses the default of 50) + // this is only for the test + pageSize: 80, + total, + }; + } + throw new Error('some error'); + }); + + // verify useGetEndpointsList hook returns all 50 agents in the list + const res = await renderReactQueryHook(() => useGetEndpointsList({ searchString: '' })); + expect(res.data?.length).toEqual(50); + }); + + it('should only list 10 more agents when 50 or more agents are already selected', async () => { + const getApiResponse = apiMocks.responseProvider.metadataList.getMockImplementation(); + + apiMocks.responseProvider.metadataList.mockImplementation(() => { + if (getApiResponse) { + const generator = new EndpointDocGenerator('seed'); + const total = 61; + const data = Array.from({ length: total }, () => { + const endpoint = { + metadata: generator.generateHostMetadata(), + host_status: HostStatus.UNHEALTHY, + }; + + generator.updateCommonInfo(); + + return endpoint; + }); + + return { + ...getApiResponse(), + data, + page: 0, + // since we're mocking that all 50 agents are selected + // page size is set to max allowed + pageSize: 10000, + total, + }; + } + throw new Error('some error'); + }); + + // get the first 50 agents to select + const agentIdsToSelect = apiMocks.responseProvider + .metadataList() + .data.map((d) => d.metadata.agent.id) + .slice(0, 50); + + // call useGetEndpointsList with all 50 agents selected + const res = await renderReactQueryHook(() => + useGetEndpointsList({ searchString: '', selectedAgentIds: agentIdsToSelect }) + ); + // verify useGetEndpointsList hook returns 60 agents + expect(res.data?.length).toEqual(60); + }); }); diff --git a/x-pack/plugins/security_solution/public/management/hooks/use_is_mounted.ts b/x-pack/plugins/security_solution/public/management/hooks/use_is_mounted.ts deleted file mode 100644 index 0c5a79b2ca2fc..0000000000000 --- a/x-pack/plugins/security_solution/public/management/hooks/use_is_mounted.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { useEffect, useState } from 'react'; - -/** - * Track when a component is mounted/unmounted. Good for use in async processing that may update - * a component's internal state. - */ -export const useIsMounted = (): boolean => { - const [isMounted, setIsMounted] = useState(false); - - useEffect(() => { - setIsMounted(true); - - return () => { - setIsMounted(false); - }; - }, []); - - return isMounted; -}; diff --git a/x-pack/plugins/security_solution/public/management/links.test.ts b/x-pack/plugins/security_solution/public/management/links.test.ts index 7d386b6d6c5e0..09c47bc70095c 100644 --- a/x-pack/plugins/security_solution/public/management/links.test.ts +++ b/x-pack/plugins/security_solution/public/management/links.test.ts @@ -7,10 +7,13 @@ import type { HttpSetup } from '@kbn/core/public'; import { coreMock } from '@kbn/core/public/mocks'; + import { SecurityPageName } from '../app/types'; import { licenseService } from '../common/hooks/use_license'; import type { StartPlugins } from '../types'; import { links, getManagementFilteredLinks } from './links'; +import { allowedExperimentalValues } from '../../common/experimental_features'; +import { ExperimentalFeaturesService } from '../common/experimental_features_service'; jest.mock('../common/hooks/use_license', () => { const licenseServiceInstance = { @@ -30,6 +33,12 @@ describe('links', () => { let getPlugins: (roles: string[]) => StartPlugins; let fakeHttpServices: jest.Mocked; + beforeAll(() => { + ExperimentalFeaturesService.init({ + experimentalFeatures: { ...allowedExperimentalValues }, + }); + }); + beforeEach(() => { coreMockStarted = coreMock.createStart(); fakeHttpServices = coreMockStarted.http as jest.Mocked; @@ -41,6 +50,13 @@ describe('links', () => { getCurrentUser: jest.fn().mockReturnValue({ roles }), }, }, + fleet: { + authz: { + fleet: { + all: true, + }, + }, + }, } as unknown as StartPlugins); }); diff --git a/x-pack/plugins/security_solution/public/management/links.ts b/x-pack/plugins/security_solution/public/management/links.ts index 659fb7a8216a5..03cfee736def3 100644 --- a/x-pack/plugins/security_solution/public/management/links.ts +++ b/x-pack/plugins/security_solution/public/management/links.ts @@ -7,7 +7,11 @@ import type { CoreStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; -import { calculateEndpointAuthz } from '../../common/endpoint/service/authz'; + +import { + calculateEndpointAuthz, + getEndpointAuthzInitialState, +} from '../../common/endpoint/service/authz'; import { BLOCKLIST_PATH, ENDPOINTS_PATH, @@ -16,7 +20,7 @@ import { HOST_ISOLATION_EXCEPTIONS_PATH, MANAGE_PATH, POLICIES_PATH, - ACTION_HISTORY_PATH, + RESPONSE_ACTIONS_HISTORY_PATH, RULES_CREATE_PATH, RULES_PATH, SecurityPageName, @@ -32,7 +36,7 @@ import { HOST_ISOLATION_EXCEPTIONS, MANAGE, POLICIES, - ACTION_HISTORY, + RESPONSE_ACTIONS_HISTORY, RULES, TRUSTED_APPLICATIONS, } from '../app/translations'; @@ -53,6 +57,7 @@ import { IconHostIsolation } from './icons/host_isolation'; import { IconSiemRules } from './icons/siem_rules'; import { IconTrustedApplications } from './icons/trusted_applications'; import { HostIsolationExceptionsApiClient } from './pages/host_isolation_exceptions/host_isolation_exceptions_api_client'; +import { ExperimentalFeaturesService } from '../common/experimental_features_service'; const categories = [ { @@ -72,7 +77,7 @@ const categories = [ SecurityPageName.eventFilters, SecurityPageName.hostIsolationExceptions, SecurityPageName.blocklist, - SecurityPageName.actionHistory, + SecurityPageName.responseActionsHistory, ], }, ...cloudSecurityPostureCategories, @@ -207,13 +212,13 @@ export const links: LinkItem = { hideTimeline: true, }, { - id: SecurityPageName.actionHistory, - title: ACTION_HISTORY, + id: SecurityPageName.responseActionsHistory, + title: RESPONSE_ACTIONS_HISTORY, description: i18n.translate('xpack.securitySolution.appLinks.actionHistoryDescription', { defaultMessage: 'View the history of response actions performed on hosts.', }), landingIcon: IconActionHistory, - path: ACTION_HISTORY_PATH, + path: RESPONSE_ACTIONS_HISTORY_PATH, skipUrlState: true, hideTimeline: true, }, @@ -230,13 +235,19 @@ export const getManagementFilteredLinks = async ( core: CoreStart, plugins: StartPlugins ): Promise => { + const fleetAuthz = plugins.fleet?.authz; + const isEndpointRbacEnabled = ExperimentalFeaturesService.get().endpointRbacEnabled; + try { const currentUserResponse = await plugins.security.authc.getCurrentUser(); - const privileges = calculateEndpointAuthz( - licenseService, - plugins.fleet?.authz, - currentUserResponse.roles - ); + const privileges = fleetAuthz + ? calculateEndpointAuthz( + licenseService, + fleetAuthz, + currentUserResponse.roles, + isEndpointRbacEnabled + ) + : getEndpointAuthzInitialState(); if (!privileges.canAccessEndpointManagement) { return getFilteredLinks([SecurityPageName.hostIsolationExceptions]); } diff --git a/x-pack/plugins/security_solution/public/management/components/mocks.tsx b/x-pack/plugins/security_solution/public/management/mocks/utils.ts similarity index 93% rename from x-pack/plugins/security_solution/public/management/components/mocks.tsx rename to x-pack/plugins/security_solution/public/management/mocks/utils.ts index 45c12df818fd8..946d2d50b05d2 100644 --- a/x-pack/plugins/security_solution/public/management/components/mocks.tsx +++ b/x-pack/plugins/security_solution/public/management/mocks/utils.ts @@ -4,7 +4,8 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -interface DeferredInterface { + +export interface DeferredInterface { promise: Promise; resolve: (data: T) => void; reject: (e: Error) => void; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/components/actions_menu.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/components/actions_menu.test.tsx index 911d3b12931a6..35fe96d94d91f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/components/actions_menu.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/components/actions_menu.test.tsx @@ -14,6 +14,9 @@ import { act } from '@testing-library/react'; import { endpointPageHttpMock } from '../../../mocks'; import { fireEvent } from '@testing-library/dom'; import { licenseService } from '../../../../../../common/hooks/use_license'; +import { useUserPrivileges } from '../../../../../../common/components/user_privileges'; +import { initialUserPrivilegesState } from '../../../../../../common/components/user_privileges/user_privileges_context'; +import { getUserPrivilegesMockDefaultValue } from '../../../../../../common/components/user_privileges/__mocks__'; jest.mock('../../../../../../common/lib/kibana/kibana_react', () => { const originalModule = jest.requireActual('../../../../../../common/lib/kibana/kibana_react'); @@ -31,6 +34,7 @@ jest.mock('../../../../../../common/lib/kibana/kibana_react', () => { }; }); jest.mock('../../../../../../common/hooks/use_license'); +jest.mock('../../../../../../common/components/user_privileges'); describe('When using the Endpoint Details Actions Menu', () => { let render: () => Promise>; @@ -59,6 +63,8 @@ describe('When using the Endpoint Details Actions Menu', () => { waitForAction = mockedContext.middlewareSpy.waitForAction; httpMocks = endpointPageHttpMock(mockedContext.coreStart.http); + (useUserPrivileges as jest.Mock).mockReturnValue(getUserPrivilegesMockDefaultValue()); + act(() => { mockedContext.history.push( '/administration/endpoints?selected_endpoint=5fe11314-678c-413e-87a2-b4a3461878ee' @@ -80,7 +86,11 @@ describe('When using the Endpoint Details Actions Menu', () => { }; }); - it('should not show the actions log link', async () => { + afterEach(() => { + (useUserPrivileges as jest.Mock).mockClear(); + }); + + it('should not show the response actions history link', async () => { await render(); expect(renderResult.queryByTestId('actionsLink')).toBeNull(); }); @@ -121,18 +131,38 @@ describe('When using the Endpoint Details Actions Menu', () => { describe('and endpoint host is isolated', () => { beforeEach(() => setEndpointMetadataResponse(true)); - it('should display Unisolate action', async () => { - await render(); - expect(renderResult.getByTestId('unIsolateLink')).not.toBeNull(); + describe('and user has unisolate privilege', () => { + it('should display Unisolate action', async () => { + await render(); + expect(renderResult.getByTestId('unIsolateLink')).not.toBeNull(); + }); + + it('should navigate via router when unisolate is clicked', async () => { + await render(); + act(() => { + fireEvent.click(renderResult.getByTestId('unIsolateLink')); + }); + + expect(coreStart.application.navigateToApp).toHaveBeenCalled(); + }); }); - it('should navigate via router when unisolate is clicked', async () => { - await render(); - act(() => { - fireEvent.click(renderResult.getByTestId('unIsolateLink')); + describe('and user does not have unisolate privilege', () => { + beforeEach(() => { + (useUserPrivileges as jest.Mock).mockReturnValue({ + ...initialUserPrivilegesState(), + endpointPrivileges: { + ...initialUserPrivilegesState().endpointPrivileges, + canIsolateHost: false, + canUnIsolateHost: false, + }, + }); }); - expect(coreStart.application.navigateToApp).toHaveBeenCalled(); + it('should not display unisolate action', async () => { + await render(); + expect(renderResult.queryByTestId('unIsolateLink')).toBeNull(); + }); }); }); @@ -143,12 +173,6 @@ describe('When using the Endpoint Details Actions Menu', () => { afterEach(() => licenseServiceMock.isPlatinumPlus.mockReturnValue(true)); - it('should not show the `isolate` action', async () => { - setEndpointMetadataResponse(); - await render(); - expect(renderResult.queryByTestId('isolateLink')).toBeNull(); - }); - it('should still show `unisolate` action for endpoints that are currently isolated', async () => { setEndpointMetadataResponse(true); await render(); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks/use_endpoint_action_items.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks/use_endpoint_action_items.tsx index b3e1ce76480f3..9a9c884a3979a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks/use_endpoint_action_items.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks/use_endpoint_action_items.tsx @@ -19,7 +19,6 @@ import { agentPolicies, uiQueryParams } from '../../store/selectors'; import { useAppUrl } from '../../../../../common/lib/kibana/hooks'; import type { ContextMenuItemNavByRouterProps } from '../../../../components/context_menu_with_router_support/context_menu_item_nav_by_router'; import { isEndpointHostIsolated } from '../../../../../common/utils/validators'; -import { useLicense } from '../../../../../common/hooks/use_license'; import { isIsolationSupported } from '../../../../../../common/endpoint/service/host_isolation/utils'; import { useDoesEndpointSupportResponder } from '../../../../../common/hooks/endpoint/use_does_endpoint_support_responder'; import { UPGRADE_ENDPOINT_FOR_RESPONDER } from '../../../../../common/translations'; @@ -36,7 +35,6 @@ export const useEndpointActionItems = ( endpointMetadata: MaybeImmutable | undefined, options?: Options ): ContextMenuItemNavByRouterProps[] => { - const isPlatinumPlus = useLicense().isPlatinumPlus(); const { getAppUrl } = useAppUrl(); const fleetAgentPolicies = useEndpointSelector(agentPolicies); const allCurrentUrlParams = useEndpointSelector(uiQueryParams); @@ -44,7 +42,8 @@ export const useEndpointActionItems = ( const isResponseActionsConsoleEnabled = useIsExperimentalFeatureEnabled( 'responseActionsConsoleEnabled' ); - const canAccessResponseConsole = useUserPrivileges().endpointPrivileges.canAccessResponseConsole; + const { canAccessResponseConsole, canIsolateHost, canUnIsolateHost } = + useUserPrivileges().endpointPrivileges; const isResponderCapabilitiesEnabled = useDoesEndpointSupportResponder(endpointMetadata); return useMemo(() => { @@ -82,8 +81,8 @@ export const useEndpointActionItems = ( const isolationActions = []; - if (isIsolated) { - // Un-isolate is always available to users regardless of license level + if (isIsolated && canUnIsolateHost) { + // Un-isolate is available to users regardless of license level if they have unisolate permissions isolationActions.push({ 'data-test-subj': 'unIsolateLink', icon: 'lockOpen', @@ -100,7 +99,7 @@ export const useEndpointActionItems = ( /> ), }); - } else if (isPlatinumPlus && isolationSupported) { + } else if (isolationSupported && canIsolateHost) { // For Platinum++ licenses, users also have ability to isolate isolationActions.push({ 'data-test-subj': 'isolateLink', @@ -156,8 +155,8 @@ export const useEndpointActionItems = ( href: getAppUrl({ path: endpointActionsPath }), children: ( ), }, @@ -260,10 +259,11 @@ export const useEndpointActionItems = ( endpointMetadata, fleetAgentPolicies, getAppUrl, - isPlatinumPlus, isResponseActionsConsoleEnabled, showEndpointResponseActionsConsole, options?.isEndpointList, isResponderCapabilitiesEnabled, + canIsolateHost, + canUnIsolateHost, ]); }; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx index bbee0e695a8dd..7d8d625d97e39 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx @@ -1007,6 +1007,7 @@ describe('when on the endpoint list page', () => { let agentId: string; let agentPolicyId: string; let renderResult: ReturnType; + let endpointActionsButton: HTMLElement; // 2nd endpoint only has isolation capabilities const mockEndpointListApi = () => { @@ -1081,13 +1082,7 @@ describe('when on the endpoint list page', () => { beforeEach(async () => { mockEndpointListApi(); - (useUserPrivileges as jest.Mock).mockReturnValue({ - ...mockInitialUserPrivilegesState(), - endpointPrivileges: { - ...mockInitialUserPrivilegesState().endpointPrivileges, - canAccessResponseConsole: true, - }, - }); + (useUserPrivileges as jest.Mock).mockReturnValue(getUserPrivilegesMockDefaultValue()); reactTestingLibrary.act(() => { history.push(`${MANAGEMENT_PATH}/endpoints`); @@ -1097,9 +1092,7 @@ describe('when on the endpoint list page', () => { await middlewareSpy.waitForAction('serverReturnedEndpointList'); await middlewareSpy.waitForAction('serverReturnedEndpointAgentPolicies'); - const endpointActionsButton = ( - await renderResult.findAllByTestId('endpointTableRowActions') - )[0]; + endpointActionsButton = (await renderResult.findAllByTestId('endpointTableRowActions'))[0]; reactTestingLibrary.act(() => { reactTestingLibrary.fireEvent.click(endpointActionsButton); @@ -1108,7 +1101,6 @@ describe('when on the endpoint list page', () => { afterEach(() => { jest.clearAllMocks(); - (useUserPrivileges as jest.Mock).mockReturnValue(getUserPrivilegesMockDefaultValue()); }); it('shows the Responder option when all 3 processes capabilities are present in the endpoint', async () => { @@ -1116,7 +1108,7 @@ describe('when on the endpoint list page', () => { expect(responderButton).not.toHaveAttribute('disabled'); }); - it('navigates to the Actions log flyout', async () => { + it('navigates to the Response actions history flyout', async () => { const actionsLink = await renderResult.findByTestId('actionsLink'); expect(actionsLink.getAttribute('href')).toEqual( @@ -1141,6 +1133,24 @@ describe('when on the endpoint list page', () => { ); }); + it('hides isolate host option if canIsolateHost is false', () => { + (useUserPrivileges as jest.Mock).mockReturnValue({ + ...mockInitialUserPrivilegesState(), + endpointPrivileges: { + ...mockInitialUserPrivilegesState().endpointPrivileges, + canIsolateHost: false, + }, + }); + reactTestingLibrary.act(() => { + reactTestingLibrary.fireEvent.click(endpointActionsButton); + }); + reactTestingLibrary.act(() => { + reactTestingLibrary.fireEvent.click(endpointActionsButton); + }); + const isolateLink = screen.queryByTestId('isolateLink'); + expect(isolateLink).toBeNull(); + }); + it('navigates to the Security Solution Host Details page', async () => { const hostLink = await renderResult.findByTestId('hostLink'); expect(hostLink.getAttribute('href')).toEqual( diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/translations.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/translations.ts index 30001f41c3636..9ec5b0eee65cf 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/translations.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/translations.ts @@ -12,8 +12,8 @@ export const OVERVIEW = i18n.translate('xpack.securitySolution.endpointDetails.o }); export const ACTIVITY_LOG = { - tabTitle: i18n.translate('xpack.securitySolution.endpointDetails.activityLog', { - defaultMessage: 'Actions Log', + tabTitle: i18n.translate('xpack.securitySolution.endpointDetails.responseActionsHistory', { + defaultMessage: 'Response actions history', }), LogEntry: { endOfLog: i18n.translate( 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 2a54557b0095b..dd06a838a26cb 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.tsx @@ -17,7 +17,7 @@ import { MANAGEMENT_ROUTING_POLICIES_PATH, MANAGEMENT_ROUTING_TRUSTED_APPS_PATH, MANAGEMENT_ROUTING_BLOCKLIST_PATH, - MANAGEMENT_ROUTING_ACTION_HISTORY_PATH, + MANAGEMENT_ROUTING_RESPONSE_ACTIONS_HISTORY_PATH, } from '../common/constants'; import { NotFoundPage } from '../../app/404'; import { EndpointsContainer } from './endpoint_hosts'; @@ -69,9 +69,9 @@ const HostIsolationExceptionsTelemetry = () => ( ); const ResponseActionsTelemetry = () => ( - + - + ); @@ -103,7 +103,10 @@ export const ManagementContainer = memo(() => { component={HostIsolationExceptionsTelemetry} /> - + diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/artifacts/delete_modal/policy_artifacts_delete_modal.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/artifacts/delete_modal/policy_artifacts_delete_modal.test.tsx index 37f04ff804c1d..b8f7a8c19fbcd 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/artifacts/delete_modal/policy_artifacts_delete_modal.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/artifacts/delete_modal/policy_artifacts_delete_modal.test.tsx @@ -20,7 +20,7 @@ import { PolicyArtifactsDeleteModal } from './policy_artifacts_delete_modal'; import { exceptionsListAllHttpMocks } from '../../../../../mocks/exceptions_list_http_mocks'; import { ExceptionsListApiClient } from '../../../../../services/exceptions_list/exceptions_list_api_client'; import { POLICY_ARTIFACT_DELETE_MODAL_LABELS } from './translations'; -import { getDeferred } from '../../../../../components/mocks'; +import { getDeferred } from '../../../../../mocks/utils'; const listType: Array = [ 'endpoint_events', diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/endpoint_policy_create_extension.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/endpoint_policy_create_extension.tsx index 9a4dc273740e5..0617707505e52 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/endpoint_policy_create_extension.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/endpoint_policy_create_extension.tsx @@ -8,7 +8,6 @@ import React, { memo, useState, useEffect, useRef, useCallback } from 'react'; import { EuiForm, - EuiCheckbox, EuiRadio, EuiSelect, EuiText, @@ -19,7 +18,6 @@ import { import { FormattedMessage } from '@kbn/i18n-react'; import styled from 'styled-components'; import type { PackagePolicyCreateExtensionComponentProps } from '@kbn/fleet-plugin/public'; -import { useLicense } from '../../../../../../common/hooks/use_license'; import { ALL_EVENTS, CLOUD_SECURITY, @@ -28,7 +26,6 @@ import { EDR_ESSENTIAL, ENDPOINT, INTERACTIVE_ONLY, - PREVENT_MALICIOUS_BEHAVIOUR, } from './translations'; const PREFIX = 'endpoint_policy_create_extension'; @@ -70,17 +67,14 @@ const HelpTextWithPadding = styled.div` */ export const EndpointPolicyCreateExtension = memo( ({ newPolicy, onChange }) => { - const isPlatinumPlus = useLicense().isPlatinumPlus(); - // / Endpoint Radio Options (NGAV and EDRs) const [endpointPreset, setEndpointPreset] = useState('NGAV'); - const [behaviorProtectionChecked, setBehaviorProtectionChecked] = useState(false); - const [selectedCloudEvent, setSelectedCloudEvent] = useState('INTERACTIVE_ONLY'); + const [selectedCloudEvent, setSelectedCloudEvent] = useState('ALL_EVENTS'); const [selectedEnvironment, setSelectedEnvironment] = useState('endpoint'); const initialRender = useRef(true); - // Fleet will initialize the create form with a default name for the integratin policy, however, - // for endpoint security, we want the user to explicitely type in a name, so we blank it out + // Fleet will initialize the create form with a default name for the integrating policy, however, + // for endpoint security, we want the user to explicitly type in a name, so we blank it out // only during 1st component render (thus why the eslint disabled rule below). // Default values for config are endpoint + NGAV useEffect(() => { @@ -113,7 +107,7 @@ export const EndpointPolicyCreateExtension = memo { - // Skip trigerring this onChange on the initial render + // Skip triggering this onChange on the initial render if (initialRender.current) { initialRender.current = false; } else { @@ -130,11 +124,6 @@ export const EndpointPolicyCreateExtension = memo) => { setSelectedEnvironment(e?.target?.value as Environment); @@ -170,9 +152,6 @@ export const EndpointPolicyCreateExtension = memo) => { setEndpointPreset(e.target.value as EndpointPreset); }, []); - const onChangeMaliciousBehavior = useCallback((e: React.ChangeEvent) => { - setBehaviorProtectionChecked((checked) => !checked); - }, []); const getEndpointPresetsProps = useCallback( (preset: EndpointPreset) => ({ @@ -217,7 +196,7 @@ export const EndpointPolicyCreateExtension = memo ), @@ -251,7 +230,7 @@ export const EndpointPolicyCreateExtension = memo @@ -265,7 +244,7 @@ export const EndpointPolicyCreateExtension = memo @@ -279,7 +258,7 @@ export const EndpointPolicyCreateExtension = memo @@ -305,13 +284,13 @@ export const EndpointPolicyCreateExtension = memo } > - + } > - + - {isPlatinumPlus && ( - <> - - -

    - -

    -
    - - -

    - -

    -
    - - - - )} )} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/translations.ts b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/translations.ts index b50835b36995b..66688371b68de 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/translations.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_extension/translations.ts @@ -30,13 +30,13 @@ export const EDR_COMPLETE = i18n.translate( export const ENDPOINT = i18n.translate( 'xpack.securitySolution.createPackagePolicy.stepConfigure.endpointDropdownOption', { - defaultMessage: 'Endpoint', + defaultMessage: 'Traditional Endpoints (desktops, laptops, virtual machines)', } ); export const CLOUD_SECURITY = i18n.translate( - 'xpack.securitySolution.createPackagePolicy.stepConfigure.cloudSecurityDropdownOption', + 'xpack.securitySolution.createPackagePolicy.stepConfigure.cloudDropdownOption', { - defaultMessage: 'Cloud Security', + defaultMessage: 'Cloud Workloads (Linux servers or Kubernetes environments)', } ); export const INTERACTIVE_ONLY = i18n.translate( @@ -51,15 +51,9 @@ export const ALL_EVENTS = i18n.translate( defaultMessage: 'All events', } ); -export const PREVENT_MALWARE = i18n.translate( - 'xpack.securitySolution.createPackagePolicy.stepConfigure.cloudEventFiltersPreventionMalware', +export const PREVENT_MALICIOUS_BEHAVIOR = i18n.translate( + 'xpack.securitySolution.createPackagePolicy.stepConfigure.cloudEventFiltersPreventionMaliciousBehavior', { - defaultMessage: 'Prevent Malware', - } -); -export const PREVENT_MALICIOUS_BEHAVIOUR = i18n.translate( - 'xpack.securitySolution.createPackagePolicy.stepConfigure.cloudEventFiltersPreventionMaliciousBehaviour', - { - defaultMessage: 'Prevent Malicious Behaviour', + defaultMessage: 'Prevent Malicious Behavior', } ); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_multi_step_extension.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_multi_step_extension.tsx new file mode 100644 index 0000000000000..747d0990b8fc0 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_create_multi_step_extension.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import type { PackagePolicyCreateMultiStepExtensionComponentProps } from '@kbn/fleet-plugin/public'; + +/** + * TBD: A component to be displayed in multi step onboarding process. + */ +export const EndpointPolicyCreateMultiStepExtension = + memo(({ newPolicy }) => { + return <>; + }); +EndpointPolicyCreateMultiStepExtension.displayName = 'EndpointPolicyCreateMultiStepExtension'; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_multi_step_extension.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_multi_step_extension.tsx new file mode 100644 index 0000000000000..b989c07fef45b --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_multi_step_extension.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { lazy } from 'react'; +import type { PackagePolicyCreateMultiStepExtensionComponent } from '@kbn/fleet-plugin/public'; + +export const LazyEndpointPolicyCreateMultiStepExtension = + lazy(async () => { + const { EndpointPolicyCreateMultiStepExtension } = await import( + './endpoint_policy_create_multi_step_extension' + ); + return { + default: EndpointPolicyCreateMultiStepExtension, + }; + }); diff --git a/x-pack/plugins/security_solution/public/management/pages/response_actions/index.tsx b/x-pack/plugins/security_solution/public/management/pages/response_actions/index.tsx index 0d3f029cc34ce..25d4fa117da6f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/response_actions/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/response_actions/index.tsx @@ -7,7 +7,7 @@ import { Switch } from 'react-router-dom'; import { Route } from '@kbn/kibana-react-plugin/public'; import React, { memo } from 'react'; -import { MANAGEMENT_ROUTING_ACTION_HISTORY_PATH } from '../../common/constants'; +import { MANAGEMENT_ROUTING_RESPONSE_ACTIONS_HISTORY_PATH } from '../../common/constants'; import { NotFoundPage } from '../../../app/404'; import { ResponseActionsListPage } from './view/response_actions_list_page'; @@ -15,7 +15,7 @@ export const ResponseActionsContainer = memo(() => { return ( diff --git a/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.test.tsx b/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.test.tsx index 734db973826c9..7b0132a4b4be4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.test.tsx @@ -112,7 +112,7 @@ jest.mock('@kbn/kibana-react-plugin/public', () => { jest.mock('../../../hooks/endpoint/use_get_endpoints_list'); const mockUseGetEndpointsList = useGetEndpointsList as jest.Mock; -describe('Action history page', () => { +describe('Response actions history page', () => { const testPrefix = 'response-actions-list'; let render: () => ReturnType; @@ -164,7 +164,7 @@ describe('Action history page', () => { describe('Hide/Show header', () => { it('should show header when data is in', () => { reactTestingLibrary.act(() => { - history.push('/administration/action_history?page=3&pageSize=20'); + history.push('/administration/response_actions_history?page=3&pageSize=20'); }); render(); const { getByTestId } = renderResult; @@ -173,7 +173,7 @@ describe('Action history page', () => { it('should not show header when there is no actions index', () => { reactTestingLibrary.act(() => { - history.push('/administration/action_history?page=3&pageSize=20'); + history.push('/administration/response_actions_history?page=3&pageSize=20'); }); mockUseGetEndpointActionList = { ...baseMockedActionList, @@ -190,7 +190,7 @@ describe('Action history page', () => { describe('Read from URL params', () => { it('should read and set paging values from URL params', () => { reactTestingLibrary.act(() => { - history.push('/administration/action_history?page=3&pageSize=20'); + history.push('/administration/response_actions_history?page=3&pageSize=20'); }); render(); const { getByTestId } = renderResult; @@ -203,7 +203,7 @@ describe('Action history page', () => { it('should read and set command filter values from URL params', () => { const filterPrefix = 'actions-filter'; reactTestingLibrary.act(() => { - history.push('/administration/action_history?commands=release,processes'); + history.push('/administration/response_actions_history?commands=release,processes'); }); render(); @@ -240,7 +240,7 @@ describe('Action history page', () => { const filterPrefix = 'hosts-filter'; reactTestingLibrary.act(() => { history.push( - '/administration/action_history?hosts=agent-id-1,agent-id-2,agent-id-4,agent-id-5' + '/administration/response_actions_history?hosts=agent-id-1,agent-id-2,agent-id-4,agent-id-5' ); }); @@ -270,7 +270,7 @@ describe('Action history page', () => { it('should read and set status filter values from URL params', () => { const filterPrefix = 'statuses-filter'; reactTestingLibrary.act(() => { - history.push('/administration/action_history?statuses=pending,failed'); + history.push('/administration/response_actions_history?statuses=pending,failed'); }); render(); @@ -293,7 +293,7 @@ describe('Action history page', () => { it('should set selected users search input strings to URL params ', () => { const filterPrefix = 'users-filter'; reactTestingLibrary.act(() => { - history.push('/administration/action_history?users=userX,userY'); + history.push('/administration/response_actions_history?users=userX,userY'); }); render(); @@ -305,7 +305,7 @@ describe('Action history page', () => { it('should read and set relative date ranges filter values from URL params', () => { reactTestingLibrary.act(() => { - history.push('/administration/action_history?startDate=now-23m&endDate=now-1m'); + history.push('/administration/response_actions_history?startDate=now-23m&endDate=now-1m'); }); render(); @@ -324,7 +324,9 @@ describe('Action history page', () => { const startDate = '2022-09-12T11:00:00.000Z'; const endDate = '2022-09-12T11:30:33.000Z'; reactTestingLibrary.act(() => { - history.push(`/administration/action_history?startDate=${startDate}&endDate=${endDate}`); + history.push( + `/administration/response_actions_history?startDate=${startDate}&endDate=${endDate}` + ); }); const { getByTestId } = render(); diff --git a/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.tsx b/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.tsx index e1f3705b4489c..d1ae96099387e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/response_actions/view/response_actions_list_page.tsx @@ -6,7 +6,7 @@ */ import React, { useState, useCallback } from 'react'; -import { ACTION_HISTORY } from '../../../../app/translations'; +import { RESPONSE_ACTIONS_HISTORY } from '../../../../app/translations'; import { AdministrationListPage } from '../../../components/administration_list_page'; import { ResponseActionsLog } from '../../../components/endpoint_response_actions_list/response_actions_log'; import { UX_MESSAGES } from '../../../components/endpoint_response_actions_list/translations'; @@ -19,7 +19,7 @@ export const ResponseActionsListPage = () => { return ( diff --git a/x-pack/plugins/security_solution/public/management/types.ts b/x-pack/plugins/security_solution/public/management/types.ts index 96c1983c8f254..4ca2c34dfcc19 100644 --- a/x-pack/plugins/security_solution/public/management/types.ts +++ b/x-pack/plugins/security_solution/public/management/types.ts @@ -31,7 +31,7 @@ export enum AdministrationSubTab { eventFilters = 'event_filters', hostIsolationExceptions = 'host_isolation_exceptions', blocklist = 'blocklist', - actionHistory = 'action_history', + responseActionsHistory = 'response_actions_history', } /** diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/anomalies/columns.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/anomalies/columns.tsx index 8f37f8af1ac3f..cc727efa5188e 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/anomalies/columns.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/anomalies/columns.tsx @@ -7,6 +7,7 @@ import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; import type { EuiBasicTableColumn } from '@elastic/eui'; +import { EuiLink } from '@elastic/eui'; import { ML_PAGES, useMlHref } from '@kbn/ml-plugin/public'; import { useDispatch } from 'react-redux'; import * as i18n from './translations'; @@ -29,6 +30,9 @@ const MediumShadeText = styled.span` color: ${({ theme }) => theme.eui.euiColorMediumShade}; `; +const INSTALL_JOBS_DOC = + 'https://www.elastic.co/guide/en/machine-learning/current/ml-ad-run-jobs.html'; + export const useAnomaliesColumns = (loading: boolean): AnomaliesColumns => { const columns: AnomaliesColumns = useMemo( () => [ @@ -73,6 +77,14 @@ export const useAnomaliesColumns = (loading: boolean): AnomaliesColumns => { return ; } + if (status === AnomalyJobStatus.uninstalled) { + return ( + + {i18n.JOB_STATUS_UNINSTALLED} + + ); + } + return {I18N_JOB_STATUS[status]}; } }, @@ -86,7 +98,6 @@ export const useAnomaliesColumns = (loading: boolean): AnomaliesColumns => { const I18N_JOB_STATUS = { [AnomalyJobStatus.disabled]: i18n.JOB_STATUS_DISABLED, [AnomalyJobStatus.failed]: i18n.JOB_STATUS_FAILED, - [AnomalyJobStatus.uninstalled]: i18n.JOB_STATUS_UNINSTALLED, }; const EnableJobLink = ({ jobId }: { jobId: string }) => { diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.test.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.test.tsx index fe8fd01665280..0a8abe2500e0c 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.test.tsx @@ -19,24 +19,12 @@ const severityCount: SeverityCount = { [RiskSeverity.unknown]: 1, [RiskSeverity.critical]: 1, }; -const href = 'test-href'; describe('RiskScoreDonutChart', () => { - it('renders link', () => { - const { getByTestId } = render( - - {}} href={href} /> - - ); - - expect(getByTestId('view-total-button')).toBeInTheDocument(); - expect(getByTestId('view-total-button')).toHaveAttribute('href', href); - }); - it('renders legends', () => { const { getByTestId } = render( - {}} href={href} /> + ); diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.tsx index aad763e7ee38e..ecd3f31489d6b 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/common/risk_score_donut_chart.tsx @@ -6,11 +6,9 @@ */ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import type { MouseEventHandler } from 'react'; import React from 'react'; import type { ShapeTreeNode } from '@elastic/charts'; import styled from 'styled-components'; -import { LinkAnchor } from '../../../../common/components/links'; import type { SeverityCount } from '../../../../common/components/severity/types'; import { useRiskDonutChartData } from './use_risk_donut_chart_data'; import type { FillColor } from '../../../../common/components/charts/donutchart'; @@ -39,11 +37,9 @@ const StyledLegendItems = styled(EuiFlexItem)` interface RiskScoreDonutChartProps { severityCount: SeverityCount; - onClick: MouseEventHandler; - href: string; } -export const RiskScoreDonutChart = ({ severityCount, onClick, href }: RiskScoreDonutChartProps) => { +export const RiskScoreDonutChart = ({ severityCount }: RiskScoreDonutChartProps) => { const [donutChartData, legendItems, total] = useRiskDonutChartData(severityCount); return ( @@ -56,11 +52,7 @@ export const RiskScoreDonutChart = ({ severityCount, onClick, href }: RiskScoreD data={donutChartData ?? null} fillColor={fillColor} height={DONUT_HEIGHT} - label={ - - {i18n.TOTAL_LABEL} - - } + label={i18n.TOTAL_LABEL} title={} totalCount={total} /> diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/header/index.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/header/index.tsx index f94c7d52f6fce..c1a52364a76f8 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/header/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/header/index.tsx @@ -8,7 +8,7 @@ import React, { useMemo } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiPanel, EuiTitle } from '@elastic/eui'; import styled from 'styled-components'; import { useDispatch } from 'react-redux'; -import { sum } from 'lodash/fp'; +import { sumBy } from 'lodash/fp'; import { ML_PAGES, useMlHref } from '@kbn/ml-plugin/public'; import { useHostRiskScoreKpi, useUserRiskScoreKpi } from '../../../../risk_score/containers'; import { LinkAnchor, useGetSecuritySolutionLinkProps } from '../../../../common/components/links'; @@ -25,15 +25,41 @@ import { useNotableAnomaliesSearch } from '../../../../common/components/ml/anom import { useGlobalTime } from '../../../../common/containers/use_global_time'; import { useKibana } from '../../../../common/lib/kibana'; import { useMlCapabilities } from '../../../../common/components/ml/hooks/use_ml_capabilities'; +import { useQueryInspector } from '../../../../common/components/page/manage_query'; const StyledEuiTitle = styled(EuiTitle)` - color: ${({ theme: { eui } }) => eui.euiColorVis9}; + color: ${({ theme: { eui } }) => eui.euiColorDanger}; `; +const HOST_RISK_QUERY_ID = 'hostRiskScoreKpiQuery'; +const USER_RISK_QUERY_ID = 'userRiskScoreKpiQuery'; + export const EntityAnalyticsHeader = () => { - const { severityCount: hostsSeverityCount } = useHostRiskScoreKpi({}); - const { severityCount: usersSeverityCount } = useUserRiskScoreKpi({}); const { from, to } = useGlobalTime(false); + const timerange = useMemo( + () => ({ + from, + to, + }), + [from, to] + ); + + const { + severityCount: hostsSeverityCount, + loading: hostRiskLoading, + inspect: inspectHostRiskScore, + refetch: refetchHostRiskScore, + } = useHostRiskScoreKpi({ timerange }); + + const { + severityCount: usersSeverityCount, + loading: userRiskLoading, + refetch: refetchUserRiskScore, + inspect: inspectUserRiskScore, + } = useUserRiskScoreKpi({ + timerange, + }); + const { data } = useNotableAnomaliesSearch({ skip: false, from, to }); const dispatch = useDispatch(); const getSecuritySolutionLinkProps = useGetSecuritySolutionLinkProps(); @@ -88,7 +114,33 @@ export const EntityAnalyticsHeader = () => { return [onClick, href]; }, [dispatch, getSecuritySolutionLinkProps]); - const totalAnomalies = useMemo(() => sum(data.map(({ count }) => count)), [data]); + const { deleteQuery, setQuery } = useGlobalTime(); + + useQueryInspector({ + queryId: USER_RISK_QUERY_ID, + loading: userRiskLoading, + refetch: refetchUserRiskScore, + setQuery, + deleteQuery, + inspect: inspectUserRiskScore, + }); + + useQueryInspector({ + queryId: HOST_RISK_QUERY_ID, + loading: hostRiskLoading, + refetch: refetchHostRiskScore, + setQuery, + deleteQuery, + inspect: inspectHostRiskScore, + }); + + // Anomalies are enabled if at least one job is installed + const areJobsEnabled = useMemo(() => data.some(({ jobId }) => !!jobId), [data]); + + const totalAnomalies = useMemo( + () => (areJobsEnabled ? sumBy('count', data) : '-'), + [data, areJobsEnabled] + ); const jobsUrl = useMlHref(ml, http.basePath.get(), { page: ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE, @@ -102,7 +154,9 @@ export const EntityAnalyticsHeader = () => { - {hostsSeverityCount[RiskSeverity.critical]} + + {hostsSeverityCount ? hostsSeverityCount[RiskSeverity.critical] : '-'} + @@ -122,7 +176,9 @@ export const EntityAnalyticsHeader = () => { - {usersSeverityCount[RiskSeverity.critical]} + + {usersSeverityCount ? usersSeverityCount[RiskSeverity.critical] : '-'} + diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/host_risk_score/index.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/host_risk_score/index.tsx index 123f190446255..49df0b1b0e456 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/host_risk_score/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/host_risk_score/index.tsx @@ -5,7 +5,7 @@ * 2.0. */ import React, { useEffect, useMemo, useState } from 'react'; -import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiPanel } from '@elastic/eui'; +import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { useDispatch } from 'react-redux'; import { RiskScoresDeprecated } from '../../../../common/components/risk_score/risk_score_deprecated'; @@ -19,7 +19,7 @@ import { HeaderSection } from '../../../../common/components/header_section'; import { useHostRiskScore, useHostRiskScoreKpi } from '../../../../risk_score/containers'; import type { RiskSeverity } from '../../../../../common/search_strategy'; -import { RiskScoreEntity } from '../../../../../common/search_strategy'; +import { EMPTY_SEVERITY_COUNT, RiskScoreEntity } from '../../../../../common/search_strategy'; import { SecurityPageName } from '../../../../app/types'; import * as i18n from './translations'; import { generateSeverityFilter } from '../../../../hosts/store/helpers'; @@ -30,12 +30,16 @@ import { useQueryToggle } from '../../../../common/containers/query_toggle'; import { hostsActions } from '../../../../hosts/store'; import { RiskScoreDonutChart } from '../common/risk_score_donut_chart'; import { BasicTableWithoutBorderBottom } from '../common/basic_table_without_border_bottom'; -import { RISKY_HOSTS_EXTERNAL_DOC_LINK } from '../../../../../common/constants'; +import { RISKY_HOSTS_DOC_LINK } from '../../../../../common/constants'; import { EntityAnalyticsHostRiskScoreDisable } from '../../../../common/components/risk_score/risk_score_disabled/host_risk_score_disabled'; import { RiskScoreHeaderTitle } from '../../../../common/components/risk_score/risk_score_onboarding/risk_score_header_title'; import { RiskScoresNoDataDetected } from '../../../../common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected'; +import { useRefetchQueries } from '../../../../common/hooks/use_refetch_queries'; +import { Loader } from '../../../../common/components/loader'; +import { Panel } from '../../../../common/components/panel'; const TABLE_QUERY_ID = 'hostRiskDashboardTable'; +const HOST_RISK_KPI_QUERY_ID = 'headerHostRiskScoreKpiQuery'; const EntityAnalyticsHostRiskScoresComponent = () => { const { deleteQuery, setQuery, from, to } = useGlobalTime(); @@ -52,11 +56,6 @@ const EntityAnalyticsHostRiskScoresComponent = () => { return filter ? JSON.stringify(filter.query) : undefined; }, [selectedSeverity]); - const { severityCount, loading: isKpiLoading } = useHostRiskScoreKpi({ - filterQuery: severityFilter, - skip: !toggleStatus, - }); - const timerange = useMemo( () => ({ from, @@ -65,6 +64,25 @@ const EntityAnalyticsHostRiskScoresComponent = () => { [from, to] ); + const { + severityCount, + loading: isKpiLoading, + refetch: refetchKpi, + inspect: inspectKpi, + } = useHostRiskScoreKpi({ + filterQuery: severityFilter, + skip: !toggleStatus, + timerange, + }); + + useQueryInspector({ + queryId: HOST_RISK_KPI_QUERY_ID, + loading: isKpiLoading, + refetch: refetchKpi, + setQuery, + deleteQuery, + inspect: inspectKpi, + }); const [ isTableLoading, { data, inspect, refetch, isDeprecated, isLicenseValid, isModuleEnabled }, @@ -107,31 +125,33 @@ const EntityAnalyticsHostRiskScoresComponent = () => { return [onClick, href]; }, [dispatch, getSecuritySolutionLinkProps]); + const refreshPage = useRefetchQueries(); + if (!isLicenseValid) { return null; } - if (!isModuleEnabled) { - return ; + if (!isModuleEnabled && !isTableLoading) { + return ; } - if (isDeprecated) { + if (isDeprecated && !isTableLoading) { return ( ); } if (isModuleEnabled && selectedSeverity.length === 0 && data && data.length === 0) { - return ; + return ; } return ( - + } titleSize="s" @@ -147,7 +167,7 @@ const EntityAnalyticsHostRiskScoresComponent = () => { {i18n.LEARN_MORE} @@ -156,7 +176,7 @@ const EntityAnalyticsHostRiskScoresComponent = () => { @@ -176,11 +196,7 @@ const EntityAnalyticsHostRiskScoresComponent = () => { {toggleStatus && ( - + { )} - + {(isTableLoading || isKpiLoading) && ( + + )} + ); }; diff --git a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/user_risk_score/index.tsx b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/user_risk_score/index.tsx index fe4a72f466ea0..034e62bb37ad3 100644 --- a/x-pack/plugins/security_solution/public/overview/components/entity_analytics/user_risk_score/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/entity_analytics/user_risk_score/index.tsx @@ -5,7 +5,7 @@ * 2.0. */ import React, { useEffect, useMemo, useState } from 'react'; -import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiPanel } from '@elastic/eui'; +import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { useDispatch } from 'react-redux'; import { RiskScoresDeprecated } from '../../../../common/components/risk_score/risk_score_deprecated'; import { SeverityFilterGroup } from '../../../../common/components/severity/severity_filter_group'; @@ -13,7 +13,7 @@ import { LinkButton, useGetSecuritySolutionLinkProps } from '../../../../common/ import { LastUpdatedAt } from '../../../../common/components/last_updated_at'; import { HeaderSection } from '../../../../common/components/header_section'; import type { RiskSeverity } from '../../../../../common/search_strategy'; -import { RiskScoreEntity } from '../../../../../common/search_strategy'; +import { EMPTY_SEVERITY_COUNT, RiskScoreEntity } from '../../../../../common/search_strategy'; import { SecurityPageName } from '../../../../app/types'; import * as i18n from './translations'; import { generateSeverityFilter } from '../../../../hosts/store/helpers'; @@ -30,12 +30,16 @@ import { getTabsOnUsersUrl } from '../../../../common/components/link_to/redirec import { RiskScoreDonutChart } from '../common/risk_score_donut_chart'; import { BasicTableWithoutBorderBottom } from '../common/basic_table_without_border_bottom'; -import { RISKY_USERS_EXTERNAL_DOC_LINK } from '../../../../../common/constants'; +import { RISKY_USERS_DOC_LINK } from '../../../../../common/constants'; import { EntityAnalyticsUserRiskScoreDisable } from '../../../../common/components/risk_score/risk_score_disabled/user_risk_score.disabled'; import { RiskScoreHeaderTitle } from '../../../../common/components/risk_score/risk_score_onboarding/risk_score_header_title'; import { RiskScoresNoDataDetected } from '../../../../common/components/risk_score/risk_score_onboarding/risk_score_no_data_detected'; +import { useRefetchQueries } from '../../../../common/hooks/use_refetch_queries'; +import { Loader } from '../../../../common/components/loader'; +import { Panel } from '../../../../common/components/panel'; const TABLE_QUERY_ID = 'userRiskDashboardTable'; +const USER_RISK_KPI_QUERY_ID = 'headerUserRiskScoreKpiQuery'; const EntityAnalyticsUserRiskScoresComponent = () => { const { deleteQuery, setQuery, from, to } = useGlobalTime(); @@ -52,11 +56,6 @@ const EntityAnalyticsUserRiskScoresComponent = () => { return filter ? JSON.stringify(filter.query) : undefined; }, [selectedSeverity]); - const { severityCount, loading: isKpiLoading } = useUserRiskScoreKpi({ - filterQuery: severityFilter, - skip: !toggleStatus, - }); - const timerange = useMemo( () => ({ from, @@ -65,6 +64,17 @@ const EntityAnalyticsUserRiskScoresComponent = () => { [from, to] ); + const { + severityCount, + loading: isKpiLoading, + refetch: refetchKpi, + inspect: inspectKpi, + } = useUserRiskScoreKpi({ + filterQuery: severityFilter, + skip: !toggleStatus, + timerange, + }); + const [ isTableLoading, { data, inspect, refetch, isLicenseValid, isDeprecated, isModuleEnabled }, @@ -87,6 +97,15 @@ const EntityAnalyticsUserRiskScoresComponent = () => { inspect, }); + useQueryInspector({ + queryId: USER_RISK_KPI_QUERY_ID, + loading: isKpiLoading, + refetch: refetchKpi, + setQuery, + deleteQuery, + inspect: inspectKpi, + }); + useEffect(() => { setUpdatedAt(Date.now()); }, [isTableLoading, isKpiLoading]); // Update the time when data loads @@ -106,31 +125,33 @@ const EntityAnalyticsUserRiskScoresComponent = () => { return [onClick, href]; }, [dispatch, getSecuritySolutionLinkProps]); + const refreshPage = useRefetchQueries(); + if (!isLicenseValid) { return null; } - if (!isModuleEnabled) { - return ; + if (!isModuleEnabled && !isTableLoading) { + return ; } - if (isDeprecated) { + if (isDeprecated && !isTableLoading) { return ( ); } if (isModuleEnabled && selectedSeverity.length === 0 && data && data.length === 0) { - return ; + return ; } return ( - + } titleSize="s" @@ -146,7 +167,7 @@ const EntityAnalyticsUserRiskScoresComponent = () => { {i18n.LEARN_MORE} @@ -155,7 +176,7 @@ const EntityAnalyticsUserRiskScoresComponent = () => { @@ -175,11 +196,7 @@ const EntityAnalyticsUserRiskScoresComponent = () => { {toggleStatus && ( - + { )} - + {(isTableLoading || isKpiLoading) && ( + + )} + ); }; 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 e85a9134eb42b..70c304e031163 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 @@ -86,10 +86,17 @@ export const HostOverview = React.memo( ); const { from, to } = useGlobalTime(); + const timerange = useMemo( + () => ({ + from, + to, + }), + [from, to] + ); const [_, { data: hostRisk, isLicenseValid }] = useHostRiskScore({ filterQuery, skip: hostName == null, - timerange: { to, from }, + timerange, }); const getDefaultRenderer = useCallback( diff --git a/x-pack/plugins/security_solution/public/overview/components/user_overview/index.tsx b/x-pack/plugins/security_solution/public/overview/components/user_overview/index.tsx index e635f94e51d51..68b40f581d384 100644 --- a/x-pack/plugins/security_solution/public/overview/components/user_overview/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/user_overview/index.tsx @@ -85,10 +85,18 @@ export const UserOverview = React.memo( const { from, to } = useGlobalTime(); + const timerange = useMemo( + () => ({ + from, + to, + }), + [from, to] + ); + const [_, { data: userRisk, isLicenseValid }] = useUserRiskScore({ filterQuery, skip: userName == null, - timerange: { to, from }, + timerange, }); const getDefaultRenderer = useCallback( diff --git a/x-pack/plugins/security_solution/public/overview/pages/entity_analytics.tsx b/x-pack/plugins/security_solution/public/overview/pages/entity_analytics.tsx index bc478eeecc4b1..3ef48810d6094 100644 --- a/x-pack/plugins/security_solution/public/overview/pages/entity_analytics.tsx +++ b/x-pack/plugins/security_solution/public/overview/pages/entity_analytics.tsx @@ -27,15 +27,15 @@ import { InputsModelId } from '../../common/store/inputs/constants'; const EntityAnalyticsComponent = () => { const { indicesExist, loading: isSourcererLoading, indexPattern } = useSourcererDataView(); + const { isPlatinumOrTrialLicense, capabilitiesFetched } = useMlCapabilities(); - const isPlatinumOrTrialLicense = useMlCapabilities().isPlatinumOrTrialLicense; return ( <> {indicesExist ? ( <> - {isPlatinumOrTrialLicense && ( + {isPlatinumOrTrialLicense && capabilitiesFetched && ( { /> )} - {isPlatinumOrTrialLicense ? ( - isSourcererLoading ? ( - - ) : ( - - - - + {!isPlatinumOrTrialLicense && capabilitiesFetched ? ( + + ) : isSourcererLoading ? ( + + ) : ( + + + + - - - + + + - - - + + + - - - - - ) - ) : ( - + + + + )} diff --git a/x-pack/plugins/security_solution/public/plugin.tsx b/x-pack/plugins/security_solution/public/plugin.tsx index 7affdd066742f..6ab6fcd6e628c 100644 --- a/x-pack/plugins/security_solution/public/plugin.tsx +++ b/x-pack/plugins/security_solution/public/plugin.tsx @@ -60,6 +60,7 @@ import { ExperimentalFeaturesService } from './common/experimental_features_serv import { getLazyEndpointPolicyEditExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_edit_extension'; import { LazyEndpointPolicyCreateExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_extension'; +import { LazyEndpointPolicyCreateMultiStepExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_multi_step_extension'; import { getLazyEndpointPackageCustomExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_package_custom_extension'; import { getLazyEndpointPolicyResponseExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_response_extension'; import { getLazyEndpointGenericErrorsListExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_generic_errors_list'; @@ -246,6 +247,12 @@ export class Plugin implements IPlugin { - const { timerange, onlyLatest, filterQuery, sort, skip = false, pagination } = params ?? {}; + const { + timerange, + onlyLatest = true, + filterQuery, + sort, + skip = false, + pagination, + } = params ?? {}; const spaceId = useSpaceId(); const defaultIndex = spaceId ? getHostRiskIndex(spaceId, onlyLatest) : undefined; @@ -81,7 +88,14 @@ export const useHostRiskScore = (params?: UseRiskScoreParams) => { }; export const useUserRiskScore = (params?: UseRiskScoreParams) => { - const { timerange, onlyLatest, filterQuery, sort, skip = false, pagination } = params ?? {}; + const { + timerange, + onlyLatest = true, + filterQuery, + sort, + skip = false, + pagination, + } = params ?? {}; const spaceId = useSpaceId(); const defaultIndex = spaceId ? getUserRiskIndex(spaceId, onlyLatest) : undefined; @@ -99,6 +113,7 @@ export const useUserRiskScore = (params?: UseRiskScoreParams) => { const useRiskScore = ({ timerange, + onlyLatest, filterQuery, sort, skip = false, @@ -167,6 +182,11 @@ const useRiskScore = (timerange ? { to: timerange.to, from: timerange.from, interval: '' } : undefined), + [timerange] + ); + const riskScoreRequest = useMemo( () => defaultIndex @@ -182,9 +202,19 @@ const useRiskScore = { @@ -196,10 +226,25 @@ const useRiskScore = { - if (!skip && riskScoreRequest != null && isLicenseValid && isEnabled && !isDeprecated) { + if ( + !skip && + !isDeprecatedLoading && + riskScoreRequest != null && + isLicenseValid && + isEnabled && + !isDeprecated + ) { search(riskScoreRequest); } - }, [isEnabled, isDeprecated, isLicenseValid, riskScoreRequest, search, skip]); + }, [ + isEnabled, + isDeprecated, + isLicenseValid, + isDeprecatedLoading, + riskScoreRequest, + search, + skip, + ]); return [loading || isDeprecatedLoading, riskScoreResponse]; }; diff --git a/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.test.ts b/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.test.ts index cb5b549894044..619de81b36b9b 100644 --- a/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.test.ts +++ b/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.test.ts @@ -37,7 +37,7 @@ describe(`risk score feature status`, () => { isDeprecated: true, isLicenseValid: true, isEnabled: true, - isLoading: false, + isLoading: true, }; test('does not search if license is not valid, and initial isDeprecated state is false', () => { diff --git a/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.ts b/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.ts index cf5a8feb0ee0d..0099ed0df3f09 100644 --- a/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.ts +++ b/x-pack/plugins/security_solution/public/risk_score/containers/feature_status/index.ts @@ -27,7 +27,7 @@ export const useRiskScoreFeatureStatus = ( factoryQueryType: RiskQueries.hostsRiskScore | RiskQueries.usersRiskScore, defaultIndex?: string ): RiskScoresFeatureStatus => { - const isPlatinumOrTrialLicense = useMlCapabilities().isPlatinumOrTrialLicense; + const { isPlatinumOrTrialLicense, capabilitiesFetched } = useMlCapabilities(); const entity = useMemo( () => factoryQueryType === RiskQueries.hostsRiskScore ? RiskScoreEntity.host : RiskScoreEntity.user, @@ -66,7 +66,7 @@ export const useRiskScoreFeatureStatus = ( return { error, - isLoading, + isLoading: isLoading || !capabilitiesFetched || defaultIndex == null, refetch: searchIndexStatus, isLicenseValid: isPlatinumOrTrialLicense, ...response, diff --git a/x-pack/plugins/security_solution/public/risk_score/containers/kpi/index.tsx b/x-pack/plugins/security_solution/public/risk_score/containers/kpi/index.tsx index 2c137a8bf1e06..340ec3347a4f7 100644 --- a/x-pack/plugins/security_solution/public/risk_score/containers/kpi/index.tsx +++ b/x-pack/plugins/security_solution/public/risk_score/containers/kpi/index.tsx @@ -5,77 +5,35 @@ * 2.0. */ -import type { Observable } from 'rxjs'; -import { filter } from 'rxjs/operators'; import { useEffect, useMemo } from 'react'; -import { useObservable, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; -import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/common'; -import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; -import { createFilter } from '../../../common/containers/helpers'; - -import type { - KpiRiskScoreRequestOptions, - KpiRiskScoreStrategyResponse, -} from '../../../../common/search_strategy'; + import { getHostRiskIndex, getUserRiskIndex, RiskQueries, RiskSeverity, RiskScoreEntity, + EMPTY_SEVERITY_COUNT, } from '../../../../common/search_strategy'; - -import { useKibana } from '../../../common/lib/kibana'; +import * as i18n from './translations'; import { isIndexNotFoundError } from '../../../common/utils/exceptions'; import type { ESTermQuery } from '../../../../common/typed_json'; import type { SeverityCount } from '../../../common/components/severity/types'; import { useSpaceId } from '../../../common/hooks/use_space_id'; import { useMlCapabilities } from '../../../common/components/ml/hooks/use_ml_capabilities'; - -type GetHostRiskScoreProps = KpiRiskScoreRequestOptions & { - data: DataPublicPluginStart; - signal: AbortSignal; -}; - -const getRiskScoreKpi = ({ - data, - defaultIndex, - signal, - filterQuery, - entity, -}: GetHostRiskScoreProps): Observable => - data.search.search( - { - defaultIndex, - factoryQueryType: RiskQueries.kpiRiskScore, - filterQuery: createFilter(filterQuery), - entity, - }, - { - strategy: 'securitySolutionSearchStrategy', - abortSignal: signal, - } - ); - -const getRiskScoreKpiComplete = ( - props: GetHostRiskScoreProps -): Observable => { - return getRiskScoreKpi(props).pipe( - filter((response) => { - return isErrorResponse(response) || isCompleteResponse(response); - }) - ); -}; - -const getRiskScoreKpiWithOptionalSignal = withOptionalSignal(getRiskScoreKpiComplete); - -const useRiskScoreKpiComplete = () => useObservable(getRiskScoreKpiWithOptionalSignal); +import { useSearchStrategy } from '../../../common/containers/use_search_strategy'; +import type { InspectResponse } from '../../../types'; +import type { inputsModel } from '../../../common/store'; +import { useAppToasts } from '../../../common/hooks/use_app_toasts'; interface RiskScoreKpi { error: unknown; isModuleDisabled: boolean; - severityCount: SeverityCount; + severityCount?: SeverityCount; loading: boolean; + refetch: inputsModel.Refetch; + inspect: InspectResponse; + timerange?: { to: string; from: string }; } type UseHostRiskScoreKpiProps = Omit< @@ -90,6 +48,7 @@ type UseUserRiskScoreKpiProps = Omit< export const useUserRiskScoreKpi = ({ filterQuery, skip, + timerange, }: UseUserRiskScoreKpiProps): RiskScoreKpi => { const spaceId = useSpaceId(); const defaultIndex = spaceId ? getUserRiskIndex(spaceId) : undefined; @@ -101,12 +60,14 @@ export const useUserRiskScoreKpi = ({ defaultIndex, entity: RiskScoreEntity.user, featureEnabled: isPlatinumOrTrialLicense, + timerange, }); }; export const useHostRiskScoreKpi = ({ filterQuery, skip, + timerange, }: UseHostRiskScoreKpiProps): RiskScoreKpi => { const spaceId = useSpaceId(); const defaultIndex = spaceId ? getHostRiskIndex(spaceId) : undefined; @@ -118,6 +79,7 @@ export const useHostRiskScoreKpi = ({ defaultIndex, entity: RiskScoreEntity.host, featureEnabled: isPlatinumOrTrialLicense, + timerange, }); }; @@ -127,6 +89,7 @@ interface UseRiskScoreKpiProps { defaultIndex: string | undefined; entity: RiskScoreEntity; featureEnabled: boolean; + timerange?: { to: string; from: string }; } const useRiskScoreKpi = ({ @@ -135,33 +98,59 @@ const useRiskScoreKpi = ({ defaultIndex, entity, featureEnabled, + timerange, }: UseRiskScoreKpiProps): RiskScoreKpi => { - const { error, result, start, loading } = useRiskScoreKpiComplete(); - const { data } = useKibana().services; + const { addError } = useAppToasts(); + + const { loading, result, search, refetch, inspect, error } = + useSearchStrategy({ + factoryQueryType: RiskQueries.kpiRiskScore, + initialResult: { + kpiRiskScore: EMPTY_SEVERITY_COUNT, + }, + abort: skip, + showErrorToast: false, + }); + const isModuleDisabled = !!error && isIndexNotFoundError(error); useEffect(() => { if (!skip && defaultIndex && featureEnabled) { - start({ - data, + search({ filterQuery, defaultIndex: [defaultIndex], entity, }); } - }, [data, defaultIndex, start, filterQuery, skip, entity, featureEnabled]); - - const severityCount = useMemo( - () => ({ - [RiskSeverity.unknown]: 0, - [RiskSeverity.low]: 0, - [RiskSeverity.moderate]: 0, - [RiskSeverity.high]: 0, - [RiskSeverity.critical]: 0, - ...(result?.kpiRiskScore ?? {}), - }), - [result] - ); - - return { error, severityCount, loading, isModuleDisabled }; + }, [defaultIndex, search, filterQuery, skip, entity, featureEnabled]); + + // since query does not take timerange arg, we need to manually refetch when time range updates + useEffect(() => { + refetch(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [timerange?.to, timerange?.from]); + + useEffect(() => { + if (error) { + if (!isIndexNotFoundError(error)) { + addError(error, { title: i18n.FAIL_RISK_SCORE }); + } + } + }, [addError, error]); + + const severityCount = useMemo(() => { + if (loading || error) { + return undefined; + } + + return { + [RiskSeverity.unknown]: result.kpiRiskScore[RiskSeverity.unknown] ?? 0, + [RiskSeverity.low]: result.kpiRiskScore[RiskSeverity.low] ?? 0, + [RiskSeverity.moderate]: result.kpiRiskScore[RiskSeverity.moderate] ?? 0, + [RiskSeverity.high]: result.kpiRiskScore[RiskSeverity.high] ?? 0, + [RiskSeverity.critical]: result.kpiRiskScore[RiskSeverity.critical] ?? 0, + }; + }, [result, loading, error]); + + return { error, severityCount, loading, isModuleDisabled, refetch, inspect }; }; diff --git a/x-pack/plugins/security_solution/public/risk_score/containers/kpi/translations.ts b/x-pack/plugins/security_solution/public/risk_score/containers/kpi/translations.ts new file mode 100644 index 0000000000000..83b402220f3d4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/risk_score/containers/kpi/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const FAIL_RISK_SCORE = i18n.translate( + 'xpack.securitySolution.riskScore.kpi.failSearchDescription', + { + defaultMessage: `Failed to run search on risk score`, + } +); diff --git a/x-pack/plugins/security_solution/public/threat_intelligence/links.ts b/x-pack/plugins/security_solution/public/threat_intelligence/links.ts index 5b59c0a50799f..c443b74690411 100644 --- a/x-pack/plugins/security_solution/public/threat_intelligence/links.ts +++ b/x-pack/plugins/security_solution/public/threat_intelligence/links.ts @@ -17,7 +17,6 @@ import type { LinkItem } from '../common/links'; */ export const indicatorsLinks: LinkItem = { ...getSecuritySolutionLink('indicators'), - experimentalKey: 'threatIntelligenceEnabled', globalNavPosition: 7, capabilities: [`${SERVER_APP_ID}.show`], }; diff --git a/x-pack/plugins/security_solution/public/threat_intelligence/routes.tsx b/x-pack/plugins/security_solution/public/threat_intelligence/routes.tsx index ab197f60236c6..774d5ea06a350 100644 --- a/x-pack/plugins/security_solution/public/threat_intelligence/routes.tsx +++ b/x-pack/plugins/security_solution/public/threat_intelligence/routes.tsx @@ -6,7 +6,6 @@ */ import React, { memo } from 'react'; -import { Redirect } from 'react-router-dom'; import { TrackApplicationView } from '@kbn/usage-collection-plugin/public'; import type { SecuritySolutionPluginContext } from '@kbn/threat-intelligence-plugin/public'; import { THREAT_INTELLIGENCE_BASE_PATH } from '@kbn/threat-intelligence-plugin/public'; @@ -17,7 +16,6 @@ import { getStore } from '../common/store'; import { useKibana } from '../common/lib/kibana'; import { FiltersGlobal } from '../common/components/filters_global'; import { SpyRoute } from '../common/utils/route/spy_routes'; -import { useIsExperimentalFeatureEnabled } from '../common/hooks/use_experimental_features'; import { licenseService } from '../common/hooks/use_license'; import { SecurityPageName } from '../app/types'; import type { SecuritySubPluginRoutes } from '../app/types'; @@ -30,11 +28,6 @@ const ThreatIntelligence = memo(() => { const sourcererDataView = useSourcererDataView(); - const enabled = useIsExperimentalFeatureEnabled('threatIntelligenceEnabled'); - if (!enabled) { - return ; - } - const securitySolutionStore = getStore() as Store; const securitySolutionContext: SecuritySolutionPluginContext = { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/actions/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/actions/index.test.tsx index 004850ede7d88..7bc64b9900640 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/actions/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/actions/index.test.tsx @@ -7,12 +7,13 @@ import { mount } from 'enzyme'; import React from 'react'; - +import { TimelineId } from '../../../../../../common/types/timeline'; import { TestProviders, mockTimelineModel, mockTimelineData } from '../../../../../common/mock'; import { Actions, isAlert } from '.'; import { useIsExperimentalFeatureEnabled } from '../../../../../common/hooks/use_experimental_features'; import { mockCasesContract } from '@kbn/cases-plugin/public/mocks'; import { useShallowEqualSelector } from '../../../../../common/hooks/use_selector'; +import { licenseService } from '../../../../../common/hooks/use_license'; jest.mock('../../../../../detections/components/user_info', () => ({ useUserData: jest.fn().mockReturnValue([{ canUserCRUD: true, hasIndexWrite: true }]), @@ -63,6 +64,19 @@ jest.mock('../../../../../common/lib/kibana', () => { }; }); +jest.mock('../../../../../common/hooks/use_license', () => { + const licenseServiceInstance = { + isPlatinumPlus: jest.fn(), + isEnterprise: jest.fn(() => false), + }; + return { + licenseService: licenseServiceInstance, + useLicense: () => { + return licenseServiceInstance; + }, + }; +}); + const defaultProps = { ariaRowindex: 2, checked: false, @@ -122,6 +136,7 @@ describe('Actions', () => { expect(wrapper.find('[data-test-subj="select-event"]').exists()).toBe(false); }); + describe('Alert context menu enabled?', () => { test('it disables for eventType=raw', () => { const wrapper = mount( @@ -225,6 +240,65 @@ describe('Actions', () => { expect(wrapper.find('[data-test-subj="view-in-analyzer"]').exists()).toBe(false); }); + + test('it should not show session view button on action tabs for basic users', () => { + const ecsData = { + ...mockTimelineData[0].ecs, + event: { kind: ['alert'] }, + agent: { type: ['endpoint'] }, + process: { entry_leader: { entity_id: ['test_id'] } }, + }; + + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="session-view-button"]').exists()).toEqual(false); + }); + + test('it should show session view button on action tabs when user access the session viewer via K8S dashboard', () => { + const ecsData = { + ...mockTimelineData[0].ecs, + event: { kind: ['alert'] }, + agent: { type: ['endpoint'] }, + process: { entry_leader: { entity_id: ['test_id'] } }, + }; + + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="session-view-button"]').exists()).toEqual(true); + }); + + test('it should show session view button on action tabs for enterprise users', () => { + const licenseServiceMock = licenseService as jest.Mocked; + + licenseServiceMock.isEnterprise.mockReturnValue(true); + + const ecsData = { + ...mockTimelineData[0].ecs, + event: { kind: ['alert'] }, + agent: { type: ['endpoint'] }, + process: { entry_leader: { entity_id: ['test_id'] } }, + }; + + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="session-view-button"]').exists()).toEqual(true); + }); }); describe('isAlert', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/__snapshots__/index.test.tsx.snap index 5b0757ee775f7..3205a30d35c04 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/__snapshots__/index.test.tsx.snap @@ -305,6 +305,7 @@ In other use cases the message field can be used to concatenate different values } kqlMode="search" kqlQueryExpression=" " + kqlQueryLanguage="kuery" onEventClosed={[MockFunction]} renderCellValue={[Function]} rowRenderers={ diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.test.tsx index b610adbe6da50..cc48a58717eee 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.test.tsx @@ -137,6 +137,7 @@ describe('Timeline', () => { itemsPerPageOptions: [5, 10, 20], kqlMode: 'search' as QueryTabContentComponentProps['kqlMode'], kqlQueryExpression: ' ', + kqlQueryLanguage: 'kuery', onEventClosed: jest.fn(), renderCellValue: DefaultCellRenderer, rowRenderers: defaultRowRenderers, diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.tsx index c38304d798418..414604109e580 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_tab_content/index.tsx @@ -179,6 +179,7 @@ export const QueryTabContentComponent: React.FC = ({ itemsPerPageOptions, kqlMode, kqlQueryExpression, + kqlQueryLanguage, onEventClosed, renderCellValue, rowRenderers, @@ -223,8 +224,8 @@ export const QueryTabContentComponent: React.FC = ({ query: string; language: KueryFilterQueryKind; } = useMemo( - () => ({ query: kqlQueryExpression.trim(), language: 'kuery' }), - [kqlQueryExpression] + () => ({ query: kqlQueryExpression.trim(), language: kqlQueryLanguage }), + [kqlQueryExpression, kqlQueryLanguage] ); const combinedQueries = combineQueries({ @@ -493,6 +494,11 @@ const makeMapStateToProps = () => { ? ' ' : kqlQueryTimeline?.expression ?? ''; + const kqlQueryLanguage = + isEmpty(dataProviders) && timelineType === 'template' + ? 'kuery' + : kqlQueryTimeline?.kind ?? 'kuery'; + return { activeTab, columns, @@ -506,6 +512,7 @@ const makeMapStateToProps = () => { itemsPerPageOptions, kqlMode, kqlQueryExpression, + kqlQueryLanguage, showCallOutUnauthorizedMsg: getShowCallOutUnauthorizedMsg(state), show, showExpandedDetails: 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 42a7460a129db..e68530e4579cc 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 @@ -78,6 +78,7 @@ describe('epicLocalStorage', () => { itemsPerPageOptions: [5, 10, 20], kqlMode: 'search' as QueryTabContentComponentProps['kqlMode'], kqlQueryExpression: '', + kqlQueryLanguage: 'kuery', onEventClosed: jest.fn(), renderCellValue: DefaultCellRenderer, rowRenderers: defaultRowRenderers, diff --git a/x-pack/plugins/security_solution/public/users/components/kpi_users/index.tsx b/x-pack/plugins/security_solution/public/users/components/kpi_users/index.tsx index 43933340fac7f..831ca2bdc76f6 100644 --- a/x-pack/plugins/security_solution/public/users/components/kpi_users/index.tsx +++ b/x-pack/plugins/security_solution/public/users/components/kpi_users/index.tsx @@ -12,19 +12,25 @@ import type { UsersKpiProps } from './types'; import { UsersKpiAuthentications } from './authentications'; import { TotalUsersKpi } from './total_users'; -import { useUserRiskScore } from '../../../risk_score/containers'; import { CallOutSwitcher } from '../../../common/components/callouts'; import * as i18n from './translations'; import { RiskScoreDocLink } from '../../../common/components/risk_score/risk_score_onboarding/risk_score_doc_link'; -import { RiskScoreEntity } from '../../../../common/search_strategy'; +import { getUserRiskIndex, RiskQueries, RiskScoreEntity } from '../../../../common/search_strategy'; +import { useSpaceId } from '../../../common/hooks/use_space_id'; +import { useRiskScoreFeatureStatus } from '../../../risk_score/containers/feature_status'; export const UsersKpiComponent = React.memo( ({ filterQuery, from, indexNames, to, setQuery, skip, updateDateRange }) => { - const [loading, { isLicenseValid, isModuleEnabled }] = useUserRiskScore(); + const spaceId = useSpaceId(); + const defaultIndex = spaceId ? getUserRiskIndex(spaceId) : undefined; + const { isEnabled, isLicenseValid, isLoading } = useRiskScoreFeatureStatus( + RiskQueries.usersRiskScore, + defaultIndex + ); return ( <> - {isLicenseValid && !isModuleEnabled && !loading && ( + {isLicenseValid && !isEnabled && !isLoading && ( <> ( <> {i18n.LEARN_MORE}{' '} diff --git a/x-pack/plugins/security_solution/public/users/components/user_risk_information/index.tsx b/x-pack/plugins/security_solution/public/users/components/user_risk_information/index.tsx index b759e8751e7e7..4004299b7e450 100644 --- a/x-pack/plugins/security_solution/public/users/components/user_risk_information/index.tsx +++ b/x-pack/plugins/security_solution/public/users/components/user_risk_information/index.tsx @@ -108,7 +108,6 @@ const UserRiskInformationFlyout = ({ handleOnClose }: { handleOnClose: () => voi values={{ UserRiskScoreDocumentationLink: ( ; } - if (isDeprecated) { + if (isDeprecated && !loading) { return ( ; + return ; } return ( @@ -110,7 +110,7 @@ export const UserRiskScoreQueryTabBody = ({ refetch={refetch} setQuery={setQuery} setQuerySkip={setQuerySkip} - severityCount={severityCount} + severityCount={severityCount ?? EMPTY_SEVERITY_COUNT} totalCount={totalCount} type={type} /> diff --git a/x-pack/plugins/security_solution/public/users/pages/navigation/user_risk_tab_body.tsx b/x-pack/plugins/security_solution/public/users/pages/navigation/user_risk_tab_body.tsx index d8123148480c6..fed651759df7c 100644 --- a/x-pack/plugins/security_solution/public/users/pages/navigation/user_risk_tab_body.tsx +++ b/x-pack/plugins/security_solution/public/users/pages/navigation/user_risk_tab_body.tsx @@ -94,7 +94,7 @@ const UserRiskTabBodyComponent: React.FC< return ; } - if (isDeprecated) { + if (isDeprecated && !loading) { return ( ; + return ; } const lastUsertRiskItem: UserRiskScore | null = diff --git a/x-pack/plugins/security_solution/server/endpoint/endpoint_app_context_services.ts b/x-pack/plugins/security_solution/server/endpoint/endpoint_app_context_services.ts index 59deaae59f450..06d54a4353958 100644 --- a/x-pack/plugins/security_solution/server/endpoint/endpoint_app_context_services.ts +++ b/x-pack/plugins/security_solution/server/endpoint/endpoint_app_context_services.ts @@ -42,6 +42,7 @@ import { registerListsPluginEndpointExtensionPoints } from '../lists_integration import type { EndpointAuthz } from '../../common/endpoint/types/authz'; import { calculateEndpointAuthz } from '../../common/endpoint/service/authz'; import type { FeatureUsageService } from './services/feature_usage/service'; +import type { ExperimentalFeatures } from '../../common/experimental_features'; export interface EndpointAppContextServiceSetupContract { securitySolutionRequestContextFactory: IRequestContextFactory; @@ -67,6 +68,7 @@ export type EndpointAppContextServiceStartContract = Partial< exceptionListsClient: ExceptionListClient | undefined; cases: CasesPluginStartContract | undefined; featureUsageService: FeatureUsageService; + experimentalFeatures: ExperimentalFeatures; }; /** @@ -161,8 +163,14 @@ export class EndpointAppContextService { public async getEndpointAuthz(request: KibanaRequest): Promise { const fleetAuthz = await this.getFleetAuthzService().fromRequest(request); const userRoles = this.startDependencies?.security.authc.getCurrentUser(request)?.roles ?? []; - - return calculateEndpointAuthz(this.getLicenseService(), fleetAuthz, userRoles); + const isEndpointRbacEnabled = this.experimentalFeatures.endpointRbacEnabled; + + return calculateEndpointAuthz( + this.getLicenseService(), + fleetAuthz, + userRoles, + isEndpointRbacEnabled + ); } public getEndpointMetadataService(): EndpointMetadataService { @@ -222,4 +230,12 @@ export class EndpointAppContextService { } return this.startDependencies.featureUsageService; } + + public get experimentalFeatures(): ExperimentalFeatures { + if (this.startDependencies == null) { + throw new EndpointAppContentServicesNotStartedError(); + } + + return this.startDependencies.experimentalFeatures; + } } diff --git a/x-pack/plugins/security_solution/server/endpoint/mocks.ts b/x-pack/plugins/security_solution/server/endpoint/mocks.ts index 8b9623b51b24c..50785f9c29bf9 100644 --- a/x-pack/plugins/security_solution/server/endpoint/mocks.ts +++ b/x-pack/plugins/security_solution/server/endpoint/mocks.ts @@ -158,6 +158,7 @@ export const createMockEndpointAppContextServiceStartContract = getCasesClientWithRequest: jest.fn(async () => casesClientMock), }, featureUsageService: createFeatureUsageServiceMock(), + experimentalFeatures: createMockConfig().experimentalFeatures, }; }; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/actions/list_handler.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/actions/list_handler.test.ts new file mode 100644 index 0000000000000..51326c8adbd12 --- /dev/null +++ b/x-pack/plugins/security_solution/server/endpoint/routes/actions/list_handler.test.ts @@ -0,0 +1,169 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import type { KibanaResponseFactory, RequestHandler, RouteConfig } from '@kbn/core/server'; +import { + coreMock, + elasticsearchServiceMock, + httpServerMock, + httpServiceMock, + loggingSystemMock, + savedObjectsClientMock, +} from '@kbn/core/server/mocks'; +import type { EndpointActionListRequestQuery } from '../../../../common/endpoint/schema/actions'; +import { ENDPOINTS_ACTION_LIST_ROUTE } from '../../../../common/endpoint/constants'; +import { parseExperimentalConfigValue } from '../../../../common/experimental_features'; +import { createMockConfig } from '../../../lib/detection_engine/routes/__mocks__'; +import { EndpointAppContextService } from '../../endpoint_app_context_services'; +import { + createMockEndpointAppContextServiceSetupContract, + createMockEndpointAppContextServiceStartContract, + createRouteHandlerContext, +} from '../../mocks'; +import { registerActionListRoutes } from './list'; +import type { SecuritySolutionRequestHandlerContext } from '../../../types'; +import { doesLogsEndpointActionsIndexExist } from '../../utils'; +import { getActionList, getActionListByStatus } from '../../services'; + +jest.mock('../../utils'); +const mockDoesLogsEndpointActionsIndexExist = doesLogsEndpointActionsIndexExist as jest.Mock; + +jest.mock('../../services'); +const mockGetActionList = getActionList as jest.Mock; +const mockGetActionListByStatus = getActionListByStatus as jest.Mock; + +describe(' Action List Handler', () => { + let endpointAppContextService: EndpointAppContextService; + let mockResponse: jest.Mocked; + + let actionListHandler: ( + query?: EndpointActionListRequestQuery + ) => Promise>; + + beforeEach(() => { + const esClientMock = elasticsearchServiceMock.createScopedClusterClient(); + const routerMock = httpServiceMock.createRouter(); + endpointAppContextService = new EndpointAppContextService(); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start(createMockEndpointAppContextServiceStartContract()); + mockDoesLogsEndpointActionsIndexExist.mockResolvedValue(true); + + registerActionListRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + }); + + actionListHandler = async ( + query?: EndpointActionListRequestQuery + ): Promise> => { + const req = httpServerMock.createKibanaRequest({ + query, + }); + mockResponse = httpServerMock.createResponseFactory(); + const [, routeHandler]: [ + RouteConfig, + RequestHandler< + unknown, + EndpointActionListRequestQuery, + unknown, + SecuritySolutionRequestHandlerContext + > + ] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(ENDPOINTS_ACTION_LIST_ROUTE) + )!; + await routeHandler( + coreMock.createCustomRequestHandlerContext( + createRouteHandlerContext(esClientMock, savedObjectsClientMock.create()) + ) as SecuritySolutionRequestHandlerContext, + req, + mockResponse + ); + + return mockResponse; + }; + }); + + afterEach(() => { + endpointAppContextService.stop(); + }); + + describe('Internals', () => { + it('should return `notFound` when actions index does not exist', async () => { + mockDoesLogsEndpointActionsIndexExist.mockResolvedValue(false); + await actionListHandler({ pageSize: 10, page: 1 }); + expect(mockResponse.notFound).toHaveBeenCalledWith({ + body: 'index_not_found_exception', + }); + }); + + it('should return `ok` when actions index exists', async () => { + await actionListHandler({ pageSize: 10, page: 1 }); + expect(mockResponse.ok).toHaveBeenCalled(); + }); + + it('should call `getActionListByStatus` when statuses filter values are provided', async () => { + await actionListHandler({ pageSize: 10, page: 1, statuses: ['failed', 'pending'] }); + expect(mockGetActionListByStatus).toBeCalledWith( + expect.objectContaining({ statuses: ['failed', 'pending'] }) + ); + }); + + it('should correctly format the request when calling `getActionListByStatus`', async () => { + await actionListHandler({ + agentIds: 'agentX', + commands: 'running-processes', + statuses: 'failed', + userIds: 'userX', + }); + expect(mockGetActionListByStatus).toBeCalledWith( + expect.objectContaining({ + elasticAgentIds: ['agentX'], + commands: ['running-processes'], + statuses: ['failed'], + userIds: ['userX'], + }) + ); + }); + + it('should call `getActionList` when statuses filter values are not provided', async () => { + await actionListHandler({ + pageSize: 10, + page: 1, + commands: ['isolate', 'kill-process'], + userIds: ['userX', 'userY'], + }); + expect(mockGetActionList).toBeCalledWith( + expect.objectContaining({ + commands: ['isolate', 'kill-process'], + userIds: ['userX', 'userY'], + }) + ); + }); + + it('should correctly format the request when calling `getActionList`', async () => { + await actionListHandler({ + page: 1, + pageSize: 10, + agentIds: 'agentX', + commands: 'isolate', + userIds: 'userX', + }); + + expect(mockGetActionList).toHaveBeenCalledWith( + expect.objectContaining({ + commands: ['isolate'], + elasticAgentIds: ['agentX'], + userIds: ['userX'], + }) + ); + }); + }); +}); 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 88d0617c18382..d03117225279a 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 @@ -285,9 +285,7 @@ describe('test endpoint routes', () => { bool: { must_not: { bool: { - should: [ - { match: { 'united.agent.upgrade_status': 'completed' } }, - ], + should: [{ exists: { field: 'united.agent.upgraded_at' } }], minimum_should_match: 1, }, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.fixtures.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.fixtures.ts index edc5d681b138e..fb01bd994f0d9 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.fixtures.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.fixtures.ts @@ -71,11 +71,7 @@ export const expectedCompleteUnitedIndexQuery = { must_not: { bool: { should: [ - { - match: { - 'united.agent.upgrade_status': 'completed', - }, - }, + { exists: { field: 'united.agent.upgraded_at' } }, ], minimum_should_match: 1, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.test.ts index 875f3927ee34c..6a7febe393db3 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.test.ts @@ -93,7 +93,7 @@ describe('test filtering endpoint hosts by agent status', () => { const status = ['healthy']; const kuery = buildStatusesKuery(status); expect(kuery).toMatchInlineSnapshot( - `"(united.agent.last_checkin:* AND not ((united.agent.last_checkin < now-300s) or ((((united.agent.upgrade_started_at:*) and not (united.agent.upgrade_status:completed)) or (not (united.agent.last_checkin:*)) or (united.agent.unenrollment_started_at:*) or (not united.agent.policy_revision_idx:*)) AND not ((united.agent.last_checkin < now-300s) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*))))) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*)))))"` + `"(united.agent.last_checkin:* AND not ((united.agent.last_checkin < now-300s) or ((((united.agent.upgrade_started_at:*) and not (united.agent.upgraded_at:*)) or (not (united.agent.last_checkin:*)) or (united.agent.unenrollment_started_at:*) or (not united.agent.policy_revision_idx:*)) AND not ((united.agent.last_checkin < now-300s) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*))))) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*)))))"` ); }); @@ -115,7 +115,7 @@ describe('test filtering endpoint hosts by agent status', () => { const status = ['updating']; const kuery = buildStatusesKuery(status); expect(kuery).toMatchInlineSnapshot( - `"((((united.agent.upgrade_started_at:*) and not (united.agent.upgrade_status:completed)) or (not (united.agent.last_checkin:*)) or (united.agent.unenrollment_started_at:*) or (not united.agent.policy_revision_idx:*)) AND not ((united.agent.last_checkin < now-300s) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*)))))"` + `"((((united.agent.upgrade_started_at:*) and not (united.agent.upgraded_at:*)) or (not (united.agent.last_checkin:*)) or (united.agent.unenrollment_started_at:*) or (not united.agent.policy_revision_idx:*)) AND not ((united.agent.last_checkin < now-300s) or ((united.agent.last_checkin_status:error or united.agent.last_checkin_status:degraded) AND not ((united.agent.last_checkin < now-300s) or (united.agent.unenrollment_started_at:*)))))"` ); }); diff --git a/x-pack/plugins/security_solution/server/features.ts b/x-pack/plugins/security_solution/server/features.ts index 2a794285b52b7..fc3307a650097 100644 --- a/x-pack/plugins/security_solution/server/features.ts +++ b/x-pack/plugins/security_solution/server/features.ts @@ -11,8 +11,10 @@ import type { KibanaFeatureConfig } from '@kbn/features-plugin/common'; import { DEFAULT_APP_CATEGORIES } from '@kbn/core/server'; import { DATA_VIEW_SAVED_OBJECT_TYPE } from '@kbn/data-views-plugin/common'; import { createUICapabilities } from '@kbn/cases-plugin/common'; + import { APP_ID, CASES_FEATURE_ID, SERVER_APP_ID } from '../common/constants'; import { savedObjectTypes } from './saved_objects'; +import type { ConfigType } from './config'; export const getCasesKibanaFeature = (): KibanaFeatureConfig => { const casesCapabilities = createUICapabilities(); @@ -99,7 +101,10 @@ const CLOUD_POSTURE_APP_ID = 'csp'; // Same as the saved-object type for rules defined by Cloud Security Posture const CLOUD_POSTURE_SAVED_OBJECT_RULE_TYPE = 'csp_rule'; -export const getKibanaPrivilegesFeaturePrivileges = (ruleTypes: string[]): KibanaFeatureConfig => ({ +export const getKibanaPrivilegesFeaturePrivileges = ( + ruleTypes: string[], + experimentalFeatures: ConfigType['experimentalFeatures'] +): KibanaFeatureConfig => ({ id: SERVER_APP_ID, name: i18n.translate('xpack.securitySolution.featureRegistry.linkSecuritySolutionTitle', { defaultMessage: 'Security', @@ -112,7 +117,6 @@ export const getKibanaPrivilegesFeaturePrivileges = (ruleTypes: string[]): Kiban insightsAndAlerting: ['triggersActions'], }, alerting: ruleTypes, - subFeatures: [], privileges: { all: { app: [APP_ID, CLOUD_POSTURE_APP_ID, 'kibana'], @@ -178,4 +182,336 @@ export const getKibanaPrivilegesFeaturePrivileges = (ruleTypes: string[]): Kiban ui: ['show'], }, }, + subFeatures: experimentalFeatures.endpointRbacEnabled + ? [ + { + name: i18n.translate('xpack.securitySolution.featureRegistry.subFeatures.endpointList', { + defaultMessage: 'Endpoint List', + }), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeEndpointList`, `${APP_ID}-readEndpointList`], + id: 'endpoint_list_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeEndpointList', 'readEndpointList'], + }, + { + api: [`${APP_ID}-readEndpointList`], + id: 'endpoint_list_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readEndpointList'], + }, + ], + }, + ], + }, + { + name: i18n.translate( + 'xpack.securitySolution.featureRegistry.subFeatures.trustedApplications', + { + defaultMessage: 'Trusted Applications', + } + ), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeTrustedApplications`, `${APP_ID}-readTrustedApplications`], + id: 'trusted_applications_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeTrustedApplications', 'readTrustedApplications'], + }, + { + api: [`${APP_ID}-readTrustedApplications`], + id: 'trusted_applications_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readTrustedApplications'], + }, + ], + }, + ], + }, + { + name: i18n.translate( + 'xpack.securitySolution.featureRegistry.subFeatures.hostIsolationExceptions', + { + defaultMessage: 'Host Isolation Exceptions', + } + ), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [ + `${APP_ID}-writeHostIsolationExceptions`, + `${APP_ID}-readHostIsolationExceptions`, + ], + id: 'host_isolation_exceptions_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeHostIsolationExceptions', 'readHostIsolationExceptions'], + }, + { + api: [`${APP_ID}-readHostIsolationExceptions`], + id: 'host_isolation_exceptions_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readHostIsolationExceptions'], + }, + ], + }, + ], + }, + { + name: i18n.translate('xpack.securitySolution.featureRegistry.subFeatures.blockList', { + defaultMessage: 'Blocklist', + }), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeBlocklist`, `${APP_ID}-readBlocklist`], + id: 'blocklist_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeBlocklist', 'readBlocklist'], + }, + { + api: [`${APP_ID}-readBlocklist`], + id: 'blocklist_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readBlocklist'], + }, + ], + }, + ], + }, + { + name: i18n.translate('xpack.securitySolution.featureRegistry.subFeatures.eventFilters', { + defaultMessage: 'Event Filters', + }), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeEventFilters`, `${APP_ID}-readEventFilters`], + id: 'event_filters_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeEventFilters', 'readEventFilters'], + }, + { + api: [`${APP_ID}-readEventFilters`], + id: 'event_filters_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readEventFilters'], + }, + ], + }, + ], + }, + { + name: i18n.translate( + 'xpack.securitySolution.featureRegistry.subFeatures.policyManagement', + { + defaultMessage: 'Policy Management', + } + ), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writePolicyManagement`, `${APP_ID}-readPolicyManagement`], + id: 'policy_management_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writePolicyManagement', 'readPolicyManagement'], + }, + { + api: [`${APP_ID}-readPolicyManagement`], + id: 'policy_management_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readPolicyManagement'], + }, + ], + }, + ], + }, + { + name: i18n.translate( + 'xpack.securitySolution.featureRegistry.subFeatures.actionsLogManagement', + { + defaultMessage: 'Actions Log Management', + } + ), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [ + `${APP_ID}-writeActionsLogManagement`, + `${APP_ID}-readActionsLogManagement`, + ], + id: 'actions_log_management_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeActionsLogManagement', 'readActionsLogManagement'], + }, + { + api: [`${APP_ID}-readActionsLogManagement`], + id: 'actions_log_management_read', + includeIn: 'read', + name: 'Read', + savedObject: { + all: [], + read: [], + }, + ui: ['readActionsLogManagement'], + }, + ], + }, + ], + }, + { + name: i18n.translate('xpack.securitySolution.featureRegistry.subFeatures.hostIsolation', { + defaultMessage: 'Host Isolation', + }), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeHostIsolation`], + id: 'host_isolation_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeHostIsolation'], + }, + ], + }, + ], + }, + { + name: i18n.translate( + 'xpack.securitySolution.featureRegistry.subFeatures.processOperations', + { + defaultMessage: 'Process Operations', + } + ), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeProcessOperations`], + id: 'process_operations_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeProcessOperations'], + }, + ], + }, + ], + }, + { + name: i18n.translate('xpack.securitySolution.featureRegistr.subFeatures.fileOperations', { + defaultMessage: 'File Operations', + }), + privilegeGroups: [ + { + groupType: 'mutually_exclusive', + privileges: [ + { + api: [`${APP_ID}-writeFileOperations`], + id: 'file_operations_all', + includeIn: 'all', + name: 'All', + savedObject: { + all: [], + read: [], + }, + ui: ['writeFileOperations'], + }, + ], + }, + ], + }, + ] + : [], }); diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts index 8ffd33e070d98..a2da989a9c08d 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts @@ -13,11 +13,7 @@ import type { LicenseService } from '../../../common/license/license'; import { isAtLeast } from '../../../common/license/license'; import { ProtectionModes } from '../../../common/endpoint/types'; import type { PolicyConfig } from '../../../common/endpoint/types'; -import type { - AnyPolicyCreateConfig, - PolicyCreateCloudConfig, - PolicyCreateEndpointConfig, -} from '../types'; +import type { AnyPolicyCreateConfig, PolicyCreateEndpointConfig } from '../types'; import { ENDPOINT_CONFIG_PRESET_EDR_ESSENTIAL, ENDPOINT_CONFIG_PRESET_NGAV } from '../constants'; /** @@ -32,7 +28,7 @@ export const createDefaultPolicy = ( : policyConfigFactoryWithoutPaidFeatures(); if (config?.type === 'cloud') { - return getCloudPolicyWithIntegrationConfig(policy, config); + return getCloudPolicyConfig(policy); } return getEndpointPolicyWithIntegrationConfig(policy, config); @@ -95,37 +91,20 @@ const getEndpointPolicyWithIntegrationConfig = ( /** * Retrieve policy for cloud based on the on the cloud integration config */ -const getCloudPolicyWithIntegrationConfig = ( - policy: PolicyConfig, - config: PolicyCreateCloudConfig -): PolicyConfig => { - /** - * Check if the protection is supported, then retrieve Behavior Protection mode based on cloud settings - */ - const getBehaviorProtectionMode = () => { - if (!policy.linux.behavior_protection.supported) { - return ProtectionModes.off; - } - - return config.cloudConfig.preventions.behavior_protection - ? ProtectionModes.prevent - : ProtectionModes.off; - }; - +const getCloudPolicyConfig = (policy: PolicyConfig): PolicyConfig => { + // Disabling all protections, since it's not yet supported on Cloud integrations const protections = { - // Disabling memory_protection, since it's not supported on Cloud integrations memory_protection: { supported: false, mode: ProtectionModes.off, }, malware: { ...policy.linux.malware, - // Disabling Malware protection, since it's not supported on Cloud integrations due to performance reasons mode: ProtectionModes.off, }, behavior_protection: { ...policy.linux.behavior_protection, - mode: getBehaviorProtectionMode(), + mode: ProtectionModes.off, }, }; diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/validate_integration_config.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/validate_integration_config.ts index 76bd3e8af93fb..bc58358565817 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/validate_integration_config.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/validate_integration_config.ts @@ -46,18 +46,6 @@ const validateEndpointIntegrationConfig = ( } }; const validateCloudIntegrationConfig = (config: PolicyCreateCloudConfig, logger: Logger): void => { - if (!config?.cloudConfig?.preventions) { - logger.warn( - 'missing cloudConfig preventions: {preventions : behavior_protection: true / false}' - ); - throwError('invalid value for cloudConfig: missing preventions '); - } - if (typeof config.cloudConfig.preventions.behavior_protection !== 'boolean') { - logger.warn( - `invalid value for cloudConfig preventions behavior_protection: ${config.cloudConfig.preventions.behavior_protection}` - ); - throwError('invalid value for cloudConfig preventions behavior_protection'); - } if (!config?.eventFilters) { logger.warn( `eventFilters is required for cloud integration: {eventFilters : nonInteractiveSession: true / false}` diff --git a/x-pack/plugins/security_solution/server/fleet_integration/types.ts b/x-pack/plugins/security_solution/server/fleet_integration/types.ts index 2d012832f1ae2..0c7a7c17951e6 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/types.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/types.ts @@ -18,12 +18,6 @@ export interface PolicyCreateEventFilters { export interface PolicyCreateCloudConfig { type: 'cloud'; - cloudConfig: { - preventions: { - malware: boolean; - behavior_protection: boolean; - }; - }; eventFilters?: PolicyCreateEventFilters; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/preview_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/preview_rules_route.ts index a147118b782d5..15b6ffe47d349 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/preview_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/preview_rules_route.ts @@ -182,7 +182,6 @@ export const previewRulesRoute = async ( | 'getState' | 'replaceState' | 'scheduleActions' - | 'scheduleActionsWithSubGroup' | 'setContext' | 'getContext' | 'hasContext' diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client.ts index 4116848b1ffcf..3c712847851fd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client.ts @@ -222,6 +222,7 @@ const normalizeStatusChangeArgs = (args: StatusChangeArgs): NormalizedStatusChan ? { total_search_duration_ms: normalizeDurations(metrics.searchDurations), total_indexing_duration_ms: normalizeDurations(metrics.indexingDurations), + total_enrichment_duration_ms: normalizeDurations(metrics.enrichmentDurations), execution_gap_duration_s: normalizeGap(metrics.executionGap), } : undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client_interface.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client_interface.ts index 22392e699fcea..5e48a43e949c3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client_interface.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/client_for_executors/client_interface.ts @@ -115,5 +115,6 @@ export interface StatusChangeArgs { export interface MetricsArgs { searchDurations?: string[]; indexingDurations?: string[]; + enrichmentDurations?: string[]; executionGap?: Duration; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/execution_saved_object/saved_objects_type.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/execution_saved_object/saved_objects_type.ts index ac3b28e87e0d9..1e0a2e74cadcd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/execution_saved_object/saved_objects_type.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/execution_saved_object/saved_objects_type.ts @@ -58,6 +58,9 @@ const ruleExecutionMappings: SavedObjectsType['mappings'] = { total_indexing_duration_ms: { type: 'long', }, + total_enrichment_duration_ms: { + type: 'long', + }, execution_gap_duration_s: { type: 'long', }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts index ae3f310d841c3..05813ed1ee29c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts @@ -343,6 +343,7 @@ export const createSecurityRuleTypeWrapper: CreateSecurityRuleTypeWrapper = const warningMessages = result.warningMessages.concat(runResult.warningMessages); result = { bulkCreateTimes: result.bulkCreateTimes.concat(runResult.bulkCreateTimes), + enrichmentTimes: result.enrichmentTimes.concat(runResult.enrichmentTimes), createdSignals, createdSignalsCount: createdSignals.length, errors: result.errors.concat(runResult.errors), @@ -358,6 +359,7 @@ export const createSecurityRuleTypeWrapper: CreateSecurityRuleTypeWrapper = } else { result = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignals: [], createdSignalsCount: 0, errors: [], @@ -434,6 +436,7 @@ export const createSecurityRuleTypeWrapper: CreateSecurityRuleTypeWrapper = metrics: { searchDurations: result.searchAfterTimes, indexingDurations: result.bulkCreateTimes, + enrichmentDurations: result.enrichmentTimes, }, }); } @@ -452,6 +455,7 @@ export const createSecurityRuleTypeWrapper: CreateSecurityRuleTypeWrapper = metrics: { searchDurations: result.searchAfterTimes, indexingDurations: result.bulkCreateTimes, + enrichmentDurations: result.enrichmentTimes, }, }); } @@ -464,6 +468,7 @@ export const createSecurityRuleTypeWrapper: CreateSecurityRuleTypeWrapper = metrics: { searchDurations: result.searchAfterTimes, indexingDurations: result.bulkCreateTimes, + enrichmentDurations: result.enrichmentTimes, }, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts index 81f15364ff128..95bc32571f6ea 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts @@ -21,6 +21,7 @@ import type { export interface GenericBulkCreateResponse { success: boolean; bulkCreateDuration: string; + enrichmentDuration: string; createdItemsCount: number; createdItems: Array & { _id: string; _index: string }>; errors: string[]; @@ -45,6 +46,7 @@ export const bulkCreateFactory = return { errors: [], success: true, + enrichmentDuration: '0', bulkCreateDuration: '0', createdItemsCount: 0, createdItems: [], @@ -54,6 +56,24 @@ export const bulkCreateFactory = const start = performance.now(); + let enrichmentsTimeStart = 0; + let enrichmentsTimeFinish = 0; + let enrichAlertsWrapper: typeof enrichAlerts; + if (enrichAlerts) { + enrichAlertsWrapper = async (alerts, params) => { + enrichmentsTimeStart = performance.now(); + try { + const enrichedAlerts = await enrichAlerts(alerts, params); + return enrichedAlerts; + } catch (error) { + ruleExecutionLogger.error(`Enrichments failed ${error}`); + throw error; + } finally { + enrichmentsTimeFinish = performance.now(); + } + }; + } + const { createdAlerts, errors, alertsWereTruncated } = await alertWithPersistence( wrappedDocs.map((doc) => ({ _id: doc._id, @@ -62,7 +82,7 @@ export const bulkCreateFactory = })), refreshForBulkCreate, maxAlerts, - enrichAlerts + enrichAlertsWrapper ); const end = performance.now(); @@ -78,6 +98,7 @@ export const bulkCreateFactory = return { errors: Object.keys(errors), success: false, + enrichmentDuration: makeFloatString(enrichmentsTimeFinish - enrichmentsTimeStart), bulkCreateDuration: makeFloatString(end - start), createdItemsCount: createdAlerts.length, createdItems: createdAlerts, @@ -88,6 +109,7 @@ export const bulkCreateFactory = errors: [], success: true, bulkCreateDuration: makeFloatString(end - start), + enrichmentDuration: makeFloatString(enrichmentsTimeFinish - enrichmentsTimeStart), createdItemsCount: createdAlerts.length, createdItems: createdAlerts, alertsWereTruncated, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/create_new_terms_alert_type.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/create_new_terms_alert_type.ts index d1fa77857c1f7..2e22d3a5798bf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/create_new_terms_alert_type.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/create_new_terms_alert_type.ts @@ -32,7 +32,7 @@ import { parseDateString, validateHistoryWindowStart } from './utils'; import { addToSearchAfterReturn, createSearchAfterReturnType, - logUnprocessedExceptionsWarnings, + getUnprocessedExceptionsWarnings, } from '../../signals/utils'; import { createEnrichEventsFunction } from '../../signals/enrichments'; @@ -114,8 +114,6 @@ export const createNewTermsAlertType = ( from: params.from, }); - logUnprocessedExceptionsWarnings(unprocessedExceptions, ruleExecutionLogger); - const esFilter = await getFilter({ filters: params.filters, index: inputIndex, @@ -137,6 +135,11 @@ export const createNewTermsAlertType = ( const result = createSearchAfterReturnType(); + const exceptionsWarning = getUnprocessedExceptionsWarnings(unprocessedExceptions); + if (exceptionsWarning) { + result.warningMessages.push(exceptionsWarning); + } + // There are 2 conditions that mean we're finished: either there were still too many alerts to create // after deduplication and the array of alerts was truncated before being submitted to ES, or there were // exactly enough new alerts to hit maxSignals without truncating the array of alerts. We check both because diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts index 403d6542f4f0c..e1af3077ec3e3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts @@ -42,6 +42,7 @@ import type { IRuleExecutionLogForExecutors, IRuleExecutionLogService } from '.. export interface SecurityAlertTypeReturnValue { bulkCreateTimes: string[]; + enrichmentTimes: string[]; createdSignalsCount: number; createdSignals: unknown[]; errors: string[]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/utils/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/utils/index.ts index 5d2dcd4a4b3d2..8f23da386f5c7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/utils/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/utils/index.ts @@ -10,6 +10,7 @@ import type { SecurityAlertTypeReturnValue } from '../types'; export const createResultObject = (state: TState) => { const result: SecurityAlertTypeReturnValue = { + enrichmentTimes: [], bulkCreateTimes: [], createdSignalsCount: 0, createdSignals: [], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/action_to_rules_client_operation.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/action_to_rules_client_operation.ts index c395798cdf618..550f624ed9351 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/action_to_rules_client_operation.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/action_to_rules_client_operation.ts @@ -93,8 +93,6 @@ export const bulkEditActionToRulesClientOperation = ( { field: 'schedule', operation: 'set', - // We need to pass a pure Interval object - // i.e. get rid of the meta property value: { interval: action.value.interval, }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/rule_params_modifier.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/rule_params_modifier.test.ts index bfbad8ac2ece3..5c194cc6c4614 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/rule_params_modifier.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_actions/rule_params_modifier.test.ts @@ -353,7 +353,7 @@ describe('ruleParamsModifier', () => { }); describe('schedule', () => { - test('should set timeline', () => { + test('should set schedule', () => { const INTERVAL_IN_MINUTES = 5; const LOOKBACK_IN_MINUTES = 1; const FROM_IN_SECONDS = (INTERVAL_IN_MINUTES + LOOKBACK_IN_MINUTES) * 60; @@ -367,8 +367,8 @@ describe('ruleParamsModifier', () => { }, ]); - // @ts-expect-error - expect(editedRuleParams.interval).toBeUndefined(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((editedRuleParams as any).interval).toBeUndefined(); expect(editedRuleParams.meta).toStrictEqual({ from: '1m', }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_edit_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_edit_rules.ts index 273d6697437bd..75c7db48333c3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_edit_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/bulk_edit_rules.ts @@ -5,27 +5,27 @@ * 2.0. */ +import type { BulkEditError, RulesClient } from '@kbn/alerting-plugin/server'; import pMap from 'p-map'; -import type { RulesClient, BulkEditError } from '@kbn/alerting-plugin/server'; import type { BulkActionEditPayload, BulkActionEditPayloadRuleActions, } from '../../../../common/detection_engine/schemas/request/perform_bulk_action_schema'; +import { BulkActionEditType } from '../../../../common/detection_engine/schemas/request/perform_bulk_action_schema'; import { enrichFilterWithRuleTypeMapping } from './enrich_filter_with_rule_type_mappings'; import type { MlAuthz } from '../../machine_learning/authz'; import { ruleParamsModifier } from './bulk_actions/rule_params_modifier'; import { splitBulkEditActions } from './bulk_actions/split_bulk_edit_actions'; import { validateBulkEditRule } from './bulk_actions/validations'; import { bulkEditActionToRulesClientOperation } from './bulk_actions/action_to_rules_client_operation'; + +import type { RuleAlertType } from './types'; import { - NOTIFICATION_THROTTLE_NO_ACTIONS, MAX_RULES_TO_UPDATE_IN_PARALLEL, + NOTIFICATION_THROTTLE_NO_ACTIONS, } from '../../../../common/constants'; -import { BulkActionEditType } from '../../../../common/detection_engine/schemas/request/perform_bulk_action_schema'; import { readRules } from './read_rules'; -import type { RuleAlertType } from './types'; - export interface BulkEditRulesArguments { rulesClient: RulesClient; actions: BulkActionEditPayload[]; @@ -67,39 +67,30 @@ export const bulkEditRules = async ({ // rulesClient bulkEdit currently doesn't support bulk mute/unmute. // this is a workaround to mitigate this, // until https://github.com/elastic/kibana/issues/139084 is resolved - // if rule actions has been applied: - // - we go through each rule - // - mute/unmute if needed, refetch rule - // calling mute for rule needed only when rule was unmuted before and throttle value is NOTIFICATION_THROTTLE_NO_ACTIONS + // if rule actions has been applied, we go through each rule, unmute it if necessary and refetch it // calling unmute needed only if rule was muted and throttle value is not NOTIFICATION_THROTTLE_NO_ACTIONS const ruleActions = attributesActions.filter((rule): rule is BulkActionEditPayloadRuleActions => [BulkActionEditType.set_rule_actions, BulkActionEditType.add_rule_actions].includes(rule.type) ); - // bulk edit actions are applying in a historical order. + // bulk edit actions are applied in historical order. // So, we need to find a rule action that will be applied the last, to be able to check if rule should be muted/unmuted const rulesAction = ruleActions.pop(); if (rulesAction) { - const muteOrUnmuteErrors: BulkEditError[] = []; - const rulesToMuteOrUnmute = await pMap( + const unmuteErrors: BulkEditError[] = []; + const rulesToUnmute = await pMap( result.rules, async (rule) => { try { if (rule.muteAll && rulesAction.value.throttle !== NOTIFICATION_THROTTLE_NO_ACTIONS) { await rulesClient.unmuteAll({ id: rule.id }); return (await readRules({ rulesClient, id: rule.id, ruleId: undefined })) ?? rule; - } else if ( - !rule.muteAll && - rulesAction.value.throttle === NOTIFICATION_THROTTLE_NO_ACTIONS - ) { - await rulesClient.muteAll({ id: rule.id }); - return (await readRules({ rulesClient, id: rule.id, ruleId: undefined })) ?? rule; } return rule; } catch (err) { - muteOrUnmuteErrors.push({ + unmuteErrors.push({ message: err.message, rule: { id: rule.id, @@ -115,8 +106,8 @@ export const bulkEditRules = async ({ return { ...result, - rules: rulesToMuteOrUnmute.filter((rule): rule is RuleAlertType => rule != null), - errors: [...result.errors, ...muteOrUnmuteErrors], + rules: rulesToUnmute.filter((rule): rule is RuleAlertType => rule != null), + errors: [...result.errors, ...unmuteErrors], }; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_email_powershell_exchange_mailbox.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_email_powershell_exchange_mailbox.json index 3a82c828d637c..d891ad96a57c0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_email_powershell_exchange_mailbox.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_email_powershell_exchange_mailbox.json @@ -47,7 +47,8 @@ "Host", "Windows", "Threat Detection", - "Collection" + "Collection", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_audio_capture.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_audio_capture.json index 3721078880a42..2a3519f83bd29 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_audio_capture.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_audio_capture.json @@ -37,7 +37,8 @@ "Host", "Windows", "Threat Detection", - "Collection" + "Collection", + "has_guide" ], "threat": [ { @@ -80,5 +81,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_keylogger.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_keylogger.json index db9abf0b19506..a1d437332842a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_keylogger.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_keylogger.json @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Collection" + "Collection", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_screen_grabber.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_screen_grabber.json index 1b041659b488c..cec0fd82efb05 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_screen_grabber.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_posh_screen_grabber.json @@ -37,7 +37,8 @@ "Host", "Windows", "Threat Detection", - "Collection" + "Collection", + "has_guide" ], "threat": [ { @@ -80,5 +81,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_winrar_encryption.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_winrar_encryption.json index 6aeca04a6d9d7..0c69fba974b39 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_winrar_encryption.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_winrar_encryption.json @@ -53,7 +53,8 @@ "Host", "Windows", "Threat Detection", - "Collection" + "Collection", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json index c437fde5ea4bb..827659f95566f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Network Connection via Certutil", - "note": "## Triage and analysis\n\n### Investigating Network Connection via Certutil\n\nAttackers can abuse `certutil.exe` to download malware, offensive security tools, and certificates from external sources\nin order to take the next steps in a compromised environment.\n\nThis rule looks for network events where `certutil.exe` contacts IP ranges other than the ones specified in\n[IANA IPv4 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml)\n\n#### Possible investigation steps\n\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate if the downloaded file was executed.\n- Determine the context in which `certutil.exe` and the file were run.\n- Retrieve the downloaded file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. If trusted software uses this command and the triage has not identified\nanything suspicious, this alert can be closed as a false positive.\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Network Connection via Certutil\n\nAttackers can abuse `certutil.exe` to download malware, offensive security tools, and certificates from external sources\nin order to take the next steps in a compromised environment.\n\nThis rule looks for network events where `certutil.exe` contacts IP ranges other than the ones specified in\n[IANA IPv4 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml)\n\n#### Possible investigation steps\n\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate if the downloaded file was executed.\n- Determine the context in which `certutil.exe` and the file were run.\n- Retrieve the downloaded file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. If trusted software uses this command and the triage has not identified\nanything suspicious, this alert can be closed as a false positive.\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by process.entity_id\n [process where process.name : \"certutil.exe\" and event.type == \"start\"]\n [network where process.name : \"certutil.exe\" and\n not cidrmatch(destination.ip, \"10.0.0.0/8\", \"127.0.0.0/8\", \"169.254.0.0/16\", \"172.16.0.0/12\", \"192.0.0.0/24\",\n \"192.0.0.0/29\", \"192.0.0.8/32\", \"192.0.0.9/32\", \"192.0.0.10/32\", \"192.0.0.170/32\",\n \"192.0.0.171/32\", \"192.0.2.0/24\", \"192.31.196.0/24\", \"192.52.193.0/24\",\n \"192.168.0.0/16\", \"192.88.99.0/24\", \"224.0.0.0/4\", \"100.64.0.0/10\", \"192.175.48.0/24\",\n \"198.18.0.0/15\", \"198.51.100.0/24\", \"203.0.113.0/24\", \"240.0.0.0/4\", \"::1\",\n \"FE80::/10\", \"FF00::/8\")]\n", "references": [ "https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml", @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -68,5 +69,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_common_webservices.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_common_webservices.json index f528501b0da5a..49562601e3372 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_common_webservices.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_common_webservices.json @@ -10,7 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Connection to Commonly Abused Web Services", - "note": "## Triage and analysis\n\n### Investigating Connection to Commonly Abused Web Services\n\nAdversaries may use an existing, legitimate external Web service as a means for relaying data to/from a compromised\nsystem. Popular websites and social media acting as a mechanism for C2 may give a significant amount of cover due to the\nlikelihood that hosts within a network are already communicating with them prior to a compromise.\n\nThis rule looks for processes outside known legitimate program locations communicating with a list of services that can\nbe abused for exfiltration or command and control.\n\n#### Possible investigation steps\n\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Verify whether the digital signature exists in the executable.\n- Identify the operation type (upload, download, tunneling, etc.).\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule has a high chance to produce false positives because it detects communication with legitimate services. Noisy\nfalse positives can be added as exceptions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Connection to Commonly Abused Web Services\n\nAdversaries may use an existing, legitimate external Web service as a means for relaying data to/from a compromised\nsystem. Popular websites and social media acting as a mechanism for C2 may give a significant amount of cover due to the\nlikelihood that hosts within a network are already communicating with them prior to a compromise.\n\nThis rule looks for processes outside known legitimate program locations communicating with a list of services that can\nbe abused for exfiltration or command and control.\n\n#### Possible investigation steps\n\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Verify whether the digital signature exists in the executable.\n- Identify the operation type (upload, download, tunneling, etc.).\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule has a high chance to produce false positives because it detects communication with legitimate services. Noisy\nfalse positives can be added as exceptions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "network where network.protocol == \"dns\" and\n process.name != null and user.id not in (\"S-1-5-18\", \"S-1-5-19\", \"S-1-5-20\") and\n /* Add new WebSvc domains here */\n dns.question.name :\n (\n \"raw.githubusercontent.*\",\n \"*.pastebin.*\",\n \"*drive.google.*\",\n \"*docs.live.*\",\n \"*api.dropboxapi.*\",\n \"*dropboxusercontent.*\",\n \"*onedrive.*\",\n \"*4shared.*\",\n \"*.file.io\",\n \"*filebin.net\",\n \"*slack-files.com\",\n \"*ghostbin.*\",\n \"*ngrok.*\",\n \"*portmap.*\",\n \"*serveo.net\",\n \"*localtunnel.me\",\n \"*pagekite.me\",\n \"*localxpose.io\",\n \"*notabug.org\",\n \"rawcdn.githack.*\",\n \"paste.nrecom.net\",\n \"zerobin.net\",\n \"controlc.com\",\n \"requestbin.net\",\n \"cdn.discordapp.com\",\n \"discordapp.com\",\n \"discord.com\"\n ) and\n /* Insert noisy false positives here */\n not process.executable :\n (\n \"?:\\\\Program Files\\\\*.exe\",\n \"?:\\\\Program Files (x86)\\\\*.exe\",\n \"?:\\\\Windows\\\\System32\\\\WWAHost.exe\",\n \"?:\\\\Windows\\\\System32\\\\smartscreen.exe\",\n \"?:\\\\Windows\\\\System32\\\\MicrosoftEdgeCP.exe\",\n \"?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender\\\\Platform\\\\*\\\\MsMpEng.exe\",\n \"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Programs\\\\Fiddler\\\\Fiddler.exe\",\n \"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\",\n \"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Microsoft\\\\OneDrive\\\\OneDrive.exe\",\n \"?:\\\\Windows\\\\system32\\\\mobsync.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\mobsync.exe\",\n \"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Discord\\\\app-*\\\\Discord.exe\"\n )\n", "required_fields": [ { @@ -47,7 +47,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -95,5 +96,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_tunneling_nslookup.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_tunneling_nslookup.json index 55eb5c136eb56..89945ae91c6da 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_tunneling_nslookup.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_tunneling_nslookup.json @@ -47,7 +47,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -80,5 +81,5 @@ "value": 15 }, "type": "threshold", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_forwarding_added_registry.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_forwarding_added_registry.json index 20a6904c44bc0..7898871bb9b3a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_forwarding_added_registry.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_forwarding_added_registry.json @@ -33,7 +33,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -54,5 +55,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_tunnel_plink.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_tunnel_plink.json index d7d8d9b394813..a9af94cec09d3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_tunnel_plink.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_tunnel_plink.json @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_desktopimgdownldr.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_desktopimgdownldr.json index a175e4f84ead1..c49f3cd7efefb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_desktopimgdownldr.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_desktopimgdownldr.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote File Download via Desktopimgdownldr Utility", - "note": "## Triage and analysis\n\n### Investigating Remote File Download via Desktopimgdownldr Utility\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nThe `Desktopimgdownldr.exe` utility is used to to configure lockscreen/desktop image, and can be abused with the\n`lockscreenurl` argument to download remote files and tools, this rule looks for this behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Check the reputation of the domain or IP address used to host the downloaded file or if the user downloaded the file\nfrom an internal system.\n- Retrieve the file and determine if it is malicious:\n - Identify the file type.\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unusual but can be done by administrators. Benign true positives (B-TPs) can be added as exceptions\nif necessary.\n- Analysts can dismiss the alert if the downloaded file is a legitimate image.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Remote File Download via Desktopimgdownldr Utility\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nThe `Desktopimgdownldr.exe` utility is used to to configure lockscreen/desktop image, and can be abused with the\n`lockscreenurl` argument to download remote files and tools, this rule looks for this behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Check the reputation of the domain or IP address used to host the downloaded file or if the user downloaded the file\nfrom an internal system.\n- Retrieve the file and determine if it is malicious:\n - Identify the file type.\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unusual but can be done by administrators. Benign true positives (B-TPs) can be added as exceptions\nif necessary.\n- Analysts can dismiss the alert if the downloaded file is a legitimate image.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name : \"desktopimgdownldr.exe\" or process.pe.original_file_name == \"desktopimgdownldr.exe\") and\n process.args : \"/lockscreenurl:http*\"\n", "references": [ "https://labs.sentinelone.com/living-off-windows-land-a-new-native-file-downldr/" @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_mpcmdrun.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_mpcmdrun.json index 2ffafee4416b6..229755609cc38 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_mpcmdrun.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_mpcmdrun.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote File Download via MpCmdRun", - "note": "## Triage and analysis\n\n### Investigating Remote File Download via MpCmdRun\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nThe `MpCmdRun.exe` is a command-line tool part of Windows Defender and is used to manage various Microsoft Windows\nDefender Antivirus settings and perform certain tasks. It can also be abused by attackers to download remote files,\nincluding malware and offensive tooling. This rule looks for the patterns used to perform downloads using the utility.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check the reputation of the domain or IP address used to host the downloaded file.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Remote File Download via MpCmdRun\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nThe `MpCmdRun.exe` is a command-line tool part of Windows Defender and is used to manage various Microsoft Windows\nDefender Antivirus settings and perform certain tasks. It can also be abused by attackers to download remote files,\nincluding malware and offensive tooling. This rule looks for the patterns used to perform downloads using the utility.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check the reputation of the domain or IP address used to host the downloaded file.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name : \"MpCmdRun.exe\" or process.pe.original_file_name == \"MpCmdRun.exe\") and\n process.args : \"-DownloadFile\" and process.args : \"-url\" and process.args : \"-path\"\n", "references": [ "https://twitter.com/mohammadaskar2/status/1301263551638761477", @@ -49,7 +49,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -70,5 +71,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_powershell.json index 1b42352777aef..c6a7c798235d8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_powershell.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote File Download via PowerShell", - "note": "## Triage and analysis\n\n### Investigating Remote File Download via PowerShell\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nPowerShell is one of system administrators' main tools for automation, report routines, and other tasks. This makes it\navailable for use in various environments and creates an attractive way for attackers to execute code and perform\nactions. This rule correlates network and file events to detect downloads of executable and script files performed using\nPowerShell.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check the reputation of the domain or IP address used to host the downloaded file.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Administrators can use PowerShell legitimately to download executable and script files. Analysts can dismiss the alert\nif the Administrator is aware of the activity and the triage has not identified suspicious or malicious files.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Remote File Download via PowerShell\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse signed utilities to drop these files.\n\nPowerShell is one of system administrators' main tools for automation, report routines, and other tasks. This makes it\navailable for use in various environments and creates an attractive way for attackers to execute code and perform\nactions. This rule correlates network and file events to detect downloads of executable and script files performed using\nPowerShell.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check the reputation of the domain or IP address used to host the downloaded file.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Administrators can use PowerShell legitimately to download executable and script files. Analysts can dismiss the alert\nif the Administrator is aware of the activity and the triage has not identified suspicious or malicious files.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by host.id, process.entity_id with maxspan=30s\n [network where process.name : (\"powershell.exe\", \"pwsh.exe\", \"powershell_ise.exe\") and network.protocol == \"dns\" and\n not dns.question.name : (\"localhost\", \"*.microsoft.com\", \"*.azureedge.net\", \"*.powershellgallery.com\", \"*.windowsupdate.com\", \"metadata.google.internal\") and\n not user.domain : \"NT AUTHORITY\"]\n [file where process.name : \"powershell.exe\" and event.type == \"creation\" and file.extension : (\"exe\", \"dll\", \"ps1\", \"bat\") and\n not file.name : \"__PSScriptPolicy*.ps1\"]\n", "required_fields": [ { @@ -69,7 +69,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -111,5 +112,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_scripts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_scripts.json index 35ac4855cdab5..3ab79126bec9f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_scripts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_remote_file_copy_scripts.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote File Download via Script Interpreter", - "note": "## Triage and analysis\n\n### Investigating Remote File Download via Script Interpreter\n\nThe Windows Script Host (WSH) is a Windows automation technology, which is ideal for non-interactive scripting needs,\nsuch as logon scripting, administrative scripting, and machine automation.\n\nAttackers commonly use WSH scripts as their initial access method, acting like droppers for second stage payloads, but\ncan also use them to download tools and utilities needed to accomplish their goals.\n\nThis rule looks for DLLs and executables downloaded using `cscript.exe` or `wscript.exe`.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Retrieve the script file and the executable involved and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n - Manually analyze the script to determine if malicious capabilities are present.\n- Investigate whether the potential malware ran successfully, is active on the host, or was stopped by defenses.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n\n### False positive analysis\n\n- The usage of these script engines by regular users is unlikely. In the case of authorized benign true positives\n(B-TPs), exceptions can be added.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Remote File Download via Script Interpreter\n\nThe Windows Script Host (WSH) is a Windows automation technology, which is ideal for non-interactive scripting needs,\nsuch as logon scripting, administrative scripting, and machine automation.\n\nAttackers commonly use WSH scripts as their initial access method, acting like droppers for second stage payloads, but\ncan also use them to download tools and utilities needed to accomplish their goals.\n\nThis rule looks for DLLs and executables downloaded using `cscript.exe` or `wscript.exe`.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Retrieve the script file and the executable involved and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n - Manually analyze the script to determine if malicious capabilities are present.\n- Investigate whether the potential malware ran successfully, is active on the host, or was stopped by defenses.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n\n### False positive analysis\n\n- The usage of these script engines by regular users is unlikely. In the case of authorized benign true positives\n(B-TPs), exceptions can be added.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by host.id, process.entity_id\n [network where process.name : (\"wscript.exe\", \"cscript.exe\") and network.protocol != \"dns\" and\n network.direction : (\"outgoing\", \"egress\") and network.type == \"ipv4\" and destination.ip != \"127.0.0.1\"\n ]\n [file where event.type == \"creation\" and file.extension : (\"exe\", \"dll\")]\n", "required_fields": [ { @@ -69,7 +69,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -89,5 +90,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sunburst_c2_activity_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sunburst_c2_activity_detected.json index 8a6bf64b5edb7..45c95688fc9b4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sunburst_c2_activity_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sunburst_c2_activity_detected.json @@ -10,7 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "SUNBURST Command and Control Activity", - "note": "## Triage and analysis\n\n### Investigating SUNBURST Command and Control Activity\n\nSUNBURST is a trojanized version of a digitally signed SolarWinds Orion plugin called\nSolarWinds.Orion.Core.BusinessLayer.dll. The plugin contains a backdoor that communicates via HTTP to third-party\nservers. After an initial dormant period of up to two weeks, SUNBURST may retrieve and execute commands that instruct\nthe backdoor to transfer files, execute files, profile the system, reboot the system, and disable system services.\nThe malware's network traffic attempts to blend in with legitimate SolarWinds activity by imitating the Orion\nImprovement Program (OIP) protocol, and the malware stores persistent state data within legitimate plugin configuration files. The\nbackdoor uses multiple obfuscated blocklists to identify processes, services, and drivers associated with forensic and\nanti-virus tools.\n\nMore details on SUNBURST can be found on the [Mandiant Report](https://www.mandiant.com/resources/sunburst-additional-technical-details).\n\nThis rule identifies suspicious network connections that attempt to blend in with legitimate SolarWinds activity\nby imitating the Orion Improvement Program (OIP) protocol behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Retrieve the executable involved:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Investigate whether the potential malware ran successfully, is active on the host, or was stopped by defenses.\n- Investigate the network traffic.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true positive\n(B-TP), as this configuration can put the environment at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Upgrade SolarWinds systems to the latest version to eradicate the chance of reinfection by abusing the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating SUNBURST Command and Control Activity\n\nSUNBURST is a trojanized version of a digitally signed SolarWinds Orion plugin called\nSolarWinds.Orion.Core.BusinessLayer.dll. The plugin contains a backdoor that communicates via HTTP to third-party\nservers. After an initial dormant period of up to two weeks, SUNBURST may retrieve and execute commands that instruct\nthe backdoor to transfer files, execute files, profile the system, reboot the system, and disable system services.\nThe malware's network traffic attempts to blend in with legitimate SolarWinds activity by imitating the Orion\nImprovement Program (OIP) protocol, and the malware stores persistent state data within legitimate plugin configuration files. The\nbackdoor uses multiple obfuscated blocklists to identify processes, services, and drivers associated with forensic and\nanti-virus tools.\n\nMore details on SUNBURST can be found on the [Mandiant Report](https://www.mandiant.com/resources/sunburst-additional-technical-details).\n\nThis rule identifies suspicious network connections that attempt to blend in with legitimate SolarWinds activity\nby imitating the Orion Improvement Program (OIP) protocol behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Retrieve the executable involved:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Investigate whether the potential malware ran successfully, is active on the host, or was stopped by defenses.\n- Investigate the network traffic.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true positive\n(B-TP), as this configuration can put the environment at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Upgrade SolarWinds systems to the latest version to eradicate the chance of reinfection by abusing the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "network where event.type == \"protocol\" and network.protocol == \"http\" and\n process.name : (\"ConfigurationWizard.exe\",\n \"NetFlowService.exe\",\n \"NetflowDatabaseMaintenance.exe\",\n \"SolarWinds.Administration.exe\",\n \"SolarWinds.BusinessLayerHost.exe\",\n \"SolarWinds.BusinessLayerHostx64.exe\",\n \"SolarWinds.Collector.Service.exe\",\n \"SolarwindsDiagnostics.exe\") and\n (\n (\n (http.request.body.content : \"*/swip/Upload.ashx*\" and http.request.body.content : (\"POST*\", \"PUT*\")) or\n (http.request.body.content : (\"*/swip/SystemDescription*\", \"*/swip/Events*\") and http.request.body.content : (\"GET*\", \"HEAD*\"))\n ) and\n not http.request.body.content : \"*solarwinds.com*\"\n )\n", "references": [ "https://www.fireeye.com/blog/threat-research/2020/12/evasive-attacker-leverages-solarwinds-supply-chain-compromises-with-sunburst-backdoor.html" @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_teamviewer_remote_file_copy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_teamviewer_remote_file_copy.json index 0e82077dd3da8..82e7f299ea8fa 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_teamviewer_remote_file_copy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_teamviewer_remote_file_copy.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote File Copy via TeamViewer", - "note": "## Triage and analysis\n\n### Investigating Remote File Copy via TeamViewer\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse legitimate utilities to drop these files.\n\nTeamViewer is a remote access and remote control tool used by helpdesks and system administrators to perform various\nsupport activities. It is also frequently used by attackers and scammers to deploy malware interactively and other\nmalicious activities. This rule looks for the TeamViewer process creating files with suspicious extensions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Contact the user to gather information about who and why was conducting the remote access.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check whether the company uses TeamViewer for the support activities and if there is a support ticket related to this\naccess.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Analysts can dismiss the alert if the company relies on TeamViewer to conduct\nremote access and the triage has not identified suspicious or malicious files.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Remote File Copy via TeamViewer\n\nAttackers commonly transfer tooling or malware from external systems into a compromised environment using the command\nand control channel. However, they can also abuse legitimate utilities to drop these files.\n\nTeamViewer is a remote access and remote control tool used by helpdesks and system administrators to perform various\nsupport activities. It is also frequently used by attackers and scammers to deploy malware interactively and other\nmalicious activities. This rule looks for the TeamViewer process creating files with suspicious extensions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Contact the user to gather information about who and why was conducting the remote access.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check whether the company uses TeamViewer for the support activities and if there is a support ticket related to this\naccess.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Analysts can dismiss the alert if the company relies on TeamViewer to conduct\nremote access and the triage has not identified suspicious or malicious files.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type == \"creation\" and process.name : \"TeamViewer.exe\" and\n file.extension : (\"exe\", \"dll\", \"scr\", \"com\", \"bat\", \"ps1\", \"vbs\", \"vbe\", \"js\", \"wsh\", \"hta\")\n", "references": [ "https://blog.menasec.net/2019/11/hunting-for-suspicious-use-of.html" @@ -43,7 +43,8 @@ "Host", "Windows", "Threat Detection", - "Command and Control" + "Command and Control", + "has_guide" ], "threat": [ { @@ -69,5 +70,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json index 646cc2397ac02..490b96665a83b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json @@ -61,7 +61,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -85,5 +86,5 @@ "value": 25 }, "type": "threshold", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_bruteforce_passowrd_guessing.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_bruteforce_passowrd_guessing.json index a50ad42b025ad..5d6992ccec503 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_bruteforce_passowrd_guessing.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_bruteforce_passowrd_guessing.json @@ -10,7 +10,8 @@ ], "language": "eql", "license": "Elastic License v2", - "name": "Potential SSH Password Spraying", + "name": "Potential SSH Password Guessing", + "note": "## Triage and analysis\n\n### Investigating Potential SSH Password Guessing Attack\n\nThe rule identifies consecutive SSH login failures followed by a successful login from the same source IP address to the\nsame target host indicating a successful attempt of brute force password guessing.\n\n#### Possible investigation steps\n\n- Investigate the login failure user name(s).\n- Investigate the source IP address of the failed ssh login attempt(s).\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Identify the source and the target computer and their roles in the IT environment.\n\n### False positive analysis\n\n- Authentication misconfiguration or obsolete credentials.\n- Service account password expired.\n- Infrastructure or availability issue.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Ensure active session(s) on the host(s) are terminated as the attacker could have gained initial\naccess to the system(s).\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified.\n- Reset passwords for these accounts and other potentially compromised credentials.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n", "query": "sequence by host.id, source.ip, user.name with maxspan=3s\n [authentication where event.action in (\"ssh_login\", \"user_login\") and\n event.outcome == \"failure\" and source.ip != null and source.ip != \"0.0.0.0\" and source.ip != \"::\" ] with runs=2\n\n [authentication where event.action in (\"ssh_login\", \"user_login\") and\n event.outcome == \"success\" and source.ip != null and source.ip != \"0.0.0.0\" and source.ip != \"::\" ]\n", "required_fields": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_cmdline_dump_tool.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_cmdline_dump_tool.json index dbc92a27f7040..30103c4bf3c5c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_cmdline_dump_tool.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_cmdline_dump_tool.json @@ -58,7 +58,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json index 844b09d5de305..cf962e1f5f65b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential Credential Access via Trusted Developer Utility", - "note": "## Triage and analysis\n\n### Investigating Potential Credential Access via Trusted Developer Utility\n\nThe Microsoft Build Engine is a platform for building applications. This engine, also known as MSBuild, provides an XML\nschema for a project file that controls how the build platform processes and builds software.\n\nAdversaries can abuse MSBuild to proxy the execution of malicious code. The inline task capability of MSBuild that was\nintroduced in .NET version 4 allows for C# or Visual Basic code to be inserted into an XML project file. MSBuild will\ncompile and execute the inline task. `MSBuild.exe` is a signed Microsoft binary, and the execution of code using it can bypass\napplication control defenses that are configured to allow `MSBuild.exe` execution.\n\nThis rule looks for the MSBuild process loading `vaultcli.dll` or `SAMLib.DLL`, which indicates the execution of\ncredential access activities.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Examine the command line to identify the `.csproj` file location.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target\nhost after the registry modification.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Potential Credential Access via Trusted Developer Utility\n\nThe Microsoft Build Engine is a platform for building applications. This engine, also known as MSBuild, provides an XML\nschema for a project file that controls how the build platform processes and builds software.\n\nAdversaries can abuse MSBuild to proxy the execution of malicious code. The inline task capability of MSBuild that was\nintroduced in .NET version 4 allows for C# or Visual Basic code to be inserted into an XML project file. MSBuild will\ncompile and execute the inline task. `MSBuild.exe` is a signed Microsoft binary, and the execution of code using it can bypass\napplication control defenses that are configured to allow `MSBuild.exe` execution.\n\nThis rule looks for the MSBuild process loading `vaultcli.dll` or `SAMLib.DLL`, which indicates the execution of\ncredential access activities.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Examine the command line to identify the `.csproj` file location.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target\nhost after the registry modification.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by process.entity_id\n [process where event.type == \"start\" and (process.name : \"MSBuild.exe\" or process.pe.original_file_name == \"MSBuild.exe\")]\n [any where (event.category == \"library\" or (event.category == \"process\" and event.action : \"Image loaded*\")) and\n (dll.name : (\"vaultcli.dll\", \"SAMLib.DLL\") or file.name : (\"vaultcli.dll\", \"SAMLib.DLL\"))]\n", "required_fields": [ { @@ -67,7 +67,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -87,5 +88,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dcsync_replication_rights.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dcsync_replication_rights.json index 38a9092d1eb2f..15fcde9b83e81 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dcsync_replication_rights.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dcsync_replication_rights.json @@ -58,7 +58,8 @@ "Windows", "Threat Detection", "Credential Access", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -86,5 +87,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_disable_kerberos_preauth.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_disable_kerberos_preauth.json index 0bde382a2e55a..783852168fcb5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_disable_kerberos_preauth.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_disable_kerberos_preauth.json @@ -39,7 +39,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -67,5 +68,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dump_registry_hives.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dump_registry_hives.json index 15e4cad7bfc40..49a04cb198d86 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dump_registry_hives.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_dump_registry_hives.json @@ -43,7 +43,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { 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 index 41e7921aab797..2140870e22d1f 100644 --- 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 @@ -61,7 +61,8 @@ "SecOps", "Identity and Access", "Credential Access", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -91,5 +92,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_kerberoasting_unusual_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_kerberoasting_unusual_process.json index b10a2e5ea9fbc..11a8abce27853 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_kerberoasting_unusual_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_kerberoasting_unusual_process.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Kerberos Traffic from Unusual Process", - "note": "## Triage and analysis\n\n### Investigating Kerberos Traffic from Unusual Process\n\nKerberos is the default authentication protocol in Active Directory, designed to provide strong authentication for\nclient/server applications by using secret-key cryptography.\n\nDomain-joined hosts usually perform Kerberos traffic using the `lsass.exe` process. This rule detects the occurrence of\ntraffic on the Kerberos port (88) by processes other than `lsass.exe` to detect the unusual request and usage of\nKerberos tickets.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check if the Destination IP is related to a Domain Controller.\n- Review event ID 4769 for suspicious ticket requests.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule uses a Kerberos-related port but does not identify the protocol used on that port. HTTP traffic on a\nnon-standard port or destination IP address unrelated to Domain controllers can create false positives.\n- Exceptions can be added for noisy/frequent connections.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n - Ticket requests can be used to investigate potentially compromised accounts.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Kerberos Traffic from Unusual Process\n\nKerberos is the default authentication protocol in Active Directory, designed to provide strong authentication for\nclient/server applications by using secret-key cryptography.\n\nDomain-joined hosts usually perform Kerberos traffic using the `lsass.exe` process. This rule detects the occurrence of\ntraffic on the Kerberos port (88) by processes other than `lsass.exe` to detect the unusual request and usage of\nKerberos tickets.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Check if the Destination IP is related to a Domain Controller.\n- Review event ID 4769 for suspicious ticket requests.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule uses a Kerberos-related port but does not identify the protocol used on that port. HTTP traffic on a\nnon-standard port or destination IP address unrelated to Domain controllers can create false positives.\n- Exceptions can be added for noisy/frequent connections.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n - Ticket requests can be used to investigate potentially compromised accounts.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "network where event.type == \"start\" and network.direction : (\"outgoing\", \"egress\") and\n destination.port == 88 and source.port >= 49152 and\n not process.executable :\n (\"?:\\\\Windows\\\\System32\\\\lsass.exe\",\n \"System\",\n \"\\\\device\\\\harddiskvolume?\\\\windows\\\\system32\\\\lsass.exe\",\n \"?:\\\\Program Files\\\\rapid7\\\\nexpose\\\\nse\\\\.DLLCACHE\\\\nseserv.exe\",\n \"?:\\\\Program Files (x86)\\\\GFI\\\\LanGuard 12 Agent\\\\lnsscomm.exe\",\n \"?:\\\\Program Files (x86)\\\\SuperScan\\\\scanner.exe\",\n \"?:\\\\Program Files (x86)\\\\Nmap\\\\nmap.exe\",\n \"\\\\device\\\\harddiskvolume?\\\\program files (x86)\\\\nmap\\\\nmap.exe\") and\n destination.address !=\"127.0.0.1\" and destination.address !=\"::1\" and\n /* insert false positives here */\n not process.name in (\"swi_fc.exe\", \"fsIPcam.exe\", \"IPCamera.exe\", \"MicrosoftEdgeCP.exe\", \"MicrosoftEdge.exe\", \"iexplore.exe\", \"chrome.exe\", \"msedge.exe\", \"opera.exe\", \"firefox.exe\")\n", "required_fields": [ { @@ -63,7 +63,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -84,5 +85,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_lsass_memdump_handle_access.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_lsass_memdump_handle_access.json index 63b939ff2e55c..eb1af7292bdfa 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_lsass_memdump_handle_access.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_lsass_memdump_handle_access.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "LSASS Memory Dump Handle Access", - "note": "## Triage and analysis\n\n### Investigating LSASS Memory Dump Handle Access\n\nLocal Security Authority Server Service (LSASS) is a process in Microsoft Windows operating systems that is responsible\nfor enforcing security policy on the system. It verifies users logging on to a Windows computer or server, handles\npassword changes, and creates access tokens.\n\nAdversaries may attempt to access credential material stored in LSASS process memory. After a user logs on,the system\ngenerates and stores a variety of credential materials in LSASS process memory. This is meant to facilitate single\nsign-on (SSO) ensuring a user isn\u2019t prompted each time resource access is requested. These credential materials can be\nharvested by an adversary using administrative user or SYSTEM privileges to conduct lateral movement using\n[alternate authentication material](https://attack.mitre.org/techniques/T1550/).\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There should be very few or no false positives for this rule. If this activity is expected or noisy in your environment,\nconsider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n- If the process is related to antivirus or endpoint detection and response solutions, validate that it is installed on\nthe correct path and signed with the company's valid digital signature.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Scope compromised credentials and disable the accounts.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\nEnsure advanced audit policies for Windows are enabled, specifically:\nObject Access policies [Event ID 4656](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4656) (Handle to an Object was Requested)\n\n```\nComputer Configuration >\nPolicies >\nWindows Settings >\nSecurity Settings >\nAdvanced Audit Policies Configuration >\nSystem Audit Policies >\nObject Access >\nAudit File System (Success,Failure)\nAudit Handle Manipulation (Success,Failure)\n```\n\nAlso, this event generates only if the object\u2019s [SACL](https://docs.microsoft.com/en-us/windows/win32/secauthz/access-control-lists) has the required access control entry (ACE) to handle the use of specific access rights.\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", + "note": "## Triage and analysis\n\n### Investigating LSASS Memory Dump Handle Access\n\nLocal Security Authority Server Service (LSASS) is a process in Microsoft Windows operating systems that is responsible\nfor enforcing security policy on the system. It verifies users logging on to a Windows computer or server, handles\npassword changes, and creates access tokens.\n\nAdversaries may attempt to access credential material stored in LSASS process memory. After a user logs on,the system\ngenerates and stores a variety of credential materials in LSASS process memory. This is meant to facilitate single\nsign-on (SSO) ensuring a user isn\u2019t prompted each time resource access is requested. These credential materials can be\nharvested by an adversary using administrative user or SYSTEM privileges to conduct lateral movement using\n[alternate authentication material](https://attack.mitre.org/techniques/T1550/).\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There should be very few or no false positives for this rule. If this activity is expected or noisy in your environment,\nconsider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n- If the process is related to antivirus or endpoint detection and response solutions, validate that it is installed on\nthe correct path and signed with the company's valid digital signature.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Scope compromised credentials and disable the accounts.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\nEnsure advanced audit policies for Windows are enabled, specifically:\nObject Access policies [Event ID 4656](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4656) (Handle to an Object was Requested)\n\n```\nComputer Configuration >\nPolicies >\nWindows Settings >\nSecurity Settings >\nAdvanced Audit Policies Configuration >\nSystem Audit Policies >\nObject Access >\nAudit File System (Success,Failure)\nAudit Handle Manipulation (Success,Failure)\n```\n\nAlso, this event generates only if the object\u2019s [SACL](https://docs.microsoft.com/en-us/windows/win32/secauthz/access-control-lists) has the required access control entry (ACE) to handle the use of specific access rights.\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", "query": "any where event.action == \"File System\" and event.code == \"4656\" and\n\n winlog.event_data.ObjectName : (\n \"?:\\\\Windows\\\\System32\\\\lsass.exe\",\n \"\\\\Device\\\\HarddiskVolume?\\\\Windows\\\\System32\\\\lsass.exe\",\n \"\\\\Device\\\\HarddiskVolume??\\\\Windows\\\\System32\\\\lsass.exe\") and\n\n /* The right to perform an operation controlled by an extended access right. */\n\n (winlog.event_data.AccessMask : (\"0x1fffff\" , \"0x1010\", \"0x120089\", \"0x1F3FFF\") or\n winlog.event_data.AccessMaskDescription : (\"READ_CONTROL\", \"Read from process memory\"))\n\n /* Common Noisy False Positives */\n\n and not winlog.event_data.ProcessName : (\n \"?:\\\\Program Files\\\\*.exe\",\n \"?:\\\\Program Files (x86)\\\\*.exe\",\n \"?:\\\\Windows\\\\system32\\\\wbem\\\\WmiPrvSE.exe\",\n \"?:\\\\Windows\\\\System32\\\\dllhost.exe\",\n \"?:\\\\Windows\\\\System32\\\\svchost.exe\",\n \"?:\\\\Windows\\\\System32\\\\msiexec.exe\",\n \"?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender\\\\*.exe\",\n \"?:\\\\Windows\\\\explorer.exe\")\n", "references": [ "https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4656", @@ -61,7 +61,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -89,5 +90,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_memssp_default_logs.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_memssp_default_logs.json index 05199fed31f61..5fa244d380ae1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_memssp_default_logs.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_memssp_default_logs.json @@ -35,7 +35,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -56,5 +57,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_powershell_module.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_powershell_module.json index 0524d0dbb1a2e..f78eead09dea8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_powershell_module.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mimikatz_powershell_module.json @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -66,5 +67,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mod_wdigest_security_provider.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mod_wdigest_security_provider.json index 018868f23fb20..d5a13d5f0285f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mod_wdigest_security_provider.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_mod_wdigest_security_provider.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Modification of WDigest Security Provider", - "note": "## Triage and analysis\n\n### Investigating Modification of WDigest Security Provider\n\nIn Windows XP, Microsoft added support for a protocol known as WDigest. The WDigest protocol allows clients to send\ncleartext credentials to Hypertext Transfer Protocol (HTTP) and Simple Authentication Security Layer (SASL) applications\nbased on RFC 2617 and 2831. Windows versions up to 8 and 2012 store logon credentials in memory in plaintext by default,\nwhich is no longer the case with newer Windows versions.\n\nStill, attackers can force WDigest to store the passwords insecurely on the memory by modifying the\n`HKLM\\SYSTEM\\*ControlSet*\\Control\\SecurityProviders\\WDigest\\UseLogonCredential` registry key. This activity is\ncommonly related to the execution of credential dumping tools.\n\n#### Possible investigation steps\n\n- It is unlikely that the monitored registry key was modified legitimately in newer versions of Windows. Analysts should\ntreat any activity triggered from this rule with high priority as it typically represents an active adversary.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Determine if credential dumping tools were run on the host, and retrieve and analyze suspicious executables:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences on other hosts.\n- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target\nhost after the registry modification.\n\n### False positive analysis\n\n- This modification should not happen legitimately. Any potential benign true positive (B-TP) should be mapped and\nmonitored by the security team, as these modifications expose the entire domain to credential compromises and\nconsequently unauthorized access.\n\n### Related rules\n\n- Mimikatz Powershell Module Activity - ac96ceb8-4399-4191-af1d-4feeac1f1f46\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Modification of WDigest Security Provider\n\nIn Windows XP, Microsoft added support for a protocol known as WDigest. The WDigest protocol allows clients to send\ncleartext credentials to Hypertext Transfer Protocol (HTTP) and Simple Authentication Security Layer (SASL) applications\nbased on RFC 2617 and 2831. Windows versions up to 8 and 2012 store logon credentials in memory in plaintext by default,\nwhich is no longer the case with newer Windows versions.\n\nStill, attackers can force WDigest to store the passwords insecurely on the memory by modifying the\n`HKLM\\SYSTEM\\*ControlSet*\\Control\\SecurityProviders\\WDigest\\UseLogonCredential` registry key. This activity is\ncommonly related to the execution of credential dumping tools.\n\n#### Possible investigation steps\n\n- It is unlikely that the monitored registry key was modified legitimately in newer versions of Windows. Analysts should\ntreat any activity triggered from this rule with high priority as it typically represents an active adversary.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Determine if credential dumping tools were run on the host, and retrieve and analyze suspicious executables:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences on other hosts.\n- Investigate potentially compromised accounts. Analysts can do this by searching for login events (for example, 4624) to the target\nhost after the registry modification.\n\n### False positive analysis\n\n- This modification should not happen legitimately. Any potential benign true positive (B-TP) should be mapped and\nmonitored by the security team, as these modifications expose the entire domain to credential compromises and\nconsequently unauthorized access.\n\n### Related rules\n\n- Mimikatz Powershell Module Activity - ac96ceb8-4399-4191-af1d-4feeac1f1f46\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where event.type : (\"creation\", \"change\") and\n registry.path :\n \"HKLM\\\\SYSTEM\\\\*ControlSet*\\\\Control\\\\SecurityProviders\\\\WDigest\\\\UseLogonCredential\"\n and registry.data.strings : (\"1\", \"0x00000001\") and\n not (process.executable : \"?:\\\\Windows\\\\System32\\\\svchost.exe\" and user.id : \"S-1-5-18\")\n", "references": [ "https://www.csoonline.com/article/3438824/how-to-detect-and-halt-credential-theft-via-windows-wdigest.html", @@ -55,7 +55,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -83,5 +84,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_moving_registry_hive_via_smb.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_moving_registry_hive_via_smb.json index ca2bae7cdc87d..9da4639332581 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_moving_registry_hive_via_smb.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_moving_registry_hive_via_smb.json @@ -48,7 +48,8 @@ "Windows", "Threat Detection", "Lateral Movement", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -98,5 +99,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_minidump.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_minidump.json index a8be93f64e493..aa5dc5f8288d6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_minidump.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_minidump.json @@ -42,7 +42,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -92,5 +93,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_request_ticket.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_request_ticket.json index 8df600b289265..0caeb8f4cd34e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_request_ticket.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_posh_request_ticket.json @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -93,5 +94,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce.json index 0dde40f82f1ce..bd28407a2d53c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce.json @@ -10,7 +10,8 @@ ], "language": "eql", "license": "Elastic License v2", - "name": "Potential SSH Brute Force Detected", + "name": "Potential Linux SSH Brute Force Detected", + "note": "## Triage and analysis\n\n### Investigating Potential SSH Brute Force Attack\n\nThe rule identifies consecutive SSH login failures targeting a user account from the same source IP address to the\nsame target host indicating brute force login attempts.\n\n#### Possible investigation steps\n\n- Investigate the login failure user name(s).\n- Investigate the source IP address of the failed ssh login attempt(s).\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Identify the source and the target computer and their roles in the IT environment.\n\n### False positive analysis\n\n- Authentication misconfiguration or obsolete credentials.\n- Service account password expired.\n- Infrastructure or availability issue.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified.\n- Reset passwords for these accounts and other potentially compromised credentials.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n", "query": "sequence by host.id, source.ip, user.name with maxspan=10s\n [authentication where event.action in (\"ssh_login\", \"user_login\") and\n event.outcome == \"failure\" and source.ip != null and source.ip != \"0.0.0.0\" and source.ip != \"::\" ] with runs=10\n", "required_fields": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce_root.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce_root.json index a15fa38e979a1..f540d3ae3202c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce_root.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_linux_ssh_bruteforce_root.json @@ -11,6 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential SSH Brute Force Detected on Privileged Account", + "note": "## Triage and analysis\n\n### Investigating Potential SSH Brute Force Attack on Privileged Account\n\nThe rule identifies consecutive SSH login failures targeting a privileged (root) account from the same source IP\naddress to the same target host indicating brute force login attempts.\n\n#### Possible investigation steps\n\n- Investigate the login failure on privileged account(s).\n- Investigate the source IP address of the failed ssh login attempt(s).\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Identify the source and the target computer and their roles in the IT environment.\n\n### False positive analysis\n- Authentication misconfiguration or obsolete credentials.\n- Service account password expired.\n- Infrastructure or availability issue.\n\n### Response and remediation\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified.\n- Reset passwords for these accounts and other potentially compromised credentials.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n", "query": "sequence by host.id, source.ip with maxspan=10s\n [authentication where event.action in (\"ssh_login\", \"user_login\") and\n event.outcome == \"failure\" and source.ip != null and source.ip != \"0.0.0.0\" and\n source.ip != \"::\" and user.name in (\"*root*\" , \"*admin*\")] with runs=3\n", "required_fields": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_ssh_bruteforce.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_macos_ssh_bruteforce.json similarity index 95% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_ssh_bruteforce.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_macos_ssh_bruteforce.json index 89519f49a1170..0f420cfb6d08f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_ssh_bruteforce.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_potential_macos_ssh_bruteforce.json @@ -10,7 +10,7 @@ ], "language": "kuery", "license": "Elastic License v2", - "name": "Potential SSH Brute Force Detected", + "name": "Potential macOS SSH Brute Force Detected", "query": "event.category:process and event.type:start and process.name:\"sshd-keygen-wrapper\" and process.parent.name:launchd\n", "references": [ "https://themittenmac.com/detecting-ssh-activity-via-process-monitoring/" @@ -71,5 +71,5 @@ "value": 20 }, "type": "threshold", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_remote_sam_secretsdump.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_remote_sam_secretsdump.json index 41d744c1ea8b1..1b6a0498a8f52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_remote_sam_secretsdump.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_remote_sam_secretsdump.json @@ -89,7 +89,8 @@ "Windows", "Threat Detection", "Lateral Movement", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -131,5 +132,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } 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 index df0d68a13f901..2ec5b4d9a877b 100644 --- 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 @@ -57,7 +57,8 @@ "Continuous Monitoring", "SecOps", "Data Protection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -78,5 +79,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_seenabledelegationprivilege_assigned_to_user.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_seenabledelegationprivilege_assigned_to_user.json index 8421a442c4724..1992b3a85cf93 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_seenabledelegationprivilege_assigned_to_user.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_seenabledelegationprivilege_assigned_to_user.json @@ -47,7 +47,8 @@ "Windows", "Threat Detection", "Credential Access", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -71,5 +72,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_spn_attribute_modified.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_spn_attribute_modified.json index 2b6866599d3da..8fb978965654c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_spn_attribute_modified.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_spn_attribute_modified.json @@ -53,7 +53,8 @@ "Windows", "Threat Detection", "Credential Access", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -81,5 +82,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_suspicious_winreg_access_via_sebackup_priv.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_suspicious_winreg_access_via_sebackup_priv.json index 2d2c2fadf1518..d8e9a61e71b4e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_suspicious_winreg_access_via_sebackup_priv.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_suspicious_winreg_access_via_sebackup_priv.json @@ -54,7 +54,8 @@ "Windows", "Threat Detection", "Lateral Movement", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -96,5 +97,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_symbolic_link_to_shadow_copy_created.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_symbolic_link_to_shadow_copy_created.json index 6ae0580651a8c..0286e35f7d049 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_symbolic_link_to_shadow_copy_created.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_symbolic_link_to_shadow_copy_created.json @@ -55,7 +55,8 @@ "Host", "Windows", "Threat Detection", - "Credential Access" + "Credential Access", + "has_guide" ], "threat": [ { @@ -76,5 +77,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_amsienable_key_mod.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_amsienable_key_mod.json index 3e6986451938e..52adb1756ad50 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_amsienable_key_mod.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_amsienable_key_mod.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Modification of AmsiEnable Registry Key", - "note": "## Triage and analysis\n\n### Investigating Modification of AmsiEnable Registry Key\n\nThe Windows Antimalware Scan Interface (AMSI) is a versatile interface standard that allows your applications and\nservices to integrate with any antimalware product that's present on a machine. AMSI provides integration with multiple\nWindows components, ranging from User Account Control (UAC) to VBA Macros.\n\nSince AMSI is widely used across security products for increased visibility, attackers can disable it to evade\ndetections that rely on it.\n\nThis rule monitors the modifications to the Software\\Microsoft\\Windows Script\\Settings\\AmsiEnable registry key.\n\n#### Possible investigation steps\n\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate the execution of scripts and macros after the registry modification.\n- Retrieve scripts or Microsoft Office files and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences on other hosts.\n\n### False positive analysis\n\n- This modification should not happen legitimately. Any potential benign true positive (B-TP) should be mapped and\nmonitored by the security team, as these modifications expose the host to malware infections.\n\n### Related rules\n\n- Microsoft Windows Defender Tampering - fe794edd-487f-4a90-b285-3ee54f2af2d3\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Delete or set the key to its default value.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Modification of AmsiEnable Registry Key\n\nThe Windows Antimalware Scan Interface (AMSI) is a versatile interface standard that allows your applications and\nservices to integrate with any antimalware product that's present on a machine. AMSI provides integration with multiple\nWindows components, ranging from User Account Control (UAC) to VBA Macros.\n\nSince AMSI is widely used across security products for increased visibility, attackers can disable it to evade\ndetections that rely on it.\n\nThis rule monitors the modifications to the Software\\Microsoft\\Windows Script\\Settings\\AmsiEnable registry key.\n\n#### Possible investigation steps\n\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate the execution of scripts and macros after the registry modification.\n- Retrieve scripts or Microsoft Office files and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences on other hosts.\n\n### False positive analysis\n\n- This modification should not happen legitimately. Any potential benign true positive (B-TP) should be mapped and\nmonitored by the security team, as these modifications expose the host to malware infections.\n\n### Related rules\n\n- Microsoft Windows Defender Tampering - fe794edd-487f-4a90-b285-3ee54f2af2d3\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Delete or set the key to its default value.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where event.type in (\"creation\", \"change\") and\n registry.path : (\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows Script\\\\Settings\\\\AmsiEnable\",\n \"HKU\\\\*\\\\Software\\\\Microsoft\\\\Windows Script\\\\Settings\\\\AmsiEnable\"\n ) and\n registry.data.strings: (\"0\", \"0x00000000\")\n", "references": [ "https://hackinparis.com/data/slides/2019/talks/HIP2019-Dominic_Chell-Cracking_The_Perimeter_With_Sharpshooter.pdf", @@ -44,7 +44,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -72,5 +73,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_azure_service_principal_addition.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_azure_service_principal_addition.json index 73223f74a8c37..8b409bdb63681 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_azure_service_principal_addition.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_azure_service_principal_addition.json @@ -53,7 +53,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -81,5 +82,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_console_history.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_console_history.json index 191502d44c71b..972c69b5052da 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_console_history.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_console_history.json @@ -50,7 +50,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -78,5 +79,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 index fec3c5dd2f0e2..ff068224efa5a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_security_logs.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_security_logs.json index a79fba0714765..eed3ed289c9c1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_security_logs.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_security_logs.json @@ -29,7 +29,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -57,5 +58,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index fa2c001a1e37a..cb0f9d549a04e 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Log Auditing" + "Log Auditing", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index c0f990f8e496e..97867f74d0557 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Log Auditing" + "Log Auditing", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index 3f0d5960e41f6..6fc0a85d8e9cc 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Monitoring" + "Monitoring", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index 15b0818b4d3d6..9113f5907dd3b 100644 --- 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 @@ -56,7 +56,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Monitoring" + "Monitoring", + "has_guide" ], "threat": [ { @@ -84,5 +85,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_create_mod_root_certificate.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_create_mod_root_certificate.json index 6221668580ee1..2264c363bb04c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_create_mod_root_certificate.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_create_mod_root_certificate.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Creation or Modification of Root Certificate", - "note": "## Triage and analysis\n\n### Investigating Creation or Modification of Root Certificate\n\nRoot certificates are the primary level of certifications that tell a browser that the communication is trusted and\nlegitimate. This verification is based upon the identification of a certification authority. Windows\nadds several trusted root certificates so browsers can use them to communicate with websites.\n\n[Check out this post](https://www.thewindowsclub.com/what-are-root-certificates-windows) for more details on root certificates and the involved cryptography.\n\nThis rule identifies the creation or modification of a root certificate by monitoring registry modifications. The\ninstallation of a malicious root certificate would allow an attacker the ability to masquerade malicious files as valid\nsigned components from any entity (for example, Microsoft). It could also allow an attacker to decrypt SSL traffic.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, other registry or file\nmodifications, and any spawned child processes.\n- If one of the processes is suspicious, retrieve it and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This detection may be triggered by certain applications that install root certificates for the purpose of inspecting\nSSL traffic. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove the malicious certificate from the root certificate store.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Creation or Modification of Root Certificate\n\nRoot certificates are the primary level of certifications that tell a browser that the communication is trusted and\nlegitimate. This verification is based upon the identification of a certification authority. Windows\nadds several trusted root certificates so browsers can use them to communicate with websites.\n\n[Check out this post](https://www.thewindowsclub.com/what-are-root-certificates-windows) for more details on root certificates and the involved cryptography.\n\nThis rule identifies the creation or modification of a root certificate by monitoring registry modifications. The\ninstallation of a malicious root certificate would allow an attacker the ability to masquerade malicious files as valid\nsigned components from any entity (for example, Microsoft). It could also allow an attacker to decrypt SSL traffic.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, other registry or file\nmodifications, and any spawned child processes.\n- If one of the processes is suspicious, retrieve it and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This detection may be triggered by certain applications that install root certificates for the purpose of inspecting\nSSL traffic. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove the malicious certificate from the root certificate store.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where event.type in (\"creation\", \"change\") and\n registry.path :\n (\n \"HKLM\\\\Software\\\\Microsoft\\\\SystemCertificates\\\\Root\\\\Certificates\\\\*\\\\Blob\",\n \"HKLM\\\\Software\\\\Microsoft\\\\SystemCertificates\\\\AuthRoot\\\\Certificates\\\\*\\\\Blob\",\n \"HKLM\\\\Software\\\\Policies\\\\Microsoft\\\\SystemCertificates\\\\Root\\\\Certificates\\\\*\\\\Blob\",\n \"HKLM\\\\Software\\\\Policies\\\\Microsoft\\\\SystemCertificates\\\\AuthRoot\\\\Certificates\\\\*\\\\Blob\"\n ) and\n not process.executable :\n (\"?:\\\\Program Files\\\\*.exe\",\n \"?:\\\\Program Files (x86)\\\\*.exe\",\n \"?:\\\\Windows\\\\System32\\\\*.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\*.exe\",\n \"?:\\\\Windows\\\\Sysmon64.exe\",\n \"?:\\\\Windows\\\\Sysmon.exe\",\n \"?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender\\\\Platform\\\\*\\\\MsMpEng.exe\",\n \"?:\\\\Windows\\\\WinSxS\\\\*.exe\",\n \"?:\\\\Windows\\\\UUS\\\\amd64\\\\MoUsoCoreWorker.exe\")\n", "references": [ "https://posts.specterops.io/code-signing-certificate-cloning-attacks-and-defenses-6f98657fc6ec", @@ -47,7 +47,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -75,5 +76,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_disabled_via_registry.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_disabled_via_registry.json index 4bf9babea192f..5b39ffc36ed8e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_disabled_via_registry.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_disabled_via_registry.json @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -81,5 +82,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_exclusion_via_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_exclusion_via_powershell.json index 90650abf7b9bb..5a74bfc9b1664 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_exclusion_via_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_defender_exclusion_via_powershell.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Windows Defender Exclusions Added via PowerShell", - "note": "## Triage and analysis\n\n### Investigating Windows Defender Exclusions Added via PowerShell\n\nMicrosoft Windows Defender is an antivirus product built into Microsoft Windows. Since this software product is\nused to prevent and stop malware, it's important to monitor what specific exclusions are made to the product's configuration\nsettings. These can often be signs of an adversary or malware trying to bypass Windows Defender's capabilities. One of\nthe more notable [examples](https://www.cyberbit.com/blog/endpoint-security/latest-trickbot-variant-has-new-tricks-up-its-sleeve/)\nwas observed in 2018 where Trickbot incorporated mechanisms to disable Windows Defender to avoid detection.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Examine the exclusion in order to determine the intent behind it.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- If the exclusion specifies a suspicious file or path, retrieve the file(s) and determine if malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule has a high chance to produce false positives due to how often network administrators legitimately configure\nexclusions. In order to validate the activity further, review the specific exclusion and its intent. There are many\nlegitimate reasons for exclusions, so it's important to gain context.\n\n### Related rules\n\n- Windows Defender Disabled via Registry Modification - 2ffa1f1e-b6db-47fa-994b-1512743847eb\n- Disabling Windows Defender Security Settings via PowerShell - c8cccb06-faf2-4cd5-886e-2c9636cfcb87\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Exclusion lists for antimalware capabilities should always be routinely monitored for review.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Windows Defender Exclusions Added via PowerShell\n\nMicrosoft Windows Defender is an antivirus product built into Microsoft Windows. Since this software product is\nused to prevent and stop malware, it's important to monitor what specific exclusions are made to the product's configuration\nsettings. These can often be signs of an adversary or malware trying to bypass Windows Defender's capabilities. One of\nthe more notable [examples](https://www.cyberbit.com/blog/endpoint-security/latest-trickbot-variant-has-new-tricks-up-its-sleeve/)\nwas observed in 2018 where Trickbot incorporated mechanisms to disable Windows Defender to avoid detection.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Examine the exclusion in order to determine the intent behind it.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- If the exclusion specifies a suspicious file or path, retrieve the file(s) and determine if malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This rule has a high chance to produce false positives due to how often network administrators legitimately configure\nexclusions. In order to validate the activity further, review the specific exclusion and its intent. There are many\nlegitimate reasons for exclusions, so it's important to gain context.\n\n### Related rules\n\n- Windows Defender Disabled via Registry Modification - 2ffa1f1e-b6db-47fa-994b-1512743847eb\n- Disabling Windows Defender Security Settings via PowerShell - c8cccb06-faf2-4cd5-886e-2c9636cfcb87\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Exclusion lists for antimalware capabilities should always be routinely monitored for review.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name : (\"powershell.exe\", \"pwsh.exe\", \"powershell_ise.exe\") or process.pe.original_file_name in (\"powershell.exe\", \"pwsh.dll\", \"powershell_ise.exe\")) and\n process.args : (\"*Add-MpPreference*\", \"*Set-MpPreference*\") and\n process.args : (\"*-Exclusion*\")\n", "references": [ "https://www.bitdefender.com/files/News/CaseStudies/study/400/Bitdefender-PR-Whitepaper-MosaicLoader-creat5540-en-EN.pdf" @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -103,5 +104,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_posh_scriptblocklogging.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_posh_scriptblocklogging.json index 3132045aeb9f1..f4c3273953dca 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_posh_scriptblocklogging.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_posh_scriptblocklogging.json @@ -43,7 +43,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -71,5 +72,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 index 912596ec4188f..a07759a72e73f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_defender_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_defender_powershell.json index 9629c53ead56c..21c0bd54b831c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_defender_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_defender_powershell.json @@ -51,7 +51,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -79,5 +80,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_logs.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_logs.json index 24dde4c55f75b..b6c0b9ceceb53 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_logs.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disabling_windows_logs.json @@ -51,7 +51,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { 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 index 6cd510f9c638c..9104509c8576e 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Log Auditing" + "Log Auditing", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_inbound_rdp_with_netsh.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_inbound_rdp_with_netsh.json index c90adc84eb4b7..5ddaa9cdac60a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_inbound_rdp_with_netsh.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_inbound_rdp_with_netsh.json @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_network_discovery_with_netsh.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_network_discovery_with_netsh.json index b23b4a422fe4c..5013d8a5d731a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_network_discovery_with_netsh.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_enable_network_discovery_with_netsh.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Enable Host Network Discovery via Netsh", - "note": "## Triage and analysis\n\n### Investigating Enable Host Network Discovery via Netsh\n\nThe Windows Defender Firewall is a native component that provides host-based, two-way network traffic filtering for a\ndevice and blocks unauthorized network traffic flowing into or out of the local device.\n\nAttackers can enable Network Discovery on the Windows firewall to find other systems present in the same network. Systems\nwith this setting enabled will communicate with other systems using broadcast messages, which can be used to identify\ntargets for lateral movement. This rule looks for the setup of this setting using the netsh utility.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Analysts can dismiss the alert if the administrator is aware of the activity\nand there are justifications for this configuration.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Disable Network Discovery:\n - Using netsh: `netsh advfirewall firewall set rule group=\"Network Discovery\" new enable=No`\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Review the privileges assigned to the involved users to ensure that the least privilege principle is being followed.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Enable Host Network Discovery via Netsh\n\nThe Windows Defender Firewall is a native component that provides host-based, two-way network traffic filtering for a\ndevice and blocks unauthorized network traffic flowing into or out of the local device.\n\nAttackers can enable Network Discovery on the Windows firewall to find other systems present in the same network. Systems\nwith this setting enabled will communicate with other systems using broadcast messages, which can be used to identify\ntargets for lateral movement. This rule looks for the setup of this setting using the netsh utility.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Analysts can dismiss the alert if the administrator is aware of the activity\nand there are justifications for this configuration.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Disable Network Discovery:\n - Using netsh: `netsh advfirewall firewall set rule group=\"Network Discovery\" new enable=No`\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Review the privileges assigned to the involved users to ensure that the least privilege principle is being followed.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\nprocess.name : \"netsh.exe\" and\nprocess.args : (\"firewall\", \"advfirewall\") and process.args : \"group=Network Discovery\" and process.args : \"enable=Yes\"\n", "required_fields": [ { @@ -43,7 +43,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -71,5 +72,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 index faa6600e315bd..a3a651443340c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_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 @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Microsoft Build Engine Started by an Office Application", - "note": "## Triage and analysis\n\n### Investigating Microsoft Build Engine Started by an Office Application\n\nMicrosoft Office (MS Office) is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently targeted\nfor initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThe Microsoft Build Engine is a platform for building applications. This engine, also known as MSBuild, provides an XML\nschema for a project file that controls how the build platform processes and builds software, and can be abused to proxy\nexecution of code.\n\nThis rule looks for the `Msbuild.exe` utility spawned by MS Office programs. This is generally the result of the\nexecution of malicious documents.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Microsoft Build Engine Started by an Office Application\n\nMicrosoft Office (MS Office) is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently targeted\nfor initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThe Microsoft Build Engine is a platform for building applications. This engine, also known as MSBuild, provides an XML\nschema for a project file that controls how the build platform processes and builds software, and can be abused to proxy\nexecution of code.\n\nThis rule looks for the `Msbuild.exe` utility spawned by MS Office programs. This is generally the result of the\nexecution of malicious documents.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.name : \"MSBuild.exe\" and\n process.parent.name : (\"eqnedt32.exe\",\n \"excel.exe\",\n \"fltldr.exe\",\n \"msaccess.exe\",\n \"mspub.exe\",\n \"outlook.exe\",\n \"powerpnt.exe\",\n \"winword.exe\" )\n", "references": [ "https://blog.talosintelligence.com/2020/02/building-bypass-with-msbuild.html" @@ -46,7 +46,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_microsoft_defender_tampering.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_microsoft_defender_tampering.json index 24a214f445d77..89a34647ca08c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_microsoft_defender_tampering.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_microsoft_defender_tampering.json @@ -53,7 +53,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -74,5 +75,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ms_office_suspicious_regmod.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ms_office_suspicious_regmod.json index ccb198f287caa..1d50e5192b479 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ms_office_suspicious_regmod.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ms_office_suspicious_regmod.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "MS Office Macro Security Registry Modifications", - "note": "## Triage and analysis\n\n### Investigating MS Office Macro Security Registry Modifications\n\nMacros are small programs that are used to automate repetitive tasks in Microsoft Office applications.\nHistorically, macros have been used for a variety of reasons -- from automating part of a job, to\nbuilding entire processes and data flows. Macros are written in Visual Basic for Applications (VBA) and are saved as\npart of Microsoft Office files.\n\nMacros are often created for legitimate reasons, but they can also be written by attackers to gain access, harm a\nsystem, or bypass other security controls such as application allow listing. In fact, exploitation from malicious macros\nis one of the top ways that organizations are compromised today. These attacks are often conducted through phishing or\nspear phishing campaigns.\n\nAttackers can convince victims to modify Microsoft Office security settings, so their macros are trusted by default and\nno warnings are displayed when they are executed. These settings include:\n\n* *Trust access to the VBA project object model* - When enabled, Microsoft Office will trust all macros and run any code\nwithout showing a security warning or requiring user permission.\n* *VbaWarnings* - When set to 1, Microsoft Office will trust all macros and run any code without showing a security\nwarning or requiring user permission.\n\nThis rule looks for registry changes affecting the conditions above.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the user and check if the change was done manually.\n- Verify whether malicious macros were executed after the registry change.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve recently executed Office documents and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true\npositives (B-TPs), as this configuration can put the user and the domain at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Reset the registry key value.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Explore using GPOs to manage security settings for Microsoft Office macros.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating MS Office Macro Security Registry Modifications\n\nMacros are small programs that are used to automate repetitive tasks in Microsoft Office applications.\nHistorically, macros have been used for a variety of reasons -- from automating part of a job, to\nbuilding entire processes and data flows. Macros are written in Visual Basic for Applications (VBA) and are saved as\npart of Microsoft Office files.\n\nMacros are often created for legitimate reasons, but they can also be written by attackers to gain access, harm a\nsystem, or bypass other security controls such as application allow listing. In fact, exploitation from malicious macros\nis one of the top ways that organizations are compromised today. These attacks are often conducted through phishing or\nspear phishing campaigns.\n\nAttackers can convince victims to modify Microsoft Office security settings, so their macros are trusted by default and\nno warnings are displayed when they are executed. These settings include:\n\n* *Trust access to the VBA project object model* - When enabled, Microsoft Office will trust all macros and run any code\nwithout showing a security warning or requiring user permission.\n* *VbaWarnings* - When set to 1, Microsoft Office will trust all macros and run any code without showing a security\nwarning or requiring user permission.\n\nThis rule looks for registry changes affecting the conditions above.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the user and check if the change was done manually.\n- Verify whether malicious macros were executed after the registry change.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve recently executed Office documents and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true\npositives (B-TPs), as this configuration can put the user and the domain at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Reset the registry key value.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Explore using GPOs to manage security settings for Microsoft Office macros.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where event.type == \"change\" and\n registry.path : (\n \"HKU\\\\S-1-5-21-*\\\\SOFTWARE\\\\Microsoft\\\\Office\\\\*\\\\Security\\\\AccessVBOM\",\n \"HKU\\\\S-1-5-21-*\\\\SOFTWARE\\\\Microsoft\\\\Office\\\\*\\\\Security\\\\VbaWarnings\"\n ) and\n registry.data.strings == \"0x00000001\" and\n process.name : (\"cscript.exe\", \"wscript.exe\", \"mshta.exe\", \"mshta.exe\", \"winword.exe\", \"excel.exe\")\n", "required_fields": [ { @@ -44,7 +44,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -87,5 +88,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_assembly_load.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_assembly_load.json index f2c188f102fa3..56df918e940ec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_assembly_load.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_assembly_load.json @@ -11,7 +11,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "Suspicious .NET Reflection via PowerShell", - "note": "## Triage and analysis\n\n### Investigating Suspicious .NET Reflection via PowerShell\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can use .NET reflection to load PEs and DLLs in memory. These payloads are commonly embedded in the script,\nwhich can circumvent file-based security protections.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Examine file or network events from the involved PowerShell process for suspicious behavior.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did\nnot identify malware or suspicious activity related to the user or host, this alert can be dismissed.\n\n### Related rules\n\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious .NET Reflection via PowerShell\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can use .NET reflection to load PEs and DLLs in memory. These payloads are commonly embedded in the script,\nwhich can circumvent file-based security protections.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Examine file or network events from the involved PowerShell process for suspicious behavior.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did\nnot identify malware or suspicious activity related to the user or host, this alert can be dismissed.\n\n### Related rules\n\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "event.category:process and\n powershell.file.script_block_text : (\n \"[System.Reflection.Assembly]::Load\" or\n \"[Reflection.Assembly]::Load\"\n )\n", "references": [ "https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load" @@ -37,7 +37,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -92,5 +93,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_compressed.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_compressed.json index 0918910210f5e..dec606a855dcb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_compressed.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_compressed.json @@ -14,7 +14,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "PowerShell Suspicious Payload Encoded and Compressed", - "note": "## Triage and analysis\n\n### Investigating PowerShell Suspicious Payload Encoded and Compressed\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can embed compressed and encoded payloads in scripts to load directly into the memory without touching the\ndisk. This strategy can circumvent string and file-based security protections.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Examine file or network events from the involved PowerShell process for suspicious behavior.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did\nnot identify malware or suspicious activity related to the user or host, this alert can be dismissed.\n\n### Related rules\n\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating PowerShell Suspicious Payload Encoded and Compressed\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can embed compressed and encoded payloads in scripts to load directly into the memory without touching the\ndisk. This strategy can circumvent string and file-based security protections.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Examine file or network events from the involved PowerShell process for suspicious behavior.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately outside engineering or IT business units. As long as the analyst did\nnot identify malware or suspicious activity related to the user or host, this alert can be dismissed.\n\n### Related rules\n\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "event.category:process and\n powershell.file.script_block_text : (\n (\n \"System.IO.Compression.DeflateStream\" or\n \"System.IO.Compression.GzipStream\" or\n \"IO.Compression.DeflateStream\" or\n \"IO.Compression.GzipStream\"\n ) and\n FromBase64String\n )\n", "required_fields": [ { @@ -37,7 +37,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -85,5 +86,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_process_injection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_process_injection.json index 53aa8459e996d..686591b1738ab 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_process_injection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_posh_process_injection.json @@ -42,7 +42,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -75,5 +76,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_powershell_windows_firewall_disabled.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_powershell_windows_firewall_disabled.json index 5cc10bf316cdb..9f870734840dd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_powershell_windows_firewall_disabled.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_powershell_windows_firewall_disabled.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Windows Firewall Disabled via PowerShell", - "note": "## Triage and analysis\n\n### Investigating Windows Firewall Disabled via PowerShell\n\nWindows Defender Firewall is a native component that provides host-based, two-way network traffic filtering for a\ndevice and blocks unauthorized network traffic flowing into or out of the local device.\n\nAttackers can disable the Windows firewall or its rules to enable lateral movement and command and control activity.\n\nThis rule identifies patterns related to disabling the Windows firewall or its rules using the `Set-NetFirewallProfile`\nPowerShell cmdlet.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Check whether the user is an administrator and is legitimately performing\ntroubleshooting.\n- In case of an allowed benign true positive (B-TP), assess adding rules to allow needed traffic and re-enable the firewall.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Re-enable the firewall with its desired configurations.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Review the privileges assigned to the involved users to ensure that the least privilege principle is being followed.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Windows Firewall Disabled via PowerShell\n\nWindows Defender Firewall is a native component that provides host-based, two-way network traffic filtering for a\ndevice and blocks unauthorized network traffic flowing into or out of the local device.\n\nAttackers can disable the Windows firewall or its rules to enable lateral movement and command and control activity.\n\nThis rule identifies patterns related to disabling the Windows firewall or its rules using the `Set-NetFirewallProfile`\nPowerShell cmdlet.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Check whether the user is an administrator and is legitimately performing\ntroubleshooting.\n- In case of an allowed benign true positive (B-TP), assess adding rules to allow needed traffic and re-enable the firewall.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Re-enable the firewall with its desired configurations.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Review the privileges assigned to the involved users to ensure that the least privilege principle is being followed.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.action == \"start\" and\n (process.name : (\"powershell.exe\", \"pwsh.exe\", \"powershell_ise.exe\") or process.pe.original_file_name == \"PowerShell.EXE\") and\n process.args : \"*Set-NetFirewallProfile*\" and\n (process.args : \"*-Enabled*\" and process.args : \"*False*\") and\n (process.args : \"*-All*\" or process.args : (\"*Public*\", \"*Domain*\", \"*Private*\"))\n", "references": [ "https://docs.microsoft.com/en-us/powershell/module/netsecurity/set-netfirewallprofile?view=windowsserver2019-ps", @@ -54,7 +54,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -82,5 +83,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_access_direct_syscall.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_access_direct_syscall.json index ee61888d446e1..d7f255f981c3a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_access_direct_syscall.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_access_direct_syscall.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious Process Access via Direct System Call", - "note": "## Triage and analysis\n\n### Investigating Suspicious Process Access via Direct System Call\n\nEndpoint security solutions usually hook userland Windows APIs in order to decide if the code that is being executed is\nmalicious or not. It's possible to bypass hooked functions by writing malicious functions that call syscalls directly.\n\nMore context and technical details can be found in this [research blog](https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-av-edr/).\n\nThis rule identifies suspicious process access events from an unknown memory region. Attackers can use direct system\ncalls to bypass security solutions that rely on hooks.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This detection may be triggered by certain applications that install root certificates for the purpose of inspecting\nSSL traffic. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove the malicious certificate from the root certificate store.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious Process Access via Direct System Call\n\nEndpoint security solutions usually hook userland Windows APIs in order to decide if the code that is being executed is\nmalicious or not. It's possible to bypass hooked functions by writing malicious functions that call syscalls directly.\n\nMore context and technical details can be found in this [research blog](https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-av-edr/).\n\nThis rule identifies suspicious process access events from an unknown memory region. Attackers can use direct system\ncalls to bypass security solutions that rely on hooks.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This detection may be triggered by certain applications that install root certificates for the purpose of inspecting\nSSL traffic. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove the malicious certificate from the root certificate store.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.code == \"10\" and\n length(winlog.event_data.CallTrace) > 0 and\n\n /* Sysmon CallTrace starting with unknown memory module instead of ntdll which host Windows NT Syscalls */\n not winlog.event_data.CallTrace :\n (\"?:\\\\WINDOWS\\\\SYSTEM32\\\\ntdll.dll*\",\n \"?:\\\\WINDOWS\\\\SysWOW64\\\\ntdll.dll*\",\n \"?:\\\\Windows\\\\System32\\\\wow64cpu.dll*\",\n \"?:\\\\WINDOWS\\\\System32\\\\wow64win.dll*\",\n \"?:\\\\Windows\\\\System32\\\\win32u.dll*\") and\n\n not winlog.event_data.TargetImage :\n (\"?:\\\\Program Files (x86)\\\\Malwarebytes Anti-Exploit\\\\mbae-svc.exe\",\n \"?:\\\\Program Files\\\\Cisco\\\\AMP\\\\*\\\\sfc.exe\",\n \"?:\\\\Program Files (x86)\\\\Microsoft\\\\EdgeWebView\\\\Application\\\\*\\\\msedgewebview2.exe\",\n \"?:\\\\Program Files\\\\Adobe\\\\Acrobat DC\\\\Acrobat\\\\*\\\\AcroCEF.exe\") and\n\n not (process.executable : (\"?:\\\\Program Files\\\\Adobe\\\\Acrobat DC\\\\Acrobat\\\\Acrobat.exe\",\n \"?:\\\\Program Files (x86)\\\\World of Warcraft\\\\_classic_\\\\WowClassic.exe\") and\n not winlog.event_data.TargetImage : \"?:\\\\WINDOWS\\\\system32\\\\lsass.exe\")\n", "references": [ "https://twitter.com/SBousseaden/status/1278013896440324096", @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -69,5 +70,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_creation_calltrace.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_creation_calltrace.json index 76e62528a181c..71090cbe65b64 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_creation_calltrace.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_suspicious_process_creation_calltrace.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Identifies when a process is created and immediately accessed from an unknown memory code region and by the same parent process. This may indicate a code injection or hollowing attempt.", + "description": "Identifies when a process is created and immediately accessed from an unknown memory code region and by the same parent process. This may indicate a code injection attempt.", "from": "now-9m", "index": [ "winlogbeat-*", @@ -11,6 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious Process Creation CallTrace", + "note": "## Triage and analysis\n\n### Investigating Suspicious Process Creation CallTrace\n\nAttackers may inject code into child processes' memory to hide their actual activity, evade detection mechanisms, and\ndecrease discoverability during forensics. This rule looks for a spawned process by Microsoft Office, scripting, and\ncommand line applications, followed by a process access event for an unknown memory region by the parent process, which\ncan indicate a code injection attempt.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behavior observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Create a memory dump of the child process for analysis.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by host.id with maxspan=1m\n [process where event.code == \"1\" and\n /* sysmon process creation */\n process.parent.name : (\"winword.exe\", \"excel.exe\", \"outlook.exe\", \"powerpnt.exe\", \"eqnedt32.exe\", \"fltldr.exe\",\n \"mspub.exe\", \"msaccess.exe\",\"cscript.exe\", \"wscript.exe\", \"rundll32.exe\", \"regsvr32.exe\",\n \"mshta.exe\", \"wmic.exe\", \"cmstp.exe\", \"msxsl.exe\") and\n\n /* noisy FP patterns */\n not (process.parent.name : \"EXCEL.EXE\" and process.executable : \"?:\\\\Program Files\\\\Microsoft Office\\\\root\\\\Office*\\\\ADDINS\\\\*.exe\") and\n not (process.executable : \"?:\\\\Windows\\\\splwow64.exe\" and process.args in (\"8192\", \"12288\") and process.parent.name : (\"winword.exe\", \"excel.exe\", \"outlook.exe\", \"powerpnt.exe\")) and\n not (process.parent.name : \"rundll32.exe\" and process.parent.args : (\"?:\\\\WINDOWS\\\\Installer\\\\MSI*.tmp,zzzzInvokeManagedCustomActionOutOfProc\", \"--no-sandbox\")) and\n not (process.executable :\n (\"?:\\\\Program Files (x86)\\\\Microsoft\\\\EdgeWebView\\\\Application\\\\*\\\\msedgewebview2.exe\",\n \"?:\\\\Program Files\\\\Adobe\\\\Acrobat DC\\\\Acrobat\\\\Acrobat.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\DWWIN.EXE\") and\n process.parent.name : (\"winword.exe\", \"excel.exe\", \"outlook.exe\", \"powerpnt.exe\")) and\n not (process.parent.name : \"regsvr32.exe\" and process.parent.args : (\"?:\\\\Program Files\\\\*\", \"?:\\\\Program Files (x86)\\\\*\"))\n ] by process.parent.entity_id, process.entity_id\n [process where event.code == \"10\" and\n /* Sysmon process access event from unknown module */\n winlog.event_data.CallTrace : \"*UNKNOWN*\"] by process.entity_id, winlog.event_data.TargetProcessGUID\n", "required_fields": [ { @@ -92,5 +93,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_system_critical_proc_abnormal_file_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_system_critical_proc_abnormal_file_activity.json index 2a39c7a7961f0..2e44936da71b2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_system_critical_proc_abnormal_file_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_system_critical_proc_abnormal_file_activity.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Unusual Executable File Creation by a System Critical Process", - "note": "## Triage and analysis\n\n### Investigating Unusual Executable File Creation by a System Critical Process\n\nWindows internal/system processes have some characteristics that can be used to spot suspicious activities. One of these\ncharacteristics is file operations.\n\nThis rule looks for the creation of executable files done by system-critical processes. This can indicate the exploitation\nof a vulnerability or a malicious process masquerading as a system-critical process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Unusual Executable File Creation by a System Critical Process\n\nWindows internal/system processes have some characteristics that can be used to spot suspicious activities. One of these\ncharacteristics is file operations.\n\nThis rule looks for the creation of executable files done by system-critical processes. This can indicate the exploitation\nof a vulnerability or a malicious process masquerading as a system-critical process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type != \"deletion\" and\n file.extension : (\"exe\", \"dll\") and\n process.name : (\"smss.exe\",\n \"autochk.exe\",\n \"csrss.exe\",\n \"wininit.exe\",\n \"services.exe\",\n \"lsass.exe\",\n \"winlogon.exe\",\n \"userinit.exe\",\n \"LogonUI.exe\")\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -61,5 +62,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_ads_file_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_ads_file_creation.json index 5892ec0a1e44b..e9d8c440038b7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_ads_file_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_ads_file_creation.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Unusual File Creation - Alternate Data Stream", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Unusual File Creation - Alternate Data Stream\n\nAlternate Data Streams (ADS) are file attributes only found on the NTFS file system. In this file system, files are\nbuilt up from a couple of attributes; one of them is $Data, also known as the data attribute.\n\nThe regular data stream, also referred to as the unnamed data stream since the name string of this attribute is empty,\ncontains the data inside the file. So any data stream that has a name is considered an alternate data stream.\n\nAttackers can abuse these alternate data streams to hide malicious files, string payloads, etc. This rule detects the\ncreation of alternate data streams on highly targeted file types.\n\n#### Possible investigation steps\n\n- Retrieve the contents of the alternate data stream, and analyze it for potential maliciousness. Analysts can use the\nfollowing PowerShell cmdlet to accomplish this:\n - `Get-Content -file C:\\Path\\To\\file.exe -stream ADSname`\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- If this activity is expected and noisy in your environment, consider adding exceptions \u2014 preferably with a combination\nof process executable and file conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type == \"creation\" and\n\n file.path : \"C:\\\\*:*\" and\n not file.path : \"C:\\\\*:zone.identifier*\" and\n\n not process.executable :\n (\"?:\\\\windows\\\\System32\\\\svchost.exe\",\n \"?:\\\\Windows\\\\System32\\\\inetsrv\\\\w3wp.exe\",\n \"?:\\\\Windows\\\\explorer.exe\",\n \"?:\\\\Windows\\\\System32\\\\sihost.exe\",\n \"?:\\\\Windows\\\\System32\\\\PickerHost.exe\",\n \"?:\\\\Windows\\\\System32\\\\SearchProtocolHost.exe\",\n \"?:\\\\Program Files (x86)\\\\Dropbox\\\\Client\\\\Dropbox.exe\",\n \"?:\\\\Program Files\\\\Rivet Networks\\\\SmartByte\\\\SmartByteNetworkService.exe\",\n \"?:\\\\Program Files (x86)\\\\Microsoft\\\\Edge\\\\Application\\\\msedge.exe\",\n \"?:\\\\Program Files\\\\ExpressConnect\\\\ExpressConnectNetworkService.exe\",\n \"?:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"?:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"?:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\") and\n\n file.extension :\n (\n \"pdf\",\n \"dll\",\n \"png\",\n \"exe\",\n \"dat\",\n \"com\",\n \"bat\",\n \"cmd\",\n \"sys\",\n \"vbs\",\n \"ps1\",\n \"hta\",\n \"txt\",\n \"vbe\",\n \"js\",\n \"wsh\",\n \"docx\",\n \"doc\",\n \"xlsx\",\n \"xls\",\n \"pptx\",\n \"ppt\",\n \"rtf\",\n \"gif\",\n \"jpg\",\n \"png\",\n \"bmp\",\n \"img\",\n \"iso\"\n )\n", "required_fields": [ { @@ -73,5 +73,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_network_connection_via_rundll32.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_network_connection_via_rundll32.json index 9ea550212840e..7afc341466d9e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_network_connection_via_rundll32.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_network_connection_via_rundll32.json @@ -58,7 +58,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_process_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_process_network_connection.json index 6b0299f2e5cd5..c93d6b9eb7045 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_process_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_unusual_process_network_connection.json @@ -39,7 +39,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { @@ -59,5 +60,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_workfolders_control_execution.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_workfolders_control_execution.json index 614bfead11cd3..aeaba22f4b281 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_workfolders_control_execution.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_workfolders_control_execution.json @@ -50,7 +50,8 @@ "Host", "Windows", "Threat Detection", - "Defense Evasion" + "Defense Evasion", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_adfind_command_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_adfind_command_activity.json index 00229a55fadc8..fa27159b49fd1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_adfind_command_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_adfind_command_activity.json @@ -53,7 +53,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_admin_recon.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_admin_recon.json index 13d3d85f47363..76d95e51f4692 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_admin_recon.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_admin_recon.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Enumeration of Administrator Accounts", - "note": "## Triage and analysis\n\n### Investigating Enumeration of Administrator Accounts\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `net` and `wmic` utilities to enumerate administrator-related users or groups\nin the domain and local machine scope. Attackers can use this information to plan their next steps of the attack, such\nas mapping targets for credential compromise and other post-exploitation activities.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Related rules\n\n- AdFind Command Activity - eda499b8-a073-4e35-9733-22ec71f57f3a\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Enumeration of Administrator Accounts\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `net` and `wmic` utilities to enumerate administrator-related users or groups\nin the domain and local machine scope. Attackers can use this information to plan their next steps of the attack, such\nas mapping targets for credential compromise and other post-exploitation activities.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Related rules\n\n- AdFind Command Activity - eda499b8-a073-4e35-9733-22ec71f57f3a\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (((process.name : \"net.exe\" or process.pe.original_file_name == \"net.exe\") or\n ((process.name : \"net1.exe\" or process.pe.original_file_name == \"net1.exe\") and\n not process.parent.name : \"net.exe\")) and\n process.args : (\"group\", \"user\", \"localgroup\") and\n process.args : (\"admin\", \"Domain Admins\", \"Remote Desktop Users\", \"Enterprise Admins\", \"Organization Management\") and\n not process.args : \"/add\")\n\n or\n\n ((process.name : \"wmic.exe\" or process.pe.original_file_name == \"wmic.exe\") and\n process.args : (\"group\", \"useraccount\"))\n", "required_fields": [ { @@ -50,7 +50,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_command_system_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_command_system_account.json index 938ed63bb184f..e0f2daaefa5ab 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_command_system_account.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_command_system_account.json @@ -50,7 +50,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_view.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_view.json index a8d08a029cd2f..38779d72a19d4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_view.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_view.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Windows Network Enumeration", - "note": "## Triage and analysis\n\n### Investigating Windows Network Enumeration\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `net` utility to enumerate servers in the environment that hosts shared drives\nor printers. This information is useful to attackers as they can identify targets for lateral movements and search for\nvaluable shared data.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Windows Network Enumeration\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `net` utility to enumerate servers in the environment that hosts shared drives\nor printers. This information is useful to attackers as they can identify targets for lateral movements and search for\nvaluable shared data.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n ((process.name : \"net.exe\" or process.pe.original_file_name == \"net.exe\") or\n ((process.name : \"net1.exe\" or process.pe.original_file_name == \"net1.exe\") and\n not process.parent.name : \"net.exe\")) and\n (process.args : \"view\" or (process.args : \"time\" and process.args : \"\\\\\\\\*\"))\n\n\n /* expand when ancestry is available\n and not descendant of [process where event.type == \"start\" and process.name : \"cmd.exe\" and\n ((process.parent.name : \"userinit.exe\") or\n (process.parent.name : \"gpscript.exe\") or\n (process.parent.name : \"explorer.exe\" and\n process.args : \"C:\\\\*\\\\Start Menu\\\\Programs\\\\Startup\\\\*.bat*\"))]\n */\n", "required_fields": [ { @@ -50,7 +50,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_peripheral_device.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_peripheral_device.json index 9a8fd5df2687a..08d44e6911cae 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_peripheral_device.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_peripheral_device.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Peripheral Device Discovery", - "note": "## Triage and analysis\n\n### Investigating Peripheral Device Discovery\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `fsutil` utility with the `fsinfo` subcommand to enumerate drives attached to\nthe computer, which can be used to identify secondary drives used for backups, mapped network drives, and removable\nmedia. These devices can contain valuable information for attackers.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n- Determine whether this activity was followed by suspicious file access/copy operations or uploads to file storage\nservices.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Peripheral Device Discovery\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `fsutil` utility with the `fsinfo` subcommand to enumerate drives attached to\nthe computer, which can be used to identify secondary drives used for backups, mapped network drives, and removable\nmedia. These devices can contain valuable information for attackers.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Determine whether this activity was followed by suspicious file access/copy operations or uploads to file storage\nservices.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name : \"fsutil.exe\" or process.pe.original_file_name == \"fsutil.exe\") and\n process.args : \"fsinfo\" and process.args : \"drives\"\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_invoke_sharefinder.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_invoke_sharefinder.json index c4c07e84c0e20..cd5b4ebbdf9f2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_invoke_sharefinder.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_invoke_sharefinder.json @@ -11,7 +11,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "PowerShell Share Enumeration Script", - "note": "", + "note": "## Triage and analysis\n\n### Investigating PowerShell Share Enumeration Script\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can use PowerShell to enumerate shares to search for sensitive data like documents, scripts, and other kinds\nof valuable data for encryption, exfiltration, and lateral movement.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Check for additional PowerShell and command line logs that indicate that imported functions were run.\n - Evaluate which information was potentially mapped and accessed by the attacker.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "event.category:process and\n powershell.file.script_block_text:(\n \"Invoke-ShareFinder\" or\n \"Invoke-ShareFinderThreaded\" or\n (\n \"shi1_netname\" and\n \"shi1_remark\"\n ) or\n (\n \"NetShareEnum\" and\n \"NetApiBufferFree\"\n )\n )\n", "references": [ "https://www.advintel.io/post/hunting-for-corporate-insurance-policies-indicators-of-ransom-exfiltrations", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_suspicious_api_functions.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_suspicious_api_functions.json index 5d584a1eed8e1..cc587ddbf8315 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_suspicious_api_functions.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_posh_suspicious_api_functions.json @@ -41,7 +41,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { @@ -101,5 +102,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_post_exploitation_external_ip_lookup.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_post_exploitation_external_ip_lookup.json index 6724b509809c2..271d3736b125c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_post_exploitation_external_ip_lookup.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_post_exploitation_external_ip_lookup.json @@ -59,7 +59,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { @@ -92,5 +93,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_privileged_localgroup_membership.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_privileged_localgroup_membership.json index ca21e6cf9077c..5c81974ec6ce3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_privileged_localgroup_membership.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_privileged_localgroup_membership.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Enumeration of Privileged Local Groups Membership", - "note": "## Triage and analysis\n\n### Investigating Enumeration of Privileged Local Groups Membership\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the enumeration of privileged local groups' membership by suspicious processes, and excludes known\nlegitimate utilities and programs installed. Attackers can use this information to decide the next steps of the attack,\nsuch as mapping targets for credential compromise and other post-exploitation activities.\n\n#### Possible investigation steps\n\n- Identify the process, host and user involved on the event.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n- Retrieve the process executable and determine if it is malicious:\n - Check if the file belongs to the operating system or has a valid digital signature.\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\nThe 'Audit Security Group Management' audit policy must be configured (Success).\nSteps to implement the logging policy with with Advanced Audit Configuration:\n\n```\nComputer Configuration >\nPolicies >\nWindows Settings >\nSecurity Settings >\nAdvanced Audit Policies Configuration >\nAudit Policies >\nAccount Management >\nAudit Security Group Management (Success)\n```\n\nMicrosoft introduced the [event used](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4799) in this detection rule on Windows 10 and Windows Server 2016 or later operating systems.\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", + "note": "## Triage and analysis\n\n### Investigating Enumeration of Privileged Local Groups Membership\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the enumeration of privileged local groups' membership by suspicious processes, and excludes known\nlegitimate utilities and programs installed. Attackers can use this information to decide the next steps of the attack,\nsuch as mapping targets for credential compromise and other post-exploitation activities.\n\n#### Possible investigation steps\n\n- Identify the process, host and user involved on the event.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Retrieve the process executable and determine if it is malicious:\n - Check if the file belongs to the operating system or has a valid digital signature.\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\nThe 'Audit Security Group Management' audit policy must be configured (Success).\nSteps to implement the logging policy with with Advanced Audit Configuration:\n\n```\nComputer Configuration >\nPolicies >\nWindows Settings >\nSecurity Settings >\nAdvanced Audit Policies Configuration >\nAudit Policies >\nAccount Management >\nAudit Security Group Management (Success)\n```\n\nMicrosoft introduced the [event used](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4799) in this detection rule on Windows 10 and Windows Server 2016 or later operating systems.\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", "query": "iam where event.action == \"user-member-enumerated\" and\n\n /* excluding machine account */\n not winlog.event_data.SubjectUserName: (\"*$\", \"LOCAL SERVICE\", \"NETWORK SERVICE\") and\n\n /* noisy and usual legit processes excluded */\n not winlog.event_data.CallerProcessName:\n (\"-\",\n \"?:\\\\Windows\\\\System32\\\\VSSVC.exe\",\n \"?:\\\\Windows\\\\System32\\\\SearchIndexer.exe\",\n \"?:\\\\Windows\\\\System32\\\\CompatTelRunner.exe\",\n \"?:\\\\Windows\\\\System32\\\\oobe\\\\msoobe.exe\",\n \"?:\\\\Windows\\\\System32\\\\net1.exe\",\n \"?:\\\\Windows\\\\System32\\\\svchost.exe\",\n \"?:\\\\Windows\\\\System32\\\\Netplwiz.exe\",\n \"?:\\\\Windows\\\\System32\\\\msiexec.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\msiexec.exe\",\n \"?:\\\\Windows\\\\System32\\\\CloudExperienceHostBroker.exe\",\n \"?:\\\\Windows\\\\System32\\\\wbem\\\\WmiPrvSE.exe\",\n \"?:\\\\Windows\\\\System32\\\\SrTasks.exe\",\n \"?:\\\\Windows\\\\System32\\\\lsass.exe\",\n \"?:\\\\Windows\\\\System32\\\\diskshadow.exe\",\n \"?:\\\\Windows\\\\System32\\\\dfsrs.exe\",\n \"?:\\\\Program Files\\\\*.exe\",\n \"?:\\\\Program Files (x86)\\\\*.exe\",\n \"?:\\\\WindowsAzure\\\\*\\\\WaAppAgent.exe\",\n \"?:\\\\Windows\\\\System32\\\\vssadmin.exe\",\n \"?:\\\\Windows\\\\VeeamVssSupport\\\\VeeamGuestHelper.exe\",\n \"?:\\\\Windows\\\\System32\\\\dllhost.exe\",\n \"?:\\\\Windows\\\\System32\\\\mmc.exe\",\n \"?:\\\\Windows\\\\System32\\\\SettingSyncHost.exe\",\n \"?:\\\\Windows\\\\ImmersiveControlPanel\\\\SystemSettings.exe\",\n \"?:\\\\Windows\\\\System32\\\\SystemSettingsAdminFlows.exe\",\n \"?:\\\\Windows\\\\Temp\\\\rubrik_vmware???\\\\snaptool.exe\",\n \"?:\\\\Windows\\\\System32\\\\inetsrv\\\\w3wp.exe\",\n \"?:\\\\$WINDOWS.~BT\\\\Sources\\\\*.exe\",\n \"?:\\\\Windows\\\\System32\\\\wsmprovhost.exe\",\n \"?:\\\\Windows\\\\System32\\\\spool\\\\drivers\\\\x64\\\\3\\\\x3jobt3?.exe\",\n \"?:\\\\Windows\\\\System32\\\\mstsc.exe\",\n \"?:\\\\Windows\\\\System32\\\\esentutl.exe\",\n \"?:\\\\Windows\\\\System32\\\\RecoveryDrive.exe\",\n \"?:\\\\Windows\\\\System32\\\\SystemPropertiesComputerName.exe\") and\n\n /* privileged local groups */\n (group.name:(\"admin*\",\"RemoteDesktopUsers\") or\n winlog.event_data.TargetSid:(\"S-1-5-32-544\",\"S-1-5-32-555\"))\n", "required_fields": [ { @@ -49,7 +49,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { @@ -77,5 +78,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_remote_system_discovery_commands_windows.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_remote_system_discovery_commands_windows.json index 2378e0c21b4e6..e0bf3a485e835 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_remote_system_discovery_commands_windows.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_remote_system_discovery_commands_windows.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote System Discovery Commands", - "note": "## Triage and analysis\n\n### Investigating Remote System Discovery Commands\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `arp` or `nbstat` utilities to enumerate remote systems in the environment,\nwhich is useful for attackers to identify lateral movement targets.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Remote System Discovery Commands\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `arp` or `nbstat` utilities to enumerate remote systems in the environment,\nwhich is useful for attackers to identify lateral movement targets.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n ((process.name : \"nbtstat.exe\" and process.args : (\"-n\", \"-s\")) or\n (process.name : \"arp.exe\" and process.args : \"-a\"))\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_grep.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_grep.json index 1d81253496323..dbed80d94bef8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_grep.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_grep.json @@ -14,7 +14,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Security Software Discovery via Grep", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Security Software Discovery via Grep\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `grep` utility with arguments compatible to the enumeration of the security\nsoftware installed on the host. Attackers can use this information to decide whether or not to infect a system, disable\nprotections, use bypasses, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence and whether they are located in expected locations.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, file modifications, and any\nspawned child processes.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\nprocess.name : \"grep\" and user.id != \"0\" and\n not process.parent.executable : \"/Library/Application Support/*\" and\n process.args :\n (\"Little Snitch*\",\n \"Avast*\",\n \"Avira*\",\n \"ESET*\",\n \"BlockBlock*\",\n \"360Sec*\",\n \"LuLu*\",\n \"KnockKnock*\",\n \"kav\",\n \"KIS\",\n \"RTProtectionDaemon*\",\n \"Malware*\",\n \"VShieldScanner*\",\n \"WebProtection*\",\n \"webinspectord*\",\n \"McAfee*\",\n \"isecespd*\",\n \"macmnsvc*\",\n \"masvc*\",\n \"kesl*\",\n \"avscan*\",\n \"guard*\",\n \"rtvscand*\",\n \"symcfgd*\",\n \"scmdaemon*\",\n \"symantec*\",\n \"sophos*\",\n \"osquery*\",\n \"elastic-endpoint*\"\n ) and\n not (process.args : \"Avast\" and process.args : \"Passwords\")\n", "required_fields": [ { @@ -81,5 +81,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_wmic.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_wmic.json index 4c4b1e6127340..5e0d757a0c232 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_wmic.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_security_software_wmic.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Security Software Discovery using WMIC", - "note": "## Triage and analysis\n\n### Investigating Security Software Discovery using WMIC\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `wmic` utility with arguments compatible to the enumeration of the security\nsoftware installed on the host. Attackers can use this information to decide whether or not to infect a system, disable\nprotections, use bypasses, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Security Software Discovery using WMIC\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `wmic` utility with arguments compatible to the enumeration of the security\nsoftware installed on the host. Attackers can use this information to decide whether or not to infect a system, disable\nprotections, use bypasses, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name:\"wmic.exe\" or process.pe.original_file_name:\"wmic.exe\") and\n process.args:\"/namespace:\\\\\\\\root\\\\SecurityCenter2\" and process.args:\"Get\"\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json index 801024ec2f04a..f27272de5cee0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json @@ -16,7 +16,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Whoami Process Activity", - "note": "## Triage and analysis\n\n### Investigating Whoami Process Activity\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `whoami` utility. Attackers commonly use this utility to measure their current\nprivileges, discover the current user, determine if a privilege escalation was successful, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed using the account, such as commands executed, files created or modified, and\nnetwork connections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Related rules\n\n- Account Discovery Command via SYSTEM Account - 2856446a-34e6-435b-9fb5-f8f040bfa7ed\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection via the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Whoami Process Activity\n\nAfter successfully compromising an environment, attackers may try to gain situational awareness to plan their next steps.\nThis can happen by running commands to enumerate network resources, users, connections, files, and installed security\nsoftware.\n\nThis rule looks for the execution of the `whoami` utility. Attackers commonly use this utility to measure their current\nprivileges, discover the current user, determine if a privilege escalation was successful, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n\n### False positive analysis\n\n- Discovery activities are not inherently malicious if they occur in isolation. As long as the analyst did not identify\nsuspicious activity related to the user or host, such alerts can be dismissed.\n\n### Related rules\n\n- Account Discovery Command via SYSTEM Account - 2856446a-34e6-435b-9fb5-f8f040bfa7ed\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and process.name : \"whoami.exe\" and\n(\n\n (/* scoped for whoami execution under system privileges */\n (user.domain : (\"NT AUTHORITY\", \"NT-AUTORIT\u00c4T\", \"AUTORITE NT\", \"IIS APPPOOL\") or user.id : (\"S-1-5-18\", \"S-1-5-19\", \"S-1-5-20\")) and\n\n not (process.parent.name : \"cmd.exe\" and\n process.parent.args : (\"chcp 437>nul 2>&1 & C:\\\\WINDOWS\\\\System32\\\\whoami.exe /groups\",\n \"chcp 437>nul 2>&1 & %systemroot%\\\\system32\\\\whoami /user\",\n \"C:\\\\WINDOWS\\\\System32\\\\whoami.exe /groups\",\n \"*WINDOWS\\\\system32\\\\config\\\\systemprofile*\")) and\n not (process.parent.executable : \"C:\\\\Windows\\\\system32\\\\inetsrv\\\\appcmd.exe\" and process.parent.args : \"LIST\") and\n not process.parent.executable : (\"C:\\\\Program Files\\\\Microsoft Monitoring Agent\\\\Agent\\\\MonitoringHost.exe\",\n \"C:\\\\Program Files\\\\Cohesity\\\\cohesity_windows_agent_service.exe\")) or\n\n process.parent.name : (\"wsmprovhost.exe\", \"w3wp.exe\", \"wmiprvse.exe\", \"rundll32.exe\", \"regsvr32.exe\")\n\n)\n", "required_fields": [ { @@ -64,7 +64,8 @@ "Host", "Windows", "Threat Detection", - "Discovery" + "Discovery", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_abnormal_process_id_file_created.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_abnormal_process_id_file_created.json index 6389a8a3ab80d..785c950719b8f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_abnormal_process_id_file_created.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_abnormal_process_id_file_created.json @@ -13,7 +13,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Abnormal Process ID or Lock File Created", - "note": "## Triage and analysis\n\n### Investigating Abnormal Process ID or Lock File Created\nDetection alerts from this rule indicate that an unusual PID file was created and could potentially have alternate purposes during an intrusion. Here are some possible avenues of investigation:\n- Run the following in Osquery to quickly identify unsual PID file size: \"SELECT f.size, f.uid, f.type, f.path from file f WHERE path like '/var/run/%pid';\"\n- Examine the history of this file creation and from which process it was created by using the \"lsof\" command.\n- Examine the contents of the PID file itself, simply by running the \"cat\" command to determine if the expected process ID integer exists and if not, the PID file is not legitimate.\n- Examine the reputation of the SHA256 hash from the PID file in a database like VirusTotal to identify additional pivots and artifacts for investigation.", + "note": "## Triage and analysis\n\n### Investigating Abnormal Process ID or Lock File Created\n\nLinux applications may need to save their process identification number (PID) for various purposes: from signaling that\na program is running to serving as a signal that a previous instance of an application didn't exit successfully. PID\nfiles contain its creator process PID in an integer value.\n\nLinux lock files are used to coordinate operations in files so that conflicts and race conditions are prevented.\n\nThis rule identifies the creation of PID, lock, or reboot files in the /var/run/ directory. Attackers can masquerade\nmalware, payloads, staged data for exfiltration, and more as legitimate PID files.\n\n#### Possible investigation steps\n\n- Retrieve the file and determine if it is malicious:\n - Check the contents of the PID files. They should only contain integer strings.\n - Check the file type of the lock and PID files to determine if they are executables. This is only observed in\n malicious files.\n - Check the size of the subject file. Legitimate PID files should be under 10 bytes.\n - Check if the lock or PID file has high entropy. This typically indicates an encrypted payload.\n - Analysts can use tools like `ent` to measure entropy.\n - Examine the reputation of the SHA-256 hash in the PID file. Use a database like VirusTotal to identify additional\n pivots and artifacts for investigation.\n- Trace the file's creation to ensure it came from a legitimate or authorized process.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, file modifications, and any\nspawned child processes.\n\n### False positive analysis\n\n- False positives can appear if the PID file is legitimate and holding a process ID as intended. If the PID file is\nan executable or has a file size that's larger than 10 bytes, it should be ruled suspicious.\n- If this activity is expected and noisy in your environment, consider adding exceptions \u2014 preferably with a combination\nof file name and process executable conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Block the identified indicators of compromise (IoCs).\n- Take actions to terminate processes and connections used by the attacker.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "/* add file size filters when data is available */\nfile where event.type == \"creation\" and user.id == \"0\" and\n file.path regex~ \"\"\"/var/run/\\w+\\.(pid|lock|reboot)\"\"\" and file.extension in (\"pid\",\"lock\",\"reboot\") and\n\n /* handle common legitimate files */\n\n not file.name in (\n \"auditd.pid\",\n \"python*\",\n \"apport.pid\",\n \"apport.lock\",\n \"kworker*\",\n \"gdm3.pid\",\n \"sshd.pid\",\n \"acpid.pid\",\n \"unattended-upgrades.lock\",\n \"unattended-upgrades.pid\",\n \"cmd.pid\",\n \"cron*.pid\",\n \"yum.pid\",\n \"netconfig.pid\",\n \"docker.pid\",\n \"atd.pid\",\n \"lfd.pid\",\n \"atop.pid\",\n \"nginx.pid\",\n \"dhclient.pid\",\n \"smtpd.pid\",\n \"stunnel.pid\"\n )\n", "references": [ "https://www.sandflysecurity.com/blog/linux-file-masquerading-and-malicious-pids-sandfly-1-2-6-update/", @@ -77,5 +77,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_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 index c14551a7a751e..7cea863e990a2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Svchost spawning Cmd", - "note": "## Triage and analysis\n\n### Investigating Svchost spawning Cmd\n\nThe Service Host process (SvcHost) is a system process that can host one, or multiple, Windows services in the Windows\nNT family of operating systems. Note that `Svchost.exe` is reserved for use by the operating system and should not be\nused by non-Windows services.\n\nThis rule looks for the creation of the `cmd.exe` process with `svchost.exe` as its parent process. This is an unusual\nbehavior that can indicate the masquerading of a malicious process as `svchost.exe` or exploitation for privilege\nescalation.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Svchost spawning Cmd\n\nThe Service Host process (SvcHost) is a system process that can host one, or multiple, Windows services in the Windows\nNT family of operating systems. Note that `Svchost.exe` is reserved for use by the operating system and should not be\nused by non-Windows services.\n\nThis rule looks for the creation of the `cmd.exe` process with `svchost.exe` as its parent process. This is an unusual\nbehavior that can indicate the masquerading of a malicious process as `svchost.exe` or exploitation for privilege\nescalation.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n\n process.parent.name : \"svchost.exe\" and process.name : \"cmd.exe\" and\n\n not process.args :\n (\"??:\\\\Program Files\\\\Npcap\\\\CheckStatus.bat?\",\n \"?:\\\\Program Files\\\\Npcap\\\\CheckStatus.bat\",\n \"\\\\system32\\\\cleanmgr.exe\",\n \"?:\\\\Windows\\\\system32\\\\silcollector.cmd\",\n \"\\\\system32\\\\AppHostRegistrationVerifier.exe\",\n \"\\\\system32\\\\ServerManagerLauncher.exe\",\n \"dir\",\n \"?:\\\\Program Files\\\\*\",\n \"?:\\\\Program Files (x86)\\\\*\",\n \"?:\\\\Windows\\\\LSDeployment\\\\Lspush.exe\",\n \"(x86)\\\\FMAuditOnsite\\\\watchdog.bat\",\n \"?:\\\\ProgramData\\\\chocolatey\\\\bin\\\\choco-upgrade-all.bat\",\n \"Files\\\\Npcap\\\\CheckStatus.bat\") and\n\n /* very noisy pattern - bat or cmd script executed via scheduled tasks */\n not (process.parent.args : \"netsvcs\" and process.args : (\"?:\\\\*.bat\", \"?:\\\\*.cmd\"))\n", "references": [ "https://nasbench.medium.com/demystifying-the-svchost-exe-process-and-its-command-line-options-508e9114e747" @@ -53,7 +53,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { @@ -76,5 +77,5 @@ "timeline_title": "Comprehensive Process Timeline", "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_from_unusual_path_cmdline.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_from_unusual_path_cmdline.json index a63258dc96af6..2221085a9b518 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_from_unusual_path_cmdline.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_from_unusual_path_cmdline.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Execution from Unusual Directory - Command Line", - "note": "## Triage and analysis\n\nThis is related to the `Process Execution from an Unusual Directory rule`.", + "note": "## Triage and analysis\n\n### Investigating Execution from Unusual Directory - Command Line\n\nThis rule looks for the execution of scripts from unusual directories. Attackers can use system or application paths to\nhide malware and make the execution less suspicious.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Examine the command line to determine which commands or scripts were executed.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- If this activity is expected and noisy in your environment, consider adding exceptions \u2014 preferably with a combination\nof parent process executable and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n\nThis is related to the `Process Execution from an Unusual Directory rule`.", "query": "process where event.type == \"start\" and\n process.name : (\"wscript.exe\",\n \"cscript.exe\",\n \"rundll32.exe\",\n \"regsvr32.exe\",\n \"cmstp.exe\",\n \"RegAsm.exe\",\n \"installutil.exe\",\n \"mshta.exe\",\n \"RegSvcs.exe\",\n \"powershell.exe\",\n \"pwsh.exe\",\n \"cmd.exe\") and\n\n /* add suspicious execution paths here */\n process.args : (\"C:\\\\PerfLogs\\\\*\",\n \"C:\\\\Users\\\\Public\\\\*\",\n \"C:\\\\Windows\\\\Tasks\\\\*\",\n \"C:\\\\Intel\\\\*\",\n \"C:\\\\AMD\\\\Temp\\\\*\",\n \"C:\\\\Windows\\\\AppReadiness\\\\*\",\n \"C:\\\\Windows\\\\ServiceState\\\\*\",\n \"C:\\\\Windows\\\\security\\\\*\",\n \"C:\\\\Windows\\\\IdentityCRL\\\\*\",\n \"C:\\\\Windows\\\\Branding\\\\*\",\n \"C:\\\\Windows\\\\csc\\\\*\",\n \"C:\\\\Windows\\\\DigitalLocker\\\\*\",\n \"C:\\\\Windows\\\\en-US\\\\*\",\n \"C:\\\\Windows\\\\wlansvc\\\\*\",\n \"C:\\\\Windows\\\\Prefetch\\\\*\",\n \"C:\\\\Windows\\\\Fonts\\\\*\",\n \"C:\\\\Windows\\\\diagnostics\\\\*\",\n \"C:\\\\Windows\\\\TAPI\\\\*\",\n \"C:\\\\Windows\\\\INF\\\\*\",\n \"C:\\\\Windows\\\\System32\\\\Speech\\\\*\",\n \"C:\\\\windows\\\\tracing\\\\*\",\n \"c:\\\\windows\\\\IME\\\\*\",\n \"c:\\\\Windows\\\\Performance\\\\*\",\n \"c:\\\\windows\\\\intel\\\\*\",\n \"c:\\\\windows\\\\ms\\\\*\",\n \"C:\\\\Windows\\\\dot3svc\\\\*\",\n \"C:\\\\Windows\\\\panther\\\\*\",\n \"C:\\\\Windows\\\\RemotePackages\\\\*\",\n \"C:\\\\Windows\\\\OCR\\\\*\",\n \"C:\\\\Windows\\\\appcompat\\\\*\",\n \"C:\\\\Windows\\\\apppatch\\\\*\",\n \"C:\\\\Windows\\\\addins\\\\*\",\n \"C:\\\\Windows\\\\Setup\\\\*\",\n \"C:\\\\Windows\\\\Help\\\\*\",\n \"C:\\\\Windows\\\\SKB\\\\*\",\n \"C:\\\\Windows\\\\Vss\\\\*\",\n \"C:\\\\Windows\\\\servicing\\\\*\",\n \"C:\\\\Windows\\\\CbsTemp\\\\*\",\n \"C:\\\\Windows\\\\Logs\\\\*\",\n \"C:\\\\Windows\\\\WaaS\\\\*\",\n \"C:\\\\Windows\\\\twain_32\\\\*\",\n \"C:\\\\Windows\\\\ShellExperiences\\\\*\",\n \"C:\\\\Windows\\\\ShellComponents\\\\*\",\n \"C:\\\\Windows\\\\PLA\\\\*\",\n \"C:\\\\Windows\\\\Migration\\\\*\",\n \"C:\\\\Windows\\\\debug\\\\*\",\n \"C:\\\\Windows\\\\Cursors\\\\*\",\n \"C:\\\\Windows\\\\Containers\\\\*\",\n \"C:\\\\Windows\\\\Boot\\\\*\",\n \"C:\\\\Windows\\\\bcastdvr\\\\*\",\n \"C:\\\\Windows\\\\TextInput\\\\*\",\n \"C:\\\\Windows\\\\security\\\\*\",\n \"C:\\\\Windows\\\\schemas\\\\*\",\n \"C:\\\\Windows\\\\SchCache\\\\*\",\n \"C:\\\\Windows\\\\Resources\\\\*\",\n \"C:\\\\Windows\\\\rescache\\\\*\",\n \"C:\\\\Windows\\\\Provisioning\\\\*\",\n \"C:\\\\Windows\\\\PrintDialog\\\\*\",\n \"C:\\\\Windows\\\\PolicyDefinitions\\\\*\",\n \"C:\\\\Windows\\\\media\\\\*\",\n \"C:\\\\Windows\\\\Globalization\\\\*\",\n \"C:\\\\Windows\\\\L2Schemas\\\\*\",\n \"C:\\\\Windows\\\\LiveKernelReports\\\\*\",\n \"C:\\\\Windows\\\\ModemLogs\\\\*\",\n \"C:\\\\Windows\\\\ImmersiveControlPanel\\\\*\",\n \"C:\\\\$Recycle.Bin\\\\*\") and\n\n /* noisy FP patterns */\n\n not process.parent.executable : (\"C:\\\\WINDOWS\\\\System32\\\\DriverStore\\\\FileRepository\\\\*\\\\igfxCUIService*.exe\",\n \"C:\\\\Windows\\\\System32\\\\spacedeskService.exe\",\n \"C:\\\\Program Files\\\\Dell\\\\SupportAssistAgent\\\\SRE\\\\SRE.exe\") and\n not (process.name : \"rundll32.exe\" and\n process.args : (\"uxtheme.dll,#64\",\n \"PRINTUI.DLL,PrintUIEntry\",\n \"?:\\\\Windows\\\\System32\\\\FirewallControlPanel.dll,ShowNotificationDialog\",\n \"?:\\\\WINDOWS\\\\system32\\\\Speech\\\\SpeechUX\\\\sapi.cpl\",\n \"?:\\\\Windows\\\\system32\\\\shell32.dll,OpenAs_RunDLL\")) and\n\n not (process.name : \"cscript.exe\" and process.args : \"?:\\\\WINDOWS\\\\system32\\\\calluxxprovider.vbs\") and\n\n not (process.name : \"cmd.exe\" and process.args : \"?:\\\\WINDOWS\\\\system32\\\\powercfg.exe\" and process.args : \"?:\\\\WINDOWS\\\\inf\\\\PowerPlan.log\") and\n\n not (process.name : \"regsvr32.exe\" and process.args : \"?:\\\\Windows\\\\Help\\\\OEM\\\\scripts\\\\checkmui.dll\") and\n\n not (process.name : \"cmd.exe\" and\n process.parent.executable : (\"?:\\\\Windows\\\\System32\\\\oobe\\\\windeploy.exe\",\n \"?:\\\\Program Files (x86)\\\\ossec-agent\\\\wazuh-agent.exe\",\n \"?:\\\\Windows\\\\System32\\\\igfxCUIService.exe\",\n \"?:\\\\Windows\\\\Temp\\\\IE*.tmp\\\\IE*-support\\\\ienrcore.exe\"))\n", "required_fields": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_linux_netcat_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_linux_netcat_network_connection.json index bd0d4ee978b74..ce07c4a04bfca 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_linux_netcat_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_linux_netcat_network_connection.json @@ -14,6 +14,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Netcat Network Activity", + "note": "## Triage and analysis\n\n### Investigating Netcat Network Activity\n\nNetcat is a dual-use command line tool that can be used for various purposes, such as port scanning, file transfers, and\nconnection tests. Attackers can abuse its functionality for malicious purposes such creating bind shells or reverse\nshells to gain access to the target system.\n\nA reverse shell is a mechanism that's abused to connect back to an attacker-controlled system. It effectively redirects\nthe system's input and output and delivers a fully functional remote shell to the attacker. Even private systems are\nvulnerable since the connection is outgoing.\n\nA bind shell is a type of backdoor that attackers set up on the target host and binds to a specific port to listen for\nan incoming connection from the attacker.\n\nThis rule identifies potential reverse shell or bind shell activity using Netcat by checking for the execution of Netcat\nfollowed by a network connection.\n\n#### Possible investigation steps\n\n- Examine the command line to identify if the command is suspicious.\n- Extract and examine the target domain or IP address.\n - Check if the domain is newly registered or unexpected.\n - Check the reputation of the domain or IP address.\n - Scope other potentially compromised hosts in your environment by mapping hosts that also communicated with the\n domain or IP address.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, file modifications, and any\nspawned child processes.\n\n### False positive analysis\n\n- Netcat is a dual-use tool that can be used for benign or malicious activity. It is included in some Linux\ndistributions, so its presence is not necessarily suspicious. Some normal use of this program, while uncommon, may\noriginate from scripts, automation tools, and frameworks.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Block the identified indicators of compromise (IoCs).\n- Take actions to terminate processes and connections used by the attacker.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by process.entity_id\n [process where (process.name == \"nc\" or process.name == \"ncat\" or process.name == \"netcat\" or\n process.name == \"netcat.openbsd\" or process.name == \"netcat.traditional\") and\n event.type == \"start\"]\n [network where (process.name == \"nc\" or process.name == \"ncat\" or process.name == \"netcat\" or\n process.name == \"netcat.openbsd\" or process.name == \"netcat.traditional\")]\n", "references": [ "http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet", @@ -65,5 +66,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_ms_office_written_file.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_ms_office_written_file.json index eaad2e49cd4f7..89f6364c7571c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_ms_office_written_file.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_ms_office_written_file.json @@ -13,7 +13,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Execution of File Written or Modified by Microsoft Office", - "note": "## Triage and analysis\n\n### Investigating Execution of File Written or Modified by Microsoft Office\n\nMicrosoft Office is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently\ntargeted for initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThis rule searches for executable files written by MS Office applications executed in sequence. This is most likely the result\nof the execution of malicious documents or exploitation for initial access or privilege escalation. This rule can also detect\nsuspicious processes masquerading as the MS Office applications.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Execution of File Written or Modified by Microsoft Office\n\nMicrosoft Office is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently\ntargeted for initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThis rule searches for executable files written by MS Office applications executed in sequence. This is most likely the result\nof the execution of malicious documents or exploitation for initial access or privilege escalation. This rule can also detect\nsuspicious processes masquerading as the MS Office applications.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence with maxspan=2h\n [file where event.type != \"deletion\" and file.extension : \"exe\" and\n (process.name : \"WINWORD.EXE\" or\n process.name : \"EXCEL.EXE\" or\n process.name : \"OUTLOOK.EXE\" or\n process.name : \"POWERPNT.EXE\" or\n process.name : \"eqnedt32.exe\" or\n process.name : \"fltldr.exe\" or\n process.name : \"MSPUB.EXE\" or\n process.name : \"MSACCESS.EXE\")\n ] by host.id, file.path\n [process where event.type == \"start\"] by host.id, process.executable\n", "required_fields": [ { @@ -55,7 +55,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_pdf_written_file.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_pdf_written_file.json index 84871a5b9d608..e525b02a6efd5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_pdf_written_file.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_pdf_written_file.json @@ -13,7 +13,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Execution of File Written or Modified by PDF Reader", - "note": "## Triage and analysis\n\n### Investigating Execution of File Written or Modified by PDF Reader\n\nPDF is a common file type used in corporate environments and most machines have software to\nhandle these files. This creates a vector where attackers can exploit the engines and technology behind this class of\nsoftware for initial access or privilege escalation.\n\nThis rule searches for executable files written by PDF reader software and executed in sequence. This is most likely the\nresult of exploitation for privilege escalation or initial access. This rule can also detect suspicious processes masquerading as\nPDF readers.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the PDF documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Execution of File Written or Modified by PDF Reader\n\nPDF is a common file type used in corporate environments and most machines have software to\nhandle these files. This creates a vector where attackers can exploit the engines and technology behind this class of\nsoftware for initial access or privilege escalation.\n\nThis rule searches for executable files written by PDF reader software and executed in sequence. This is most likely the\nresult of exploitation for privilege escalation or initial access. This rule can also detect suspicious processes masquerading as\nPDF readers.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the PDF documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence with maxspan=2h\n [file where event.type != \"deletion\" and file.extension : \"exe\" and\n (process.name : \"AcroRd32.exe\" or\n process.name : \"rdrcef.exe\" or\n process.name : \"FoxitPhantomPDF.exe\" or\n process.name : \"FoxitReader.exe\") and\n not (file.name : \"FoxitPhantomPDF.exe\" or\n file.name : \"FoxitPhantomPDFUpdater.exe\" or\n file.name : \"FoxitReader.exe\" or\n file.name : \"FoxitReaderUpdater.exe\" or\n file.name : \"AcroRd32.exe\" or\n file.name : \"rdrcef.exe\")\n ] by host.id, file.path\n [process where event.type == \"start\"] by host.id, process.executable\n", "required_fields": [ { @@ -60,7 +60,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_portable_executable.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_portable_executable.json index 538dc16e045d3..50a63ceed93a2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_portable_executable.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_portable_executable.json @@ -11,7 +11,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "Suspicious Portable Executable Encoded in Powershell Script", - "note": "## Triage and analysis\n\n### Investigating Suspicious Portable Executable Encoded in Powershell Script\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can abuse PowerShell in-memory capabilities to inject executables into memory without touching the disk,\nbypassing file-based security protections. These executables are generally base64 encoded.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Reimage the host operating system or restore the compromised files to clean versions.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious Portable Executable Encoded in Powershell Script\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can abuse PowerShell in-memory capabilities to inject executables into memory without touching the disk,\nbypassing file-based security protections. These executables are generally base64 encoded.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics.\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n- PowerShell PSReflect Script - 56f2e9b5-4803-4e44-a0a4-a52dc79d57fe\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Reimage the host operating system or restore the compromised files to clean versions.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "event.category:process and\n powershell.file.script_block_text : (\n TVqQAAMAAAAEAAAA\n )\n", "references": [ "https://github.com/atc-project/atc-data/blob/master/docs/Logging_Policies/LP_0109_windows_powershell_script_block_log.md" @@ -37,7 +37,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { @@ -65,5 +66,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_psreflect.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_psreflect.json index e775d8bf73942..ac618f2a58cd4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_psreflect.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_posh_psreflect.json @@ -14,7 +14,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "PowerShell PSReflect Script", - "note": "## Triage and analysis\n\n### Investigating PowerShell PSReflect Script\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nPSReflect is a library that enables PowerShell to access win32 API functions in an uncomplicated way. It also helps to\ncreate enums and structs easily\u2014all without touching the disk.\n\nAlthough this is an interesting project for every developer and admin out there, it is mainly used in the red team and\nmalware tooling for its capabilities.\n\nDetecting the core implementation of PSReflect means detecting most of the tooling that uses Windows API through\nPowerShell, enabling defenders to discover tools being dropped in the environment.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. The\nscript content that may be split into multiple script blocks (you can use the field `powershell.file.script_block_id`\nfor filtering).\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Check for additional PowerShell and command-line logs that indicate that imported functions were run.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- PowerShell Suspicious Discovery Related Windows API Functions - 61ac3638-40a3-44b2-855a-985636ca985e\n- PowerShell Keylogging Script - bd2c86a0-8b61-4457-ab38-96943984e889\n- PowerShell Suspicious Script with Audio Capture Capabilities - 2f2f4939-0b34-40c2-a0a3-844eb7889f43\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n- PowerShell Suspicious Script with Screenshot Capabilities - 959a7353-1129-4aa7-9084-30746b256a70\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating PowerShell PSReflect Script\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nPSReflect is a library that enables PowerShell to access win32 API functions in an uncomplicated way. It also helps to\ncreate enums and structs easily\u2014all without touching the disk.\n\nAlthough this is an interesting project for every developer and admin out there, it is mainly used in the red team and\nmalware tooling for its capabilities.\n\nDetecting the core implementation of PSReflect means detecting most of the tooling that uses Windows API through\nPowerShell, enabling defenders to discover tools being dropped in the environment.\n\n#### Possible investigation steps\n\n- Examine the script content that triggered the detection; look for suspicious DLL imports, collection or exfiltration\ncapabilities, suspicious functions, encoded or compressed data, and other potentially malicious characteristics. The\nscript content that may be split into multiple script blocks (you can use the field `powershell.file.script_block_id`\nfor filtering).\n- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for\nprevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Check for additional PowerShell and command-line logs that indicate that imported functions were run.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Evaluate whether the user needs to use PowerShell to complete tasks.\n- Retrieve the script and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- PowerShell Suspicious Discovery Related Windows API Functions - 61ac3638-40a3-44b2-855a-985636ca985e\n- PowerShell Keylogging Script - bd2c86a0-8b61-4457-ab38-96943984e889\n- PowerShell Suspicious Script with Audio Capture Capabilities - 2f2f4939-0b34-40c2-a0a3-844eb7889f43\n- Potential Process Injection via PowerShell - 2e29e96a-b67c-455a-afe4-de6183431d0d\n- Suspicious .NET Reflection via PowerShell - e26f042e-c590-4e82-8e05-41e81bd822ad\n- PowerShell Suspicious Payload Encoded and Compressed - 81fe9dc6-a2d7-4192-a2d8-eed98afc766a\n- PowerShell Suspicious Script with Screenshot Capabilities - 959a7353-1129-4aa7-9084-30746b256a70\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Restrict PowerShell usage outside of IT and engineering business units using GPOs, AppLocker, Intune, or similar software.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "event.category:process and\n powershell.file.script_block_text:(\n \"New-InMemoryModule\" or\n \"Add-Win32Type\" or\n psenum or\n DefineDynamicAssembly or\n DefineDynamicModule or\n \"Reflection.TypeAttributes\" or\n \"Reflection.Emit.OpCodes\" or\n \"Reflection.Emit.CustomAttributeBuilder\" or\n \"Runtime.InteropServices.DllImportAttribute\"\n )\n", "references": [ "https://github.com/mattifestation/PSReflect/blob/master/PSReflect.psm1", @@ -41,7 +41,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { @@ -74,5 +75,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json index 72d8ed1fdaffc..a293878687a6e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json @@ -57,7 +57,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { @@ -93,5 +94,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_revershell_via_shell_cmd.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_revershell_via_shell_cmd.json index 85ed673ec33e6..fbefe7152d9c0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_revershell_via_shell_cmd.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_revershell_via_shell_cmd.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential Reverse Shell Activity via Terminal", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Potential Reverse Shell Activity via Terminal\n\nA reverse shell is a mechanism that's abused to connect back to an attacker-controlled system. It effectively redirects\nthe system's input and output and delivers a fully functional remote shell to the attacker. Even private systems are\nvulnerable since the connection is outgoing. This activity is typically the result of vulnerability exploitation,\nmalware infection, or penetration testing.\n\nThis rule identifies commands that are potentially related to reverse shell activities using shell applications.\n\n#### Possible investigation steps\n\n- Examine the command line and extract the target domain or IP address information.\n - Check if the domain is newly registered or unexpected.\n - Check the reputation of the domain or IP address.\n - Scope other potentially compromised hosts in your environment by mapping hosts that also communicated with the\n domain or IP address.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, file modifications, and any\nspawned child processes.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Any activity that triggered the alert and is not inherently\nmalicious must be monitored by the security team.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Take actions to terminate processes and connections used by the attacker.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type in (\"start\", \"process_started\") and\n process.name in (\"sh\", \"bash\", \"zsh\", \"dash\", \"zmodload\") and\n process.args : (\"*/dev/tcp/*\", \"*/dev/udp/*\", \"*zsh/net/tcp*\", \"*zsh/net/udp*\") and\n\n /* noisy FPs */\n not (process.parent.name : \"timeout\" and process.executable : \"/var/lib/docker/overlay*\") and\n not process.command_line : (\"*/dev/tcp/sirh_db/*\", \"*/dev/tcp/remoteiot.com/*\", \"*dev/tcp/elk.stag.one/*\", \"*dev/tcp/kafka/*\", \"*/dev/tcp/$0/$1*\", \"*/dev/tcp/127.*\", \"*/dev/udp/127.*\", \"*/dev/tcp/localhost/*\") and\n not process.parent.command_line : \"runc init\"\n", "references": [ "https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md", @@ -86,5 +86,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_jar_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_jar_child_process.json index 629a5b1f21401..5e742ae4ed4bb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_jar_child_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_jar_child_process.json @@ -11,7 +11,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious JAVA Child Process", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Suspicious Java Child Process\n\nThis rule identifies a suspicious child process of the Java interpreter process. It may indicate an attempt to execute\na malicious JAR file or an exploitation attempt via a Java specific vulnerability.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence and whether they are located in expected locations.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, file modifications, and any\nspawned child processes.\n- Examine the command line to determine if the command executed is potentially harmful or malicious.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n\n### False positive analysis\n\n- If this activity is expected and noisy in your environment, consider adding exceptions \u2014 preferably with a combination\nof process and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type in (\"start\", \"process_started\") and\n process.parent.name : \"java\" and\n process.name : (\"sh\", \"bash\", \"dash\", \"ksh\", \"tcsh\", \"zsh\", \"curl\", \"wget\")\n", "references": [ "https://www.lunasec.io/docs/blog/log4j-zero-day/", @@ -73,5 +73,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } 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 index 3bf8084fe3659..3eab94d7a63e7 100644 --- 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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious PDF Reader Child Process", - "note": "## Triage and analysis\n\n### Investigating Suspicious PDF Reader Child Process\n\nPDF is a common file type used in corporate environments and most machines have software to handle these files. This\ncreates a vector where attackers can exploit the engines and technology behind this class of software for initial access\nor privilege escalation.\n\nThis rule looks for commonly abused built-in utilities spawned by a PDF reader process, which is likely a malicious behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve PDF documents received and opened by the user that could cause this behavior. Common locations include, but\nare not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious PDF Reader Child Process\n\nPDF is a common file type used in corporate environments and most machines have software to handle these files. This\ncreates a vector where attackers can exploit the engines and technology behind this class of software for initial access\nor privilege escalation.\n\nThis rule looks for commonly abused built-in utilities spawned by a PDF reader process, which is likely a malicious behavior.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve PDF documents received and opened by the user that could cause this behavior. Common locations include, but\nare not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : (\"AcroRd32.exe\",\n \"Acrobat.exe\",\n \"FoxitPhantomPDF.exe\",\n \"FoxitReader.exe\") and\n process.name : (\"arp.exe\", \"dsquery.exe\", \"dsget.exe\", \"gpresult.exe\", \"hostname.exe\", \"ipconfig.exe\", \"nbtstat.exe\",\n \"net.exe\", \"net1.exe\", \"netsh.exe\", \"netstat.exe\", \"nltest.exe\", \"ping.exe\", \"qprocess.exe\",\n \"quser.exe\", \"qwinsta.exe\", \"reg.exe\", \"sc.exe\", \"systeminfo.exe\", \"tasklist.exe\", \"tracert.exe\",\n \"whoami.exe\", \"bginfo.exe\", \"cdb.exe\", \"cmstp.exe\", \"csi.exe\", \"dnx.exe\", \"fsi.exe\", \"ieexec.exe\",\n \"iexpress.exe\", \"installutil.exe\", \"Microsoft.Workflow.Compiler.exe\", \"msbuild.exe\", \"mshta.exe\",\n \"msxsl.exe\", \"odbcconf.exe\", \"rcsi.exe\", \"regsvr32.exe\", \"xwizard.exe\", \"atbroker.exe\",\n \"forfiles.exe\", \"schtasks.exe\", \"regasm.exe\", \"regsvcs.exe\", \"cmd.exe\", \"cscript.exe\",\n \"powershell.exe\", \"pwsh.exe\", \"wmic.exe\", \"wscript.exe\", \"bitsadmin.exe\", \"certutil.exe\", \"ftp.exe\")\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_powershell_imgload.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_powershell_imgload.json index 652689a233566..b1b2b87bc5d87 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_powershell_imgload.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_powershell_imgload.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious PowerShell Engine ImageLoad", - "note": "## Triage and analysis\n\n### Investigating Suspicious PowerShell Engine ImageLoad\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can use PowerShell without having to execute `PowerShell.exe` directly. This technique, often called\n\"PowerShell without PowerShell,\" works by using the underlying System.Management.Automation namespace and can bypass\napplication allowlisting and PowerShell security features.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Retrieve the implementation (DLL, executable, etc.) and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity can happen legitimately. Some vendors have their own PowerShell implementations that are shipped with\nsome products. These benign true positives (B-TPs) can be added as exceptions if necessary after analysis.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", + "note": "## Triage and analysis\n\n### Investigating Suspicious PowerShell Engine ImageLoad\n\nPowerShell is one of the main tools system administrators use for automation, report routines, and other tasks. This\nmakes it available for use in various environments, and creates an attractive way for attackers to execute code.\n\nAttackers can use PowerShell without having to execute `PowerShell.exe` directly. This technique, often called\n\"PowerShell without PowerShell,\" works by using the underlying System.Management.Automation namespace and can bypass\napplication allowlisting and PowerShell security features.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Retrieve the implementation (DLL, executable, etc.) and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity can happen legitimately. Some vendors have their own PowerShell implementations that are shipped with\nsome products. These benign true positives (B-TPs) can be added as exceptions if necessary after analysis.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n\n\n\nIf enabling an EQL rule on a non-elastic-agent index (such as beats) for versions <8.2, events will not define `event.ingested` and default fallback for EQL rules was not added until 8.2, so you will need to add a custom pipeline to populate `event.ingested` to @timestamp for this rule to work.", "query": "any where (event.category == \"library\" or (event.category == \"process\" and event.action : \"Image loaded*\")) and\n (dll.name : (\"System.Management.Automation.ni.dll\", \"System.Management.Automation.dll\") or\n file.name : (\"System.Management.Automation.ni.dll\", \"System.Management.Automation.dll\")) and\n\n/* add false positives relevant to your environment here */\nnot process.executable : (\"C:\\\\Windows\\\\System32\\\\RemoteFXvGPUDisablement.exe\", \"C:\\\\Windows\\\\System32\\\\sdiagnhost.exe\") and\nnot process.executable regex~ \"\"\"C:\\\\Program Files( \\(x86\\))?\\\\*\\.exe\"\"\" and\n not process.name :\n (\n \"Altaro.SubAgent.exe\",\n \"AppV_Manage.exe\",\n \"azureadconnect.exe\",\n \"CcmExec.exe\",\n \"configsyncrun.exe\",\n \"choco.exe\",\n \"ctxappvservice.exe\",\n \"DVLS.Console.exe\",\n \"edgetransport.exe\",\n \"exsetup.exe\",\n \"forefrontactivedirectoryconnector.exe\",\n \"InstallUtil.exe\",\n \"JenkinsOnDesktop.exe\",\n \"Microsoft.EnterpriseManagement.ServiceManager.UI.Console.exe\",\n \"mmc.exe\",\n \"mscorsvw.exe\",\n \"msexchangedelivery.exe\",\n \"msexchangefrontendtransport.exe\",\n \"msexchangehmworker.exe\",\n \"msexchangesubmission.exe\",\n \"msiexec.exe\",\n \"MsiExec.exe\",\n \"noderunner.exe\",\n \"NServiceBus.Host.exe\",\n \"NServiceBus.Host32.exe\",\n \"NServiceBus.Hosting.Azure.HostProcess.exe\",\n \"OuiGui.WPF.exe\",\n \"powershell.exe\",\n \"powershell_ise.exe\",\n \"pwsh.exe\",\n \"SCCMCliCtrWPF.exe\",\n \"ScriptEditor.exe\",\n \"ScriptRunner.exe\",\n \"sdiagnhost.exe\",\n \"servermanager.exe\",\n \"setup100.exe\",\n \"ServiceHub.VSDetouredHost.exe\",\n \"SPCAF.Client.exe\",\n \"SPCAF.SettingsEditor.exe\",\n \"SQLPS.exe\",\n \"telemetryservice.exe\",\n \"UMWorkerProcess.exe\",\n \"w3wp.exe\",\n \"wsmprovhost.exe\"\n )\n", "required_fields": [ { @@ -55,7 +55,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { @@ -83,5 +84,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_hidden_shell_conhost.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_hidden_shell_conhost.json index 4f6e8c63b7be8..873ed4a120f19 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_hidden_shell_conhost.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_hidden_shell_conhost.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Conhost Spawned By Suspicious Parent Process", - "note": "## Triage and analysis\n\n### Investigating Conhost Spawned By Suspicious Parent Process\n\nThe Windows Console Host, or `conhost.exe`, is both the server application for all of the Windows Console APIs as well as\nthe classic Windows user interface for working with command-line applications.\n\nAttackers often rely on custom shell implementations to avoid using built-in command interpreters like `cmd.exe` and\n`PowerShell.exe` and bypass application allowlisting and security features. Attackers commonly inject these implementations into\nlegitimate system processes.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Retrieve the parent process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious Process from Conhost - 28896382-7d4f-4d50-9b72-67091901fd26\n- Suspicious PowerShell Engine ImageLoad - 852c1f19-68e8-43a6-9dce-340771fe1be3\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Conhost Spawned By Suspicious Parent Process\n\nThe Windows Console Host, or `conhost.exe`, is both the server application for all of the Windows Console APIs as well as\nthe classic Windows user interface for working with command-line applications.\n\nAttackers often rely on custom shell implementations to avoid using built-in command interpreters like `cmd.exe` and\n`PowerShell.exe` and bypass application allowlisting and security features. Attackers commonly inject these implementations into\nlegitimate system processes.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate abnormal behaviors observed by the subject process, such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Retrieve the parent process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious Process from Conhost - 28896382-7d4f-4d50-9b72-67091901fd26\n- Suspicious PowerShell Engine ImageLoad - 852c1f19-68e8-43a6-9dce-340771fe1be3\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.name : \"conhost.exe\" and\n process.parent.name : (\"lsass.exe\", \"services.exe\", \"smss.exe\", \"winlogon.exe\", \"explorer.exe\", \"dllhost.exe\", \"rundll32.exe\",\n \"regsvr32.exe\", \"userinit.exe\", \"wininit.exe\", \"spoolsv.exe\", \"ctfmon.exe\") and\n not (process.parent.name : \"rundll32.exe\" and\n process.parent.args : (\"?:\\\\Windows\\\\Installer\\\\MSI*.tmp,zzzzInvokeManagedCustomActionOutOfProc\",\n \"?:\\\\WINDOWS\\\\system32\\\\PcaSvc.dll,PcaPatchSdbTask\",\n \"?:\\\\WINDOWS\\\\system32\\\\davclnt.dll,DavSetCookie\"))\n", "references": [ "https://www.fireeye.com/blog/threat-research/2017/08/monitoring-windows-console-activity-part-one.html" @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Execution" + "Execution", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_xp_cmdshell_mssql_stored_procedure.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_xp_cmdshell_mssql_stored_procedure.json index fdc2114f9c36d..2b55041c64fe7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_xp_cmdshell_mssql_stored_procedure.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_xp_cmdshell_mssql_stored_procedure.json @@ -12,8 +12,11 @@ "language": "eql", "license": "Elastic License v2", "name": "Execution via MSSQL xp_cmdshell Stored Procedure", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Execution via MSSQL xp_cmdshell Stored Procedure\n\nMicrosoft SQL Server (MSSQL) has procedures meant to extend its functionality, the Extended Stored Procedures. These\nprocedures are external functions written in C/C++; some provide interfaces for external programs. This is the case for\nxp_cmdshell, which spawns a Windows command shell and passes in a string for execution. Attackers can use this to\nexecute commands on the system running the SQL server, commonly to escalate their privileges and establish persistence.\n\nThe xp_cmdshell procedure is disabled by default, but when used, it has the same security context as the MSSQL Server\nservice account, which is often privileged.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal account behavior, such as command executions, file creations or modifications, and network\nconnections.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Examine the command line to determine if the command executed is potentially harmful or malicious.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n\n### False positive analysis\n\n- This mechanism can be used legitimately, but it brings inherent risk. The security team must monitor any activity of\nit. If recurrent tasks are being executed using this mechanism, consider adding exceptions \u2014 preferably with a full\ncommand line.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Ensure that SQL servers are not directly exposed to the internet. If there is a business justification for such, use\nan allowlist to allow only connections from known legitimate sources.\n- Disable the xp_cmdshell stored procedure.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.name : \"cmd.exe\" and process.parent.name : \"sqlservr.exe\" and\n not process.args : (\"\\\\\\\\*\", \"diskfree\", \"rmdir\", \"mkdir\", \"dir\", \"del\", \"rename\", \"bcp\", \"*XMLNAMESPACES*\",\n \"?:\\\\MSSQL\\\\Backup\\\\Jobs\\\\sql_agent_backup_job.ps1\", \"K:\\\\MSSQL\\\\Backup\\\\msdb\", \"K:\\\\MSSQL\\\\Backup\\\\Logins\")\n", + "references": [ + "https://thedfirreport.com/2022/07/11/select-xmrig-from-sqlserver/" + ], "required_fields": [ { "ecs": true, 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 index c39d0637ab983..d8de82c5251a9 100644 --- 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 @@ -56,7 +56,8 @@ "Continuous Monitoring", "SecOps", "Asset Visibility", - "Exfiltration" + "Exfiltration", + "has_guide" ], "threat": [ { @@ -77,5 +78,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_backup_file_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_backup_file_deletion.json index 5c0cae49bde07..73d7ed7c943bf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_backup_file_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_backup_file_deletion.json @@ -46,7 +46,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { @@ -67,5 +68,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } 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 index 84403d4b48ded..80ad1350df659 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Log Auditing" + "Log Auditing", + "has_guide" ], "threat": [ { @@ -103,5 +104,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index 0e28f8255ffb2..5734ffe4c312a 100644 --- 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 @@ -60,7 +60,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Log Auditing" + "Log Auditing", + "has_guide" ], "threat": [ { @@ -103,5 +104,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index fa184b0ea2c37..04870a18138e7 100644 --- 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 @@ -61,7 +61,8 @@ "Continuous Monitoring", "SecOps", "Log Auditing", - "Impact" + "Impact", + "has_guide" ], "threat": [ { @@ -104,5 +105,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_deleting_backup_catalogs_with_wbadmin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_deleting_backup_catalogs_with_wbadmin.json index 9b83fccb1fb17..0136fbd4adc2a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_deleting_backup_catalogs_with_wbadmin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_deleting_backup_catalogs_with_wbadmin.json @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_google_workspace_mfa_enforcement_disabled.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_google_workspace_mfa_enforcement_disabled.json index bbaed9c02d794..6095c3c3a3923 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_google_workspace_mfa_enforcement_disabled.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_google_workspace_mfa_enforcement_disabled.json @@ -64,7 +64,8 @@ "Continuous Monitoring", "SecOps", "Configuration Audit", - "Impact" + "Impact", + "has_guide" ], "threat": [ { @@ -85,5 +86,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_hosts_file_modified.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_hosts_file_modified.json index a5970f7a09fbd..a7ce614def97f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_hosts_file_modified.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_hosts_file_modified.json @@ -13,7 +13,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Hosts File Modified", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Hosts File Modified\n\nOperating systems use the hosts file to map a connection between an IP address and domain names before going to domain\nname servers. Attackers can abuse this mechanism to route traffic to malicious infrastructure or disrupt security that\ndepends on server communications. For example, Russian threat actors modified this file on a domain controller to\nredirect Duo MFA calls to localhost instead of the Duo server, which prevented the MFA service from contacting its\nserver to validate MFA login. This effectively disabled MFA for active domain accounts because the default policy of Duo\nfor Windows is to \"Fail open\" if the MFA server is unreachable. This can happen in any MFA implementation and is not\nexclusive to Duo. Find more details in this [CISA Alert](https://www.cisa.gov/uscert/ncas/alerts/aa22-074a).\n\nThis rule identifies modifications in the hosts file across multiple operating systems using process creation events for\nLinux and file events in Windows and macOS.\n\n#### Possible investigation steps\n\n- Identify the specifics of the involved assets, such as role, criticality, and associated users.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Examine the changes to the hosts file by comparing it against file backups, volume shadow copies, and other restoration\nmechanisms.\n\n### False positive analysis\n\n- This mechanism can be used legitimately. Analysts can dismiss the alert if the administrator is aware of the activity\nand the configuration was justified.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Consider isolating the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Review the privileges of the administrator account that performed the action.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "any where\n\n /* file events for creation; file change events are not captured by some of the included sources for linux and so may\n miss this, which is the purpose of the process + command line args logic below */\n (\n event.category == \"file\" and event.type in (\"change\", \"creation\") and\n file.path : (\"/private/etc/hosts\", \"/etc/hosts\", \"?:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts\")\n )\n or\n\n /* process events for change targeting linux only */\n (\n event.category == \"process\" and event.type in (\"start\") and\n process.name in (\"nano\", \"vim\", \"vi\", \"emacs\", \"echo\", \"sed\") and\n process.args : (\"/etc/hosts\")\n )\n", "references": [ "https://www.elastic.co/guide/en/beats/auditbeat/current/auditbeat-reference-yml.html" @@ -86,5 +86,5 @@ "timeline_title": "Comprehensive File Timeline", "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } 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 index 864a9c9e814f6..49c4f32551554 100644 --- 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 @@ -61,7 +61,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Monitoring" + "Monitoring", + "has_guide" ], "threat": [ { @@ -82,5 +83,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_modification_of_boot_config.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_modification_of_boot_config.json index 2952696f91d6b..256e8a869d076 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_modification_of_boot_config.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_modification_of_boot_config.json @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_process_kill_threshold.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_process_kill_threshold.json index 0a86a88da1140..18700e2d4bbac 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_process_kill_threshold.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_process_kill_threshold.json @@ -42,7 +42,8 @@ "Host", "Linux", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { @@ -68,5 +69,5 @@ "value": 10 }, "type": "threshold", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_stop_process_service_threshold.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_stop_process_service_threshold.json index cb9344a9276ee..8204204bb34c0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_stop_process_service_threshold.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_stop_process_service_threshold.json @@ -44,7 +44,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { @@ -70,5 +71,5 @@ "value": 10 }, "type": "threshold", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_or_resized_via_vssadmin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_or_resized_via_vssadmin.json index e640e7778107d..a4dbdf6df2385 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_or_resized_via_vssadmin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_or_resized_via_vssadmin.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Volume Shadow Copy Deleted or Resized via VssAdmin", - "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deleted or Resized via VssAdmin\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of Vssadmin.exe to either delete or resize shadow copies.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- In the case of a resize operation, check if the resize value is equal to suspicious values, like 401MB.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule may produce benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deleted or Resized via VssAdmin\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of Vssadmin.exe to either delete or resize shadow copies.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- In the case of a resize operation, check if the resize value is equal to suspicious values, like 401MB.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule may produce benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\"\n and (process.name : \"vssadmin.exe\" or process.pe.original_file_name == \"VSSADMIN.EXE\") and\n process.args in (\"delete\", \"resize\") and process.args : \"shadows*\"\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_powershell.json index fefcf9f192ded..04563fc72f525 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_powershell.json @@ -13,7 +13,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Volume Shadow Copy Deletion via PowerShell", - "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deletion via PowerShell\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of PowerShell cmdlets to interact with the Win32_ShadowCopy WMI class, retrieve shadow\ncopy objects, and delete them.\n\n#### Possible investigation steps\n\n- Investigate the program execution chain (parent process tree).\n- Check whether the account is authorized to perform this operation.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule has chances of producing benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deletion via PowerShell\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of PowerShell cmdlets to interact with the Win32_ShadowCopy WMI class, retrieve shadow\ncopy objects, and delete them.\n\n#### Possible investigation steps\n\n- Investigate the program execution chain (parent process tree).\n- Check whether the account is authorized to perform this operation.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule has chances of producing benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.name : (\"powershell.exe\", \"pwsh.exe\", \"powershell_ise.exe\") and\n process.args : (\"*Get-WmiObject*\", \"*gwmi*\", \"*Get-CimInstance*\", \"*gcim*\") and\n process.args : (\"*Win32_ShadowCopy*\") and\n process.args : (\"*.Delete()*\", \"*Remove-WmiObject*\", \"*rwmi*\", \"*Remove-CimInstance*\", \"*rcim*\")\n", "references": [ "https://docs.microsoft.com/en-us/previous-versions/windows/desktop/vsswmi/win32-shadowcopy", @@ -46,7 +46,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_wmic.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_wmic.json index 0844dc6d0148d..eac82475417b6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_wmic.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_volume_shadow_copy_deletion_via_wmic.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Volume Shadow Copy Deletion via WMIC", - "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deletion via WMIC\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of `wmic.exe` to interact with VSS via the `shadowcopy` alias and delete parameter.\n\n#### Possible investigation steps\n\n- Investigate the program execution chain (parent process tree).\n- Check whether the account is authorized to perform this operation.\n- Contact the account owner and confirm whether they are aware of this activity.\n- In the case of a resize operation, check if the resize value is equal to suspicious values, like 401MB.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule has chances of producing benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Volume Shadow Copy Deletion via WMIC\n\nThe Volume Shadow Copy Service (VSS) is a Windows feature that enables system administrators to take snapshots of volumes\nthat can later be restored or mounted to recover specific files or folders.\n\nA typical step in the playbook of an attacker attempting to deploy ransomware is to delete Volume Shadow\nCopies to ensure that victims have no alternative to paying the ransom, making any action that deletes shadow\ncopies worth monitoring.\n\nThis rule monitors the execution of `wmic.exe` to interact with VSS via the `shadowcopy` alias and delete parameter.\n\n#### Possible investigation steps\n\n- Investigate the program execution chain (parent process tree).\n- Check whether the account is authorized to perform this operation.\n- Contact the account owner and confirm whether they are aware of this activity.\n- In the case of a resize operation, check if the resize value is equal to suspicious values, like 401MB.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Use process name, command line, and file hash to search for occurrences in other hosts.\n- Check if any files on the host machine have been encrypted.\n\n\n### False positive analysis\n\n- This rule has chances of producing benign true positives (B-TPs). If this activity is expected and noisy in your\nenvironment, consider adding exceptions \u2014 preferably with a combination of user and command line conditions.\n\n### Related rules\n\n- Volume Shadow Copy Deleted or Resized via VssAdmin - b5ea4bfe-a1b2-421f-9d47-22a75a6f2921\n- Volume Shadow Copy Deletion via PowerShell - d99a037b-c8e2-47a5-97b9-170d076827c4\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Priority should be given due to the advanced stage of this activity on the attack.\n- Consider isolating the involved host to prevent destructive behavior, which is commonly associated with this activity.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If data was encrypted, deleted, or modified, activate your data recovery plan.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Perform data recovery locally or restore the backups from replicated copies (cloud, other servers, etc.).\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n (process.name : \"WMIC.exe\" or process.pe.original_file_name == \"wmic.exe\") and\n process.args : \"delete\" and process.args : \"shadowcopy\"\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Impact" + "Impact", + "has_guide" ], "threat": [ { 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 7d30ff7502a90..97878f9eb2e0b 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 @@ -368,7 +368,7 @@ import rule355 from './persistence_google_workspace_api_access_granted_via_domai import rule356 from './defense_evasion_suspicious_short_program_name.json'; import rule357 from './lateral_movement_incoming_wmi.json'; import rule358 from './persistence_via_hidden_run_key_valuename.json'; -import rule359 from './credential_access_potential_ssh_bruteforce.json'; +import rule359 from './credential_access_potential_macos_ssh_bruteforce.json'; import rule360 from './credential_access_promt_for_pwd_via_osascript.json'; import rule361 from './lateral_movement_remote_services.json'; import rule362 from './defense_evasion_domain_added_to_google_workspace_trusted_domains.json'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin.json index 3dec3ef0087ae..d06a073fd504c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin.json @@ -57,7 +57,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -78,5 +79,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin_atrisk_or_confirmed.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin_atrisk_or_confirmed.json index c1aa77df2db99..c2d57924a39e4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin_atrisk_or_confirmed.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_high_risk_signin_atrisk_or_confirmed.json @@ -52,7 +52,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -73,5 +74,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_powershell_signin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_powershell_signin.json index e6660c2dc1251..d46d34a762cce 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_powershell_signin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_azure_active_directory_powershell_signin.json @@ -58,7 +58,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -86,5 +87,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_consent_grant_attack_via_azure_registered_application.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_consent_grant_attack_via_azure_registered_application.json index 9ce6e6ddaee9d..01a68b944d294 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_consent_grant_attack_via_azure_registered_application.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_consent_grant_attack_via_azure_registered_application.json @@ -70,7 +70,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -113,5 +114,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } 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 index 48b42a0351b9e..7612d79572c17 100644 --- 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 @@ -64,7 +64,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -100,5 +101,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_script_executing_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_script_executing_powershell.json index 8c707115c0bb6..564667506aac3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_script_executing_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_script_executing_powershell.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Windows Script Executing PowerShell", - "note": "## Triage and analysis\n\n### Investigating Windows Script Executing PowerShell\n\nThe Windows Script Host (WSH) is an Windows automation technology, which is ideal for non-interactive scripting needs,\nsuch as logon scripting, administrative scripting, and machine automation.\n\nAttackers commonly use WSH scripts as their initial access method, acting like droppers for second stage payloads, but\ncan also use them to download tools and utilities needed to accomplish their goals.\n\nThis rule looks for the spawn of the `powershell.exe` process with `cscript.exe` or `wscript.exe` as its parent process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate commands executed by the spawned PowerShell process.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Determine how the script file was delivered (email attachment, dropped by other processes, etc.).\n- Investigate other alerts associated with the user/host during the past 48 hours.\n\n### False positive analysis\n\n- The usage of these script engines by regular users is unlikely. In the case of authorized benign true positives\n(B-TPs), exceptions can be added.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Windows Script Executing PowerShell\n\nThe Windows Script Host (WSH) is an Windows automation technology, which is ideal for non-interactive scripting needs,\nsuch as logon scripting, administrative scripting, and machine automation.\n\nAttackers commonly use WSH scripts as their initial access method, acting like droppers for second stage payloads, but\ncan also use them to download tools and utilities needed to accomplish their goals.\n\nThis rule looks for the spawn of the `powershell.exe` process with `cscript.exe` or `wscript.exe` as its parent process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate commands executed by the spawned PowerShell process.\n- If unsigned files are found on the process tree, retrieve them and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n- Determine how the script file was delivered (email attachment, dropped by other processes, etc.).\n- Investigate other alerts associated with the user/host during the past 48 hours.\n\n### False positive analysis\n\n- The usage of these script engines by regular users is unlikely. In the case of authorized benign true positives\n(B-TPs), exceptions can be added.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Reimage the host operating system and restore compromised files to clean versions.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : (\"cscript.exe\", \"wscript.exe\") and process.name : \"powershell.exe\"\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Initial Access" + "Initial Access", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_office_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_office_child_process.json index 91f65ff6fbd18..9bc62b2b0ec53 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_office_child_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_office_child_process.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious MS Office Child Process", - "note": "## Triage and analysis\n\n### Investigating Suspicious MS Office Child Process\n\nMicrosoft Office (MS Office) is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently targeted\nfor initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThis rule looks for suspicious processes spawned by MS Office programs. This is generally the result of the execution of\nmalicious documents.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious MS Office Child Process\n\nMicrosoft Office (MS Office) is a suite of applications designed to help with productivity and completing common tasks on a computer.\nYou can create and edit documents containing text and images, work with data in spreadsheets and databases, and create\npresentations and posters. As it is some of the most-used software across companies, MS Office is frequently targeted\nfor initial access. It also has a wide variety of capabilities that attackers can take advantage of.\n\nThis rule looks for suspicious processes spawned by MS Office programs. This is generally the result of the execution of\nmalicious documents.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve MS Office documents received and opened by the user that could cause this behavior. Common locations include,\nbut are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : (\"eqnedt32.exe\", \"excel.exe\", \"fltldr.exe\", \"msaccess.exe\", \"mspub.exe\", \"powerpnt.exe\", \"winword.exe\", \"outlook.exe\") and\n process.name : (\"Microsoft.Workflow.Compiler.exe\", \"arp.exe\", \"atbroker.exe\", \"bginfo.exe\", \"bitsadmin.exe\", \"cdb.exe\", \"certutil.exe\",\n \"cmd.exe\", \"cmstp.exe\", \"control.exe\", \"cscript.exe\", \"csi.exe\", \"dnx.exe\", \"dsget.exe\", \"dsquery.exe\", \"forfiles.exe\",\n \"fsi.exe\", \"ftp.exe\", \"gpresult.exe\", \"hostname.exe\", \"ieexec.exe\", \"iexpress.exe\", \"installutil.exe\", \"ipconfig.exe\",\n \"mshta.exe\", \"msxsl.exe\", \"nbtstat.exe\", \"net.exe\", \"net1.exe\", \"netsh.exe\", \"netstat.exe\", \"nltest.exe\", \"odbcconf.exe\",\n \"ping.exe\", \"powershell.exe\", \"pwsh.exe\", \"qprocess.exe\", \"quser.exe\", \"qwinsta.exe\", \"rcsi.exe\", \"reg.exe\", \"regasm.exe\",\n \"regsvcs.exe\", \"regsvr32.exe\", \"sc.exe\", \"schtasks.exe\", \"systeminfo.exe\", \"tasklist.exe\", \"tracert.exe\", \"whoami.exe\",\n \"wmic.exe\", \"wscript.exe\", \"xwizard.exe\", \"explorer.exe\", \"rundll32.exe\", \"hh.exe\", \"msdt.exe\")\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Initial Access" + "Initial Access", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_outlook_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_outlook_child_process.json index 2b21f26bd82e9..0b21f7c5f2e75 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_outlook_child_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_ms_outlook_child_process.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious MS Outlook Child Process", - "note": "## Triage and analysis\n\n### Investigating Suspicious MS Outlook Child Process\n\nMicrosoft Outlook is an email client that provides contact, email calendar, and task management features. Outlook is\nwidely used, either standalone or as part of the Office suite.\n\nThis rule looks for suspicious processes spawned by MS Outlook, which can be the result of the execution of malicious\ndocuments and/or exploitation for initial access.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve recently opened files received via email and opened by the user that could cause this behavior. Common\nlocations include but are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Suspicious MS Outlook Child Process\n\nMicrosoft Outlook is an email client that provides contact, email calendar, and task management features. Outlook is\nwidely used, either standalone or as part of the Office suite.\n\nThis rule looks for suspicious processes spawned by MS Outlook, which can be the result of the execution of malicious\ndocuments and/or exploitation for initial access.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve recently opened files received via email and opened by the user that could cause this behavior. Common\nlocations include but are not limited to, the Downloads and Document folders and the folder configured at the email client.\n- Determine if the collected files are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n - If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : \"outlook.exe\" and\n process.name : (\"Microsoft.Workflow.Compiler.exe\", \"arp.exe\", \"atbroker.exe\", \"bginfo.exe\", \"bitsadmin.exe\",\n \"cdb.exe\", \"certutil.exe\", \"cmd.exe\", \"cmstp.exe\", \"cscript.exe\", \"csi.exe\", \"dnx.exe\", \"dsget.exe\",\n \"dsquery.exe\", \"forfiles.exe\", \"fsi.exe\", \"ftp.exe\", \"gpresult.exe\", \"hostname.exe\", \"ieexec.exe\",\n \"iexpress.exe\", \"installutil.exe\", \"ipconfig.exe\", \"mshta.exe\", \"msxsl.exe\", \"nbtstat.exe\", \"net.exe\",\n \"net1.exe\", \"netsh.exe\", \"netstat.exe\", \"nltest.exe\", \"odbcconf.exe\", \"ping.exe\", \"powershell.exe\",\n \"pwsh.exe\", \"qprocess.exe\", \"quser.exe\", \"qwinsta.exe\", \"rcsi.exe\", \"reg.exe\", \"regasm.exe\",\n \"regsvcs.exe\", \"regsvr32.exe\", \"sc.exe\", \"schtasks.exe\", \"systeminfo.exe\", \"tasklist.exe\",\n \"tracert.exe\", \"whoami.exe\", \"wmic.exe\", \"wscript.exe\", \"xwizard.exe\")\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Initial Access" + "Initial Access", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_unusual_dns_service_children.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_unusual_dns_service_children.json index cab15fd6b1ed6..a91bdd8faea3e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_unusual_dns_service_children.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_unusual_dns_service_children.json @@ -15,7 +15,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Unusual Child Process of dns.exe", - "note": "## Triage and analysis\n\n### Investigating Unusual Child Process of dns.exe\n\nSIGRed (CVE-2020-1350) is a wormable, critical vulnerability in the Windows DNS server that affects Windows Server\nversions 2003 to 2019 and can be triggered by a malicious DNS response. Because the service is running in elevated\nprivileges (SYSTEM), an attacker that successfully exploits it is granted Domain Administrator rights. This can\neffectively compromise the entire corporate infrastructure.\n\nThis rule looks for unusual children of the `dns.exe` process, which can indicate the exploitation of the SIGRed or a\nsimilar remote code execution vulnerability in the DNS server.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes.\n - Any suspicious or abnormal child process spawned from dns.exe should be carefully reviewed and investigated. It's\n impossible to predict what an adversary may deploy as the follow-on process after the exploit, but built-in\n discovery/enumeration utilities should be top of mind (`whoami.exe`, `netstat.exe`, `systeminfo.exe`, `tasklist.exe`).\n - Built-in Windows programs that contain capabilities used to download and execute additional payloads should also be\n considered. This is not an exhaustive list, but ideal candidates to start out would be: `mshta.exe`, `powershell.exe`,\n `regsvr32.exe`, `rundll32.exe`, `wscript.exe`, `wmic.exe`.\n - If a denial-of-service (DoS) exploit is successful and DNS Server service crashes, be mindful of potential child processes related to\n `werfault.exe` occurring.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Investigate other alerts associated with the host during the past 48 hours.\n- Check whether the server is vulnerable to CVE-2020-1350.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Reimage the host operating system or restore the compromised server to a clean state.\n- Install the latest patches on systems that run Microsoft DNS Server.\n- Consider the implementation of a patch management system, such as the Windows Server Update Services (WSUS).\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Review the privileges assigned to the user to ensure that the least privilege principle is being followed.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Unusual Child Process of dns.exe\n\nSIGRed (CVE-2020-1350) is a wormable, critical vulnerability in the Windows DNS server that affects Windows Server\nversions 2003 to 2019 and can be triggered by a malicious DNS response. Because the service is running in elevated\nprivileges (SYSTEM), an attacker that successfully exploits it is granted Domain Administrator rights. This can\neffectively compromise the entire corporate infrastructure.\n\nThis rule looks for unusual children of the `dns.exe` process, which can indicate the exploitation of the SIGRed or a\nsimilar remote code execution vulnerability in the DNS server.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes.\n - Any suspicious or abnormal child process spawned from dns.exe should be carefully reviewed and investigated. It's\n impossible to predict what an adversary may deploy as the follow-on process after the exploit, but built-in\n discovery/enumeration utilities should be top of mind (`whoami.exe`, `netstat.exe`, `systeminfo.exe`, `tasklist.exe`).\n - Built-in Windows programs that contain capabilities used to download and execute additional payloads should also be\n considered. This is not an exhaustive list, but ideal candidates to start out would be: `mshta.exe`, `powershell.exe`,\n `regsvr32.exe`, `rundll32.exe`, `wscript.exe`, `wmic.exe`.\n - If a denial-of-service (DoS) exploit is successful and DNS Server service crashes, be mindful of potential child processes related to\n `werfault.exe` occurring.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Investigate other alerts associated with the host during the past 48 hours.\n- Check whether the server is vulnerable to CVE-2020-1350.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Reimage the host operating system or restore the compromised server to a clean state.\n- Install the latest patches on systems that run Microsoft DNS Server.\n- Consider the implementation of a patch management system, such as the Windows Server Update Services (WSUS).\n- Run a full scan using the antimalware tool in place. This scan can reveal additional artifacts left in the system,\npersistence mechanisms, and malware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Review the privileges assigned to the user to ensure that the least privilege principle is being followed.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and process.parent.name : \"dns.exe\" and\n not process.name : \"conhost.exe\"\n", "references": [ "https://research.checkpoint.com/2020/resolving-your-way-into-domain-admin-exploiting-a-17-year-old-bug-in-windows-dns-servers/", @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Initial Access" + "Initial Access", + "has_guide" ], "threat": [ { @@ -69,5 +70,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_via_system_manager.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_via_system_manager.json index 1af2502b0034a..78fea7b5dafe2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_via_system_manager.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_via_system_manager.json @@ -60,7 +60,8 @@ "Continuous Monitoring", "SecOps", "Log Auditing", - "Initial Access" + "Initial Access", + "has_guide" ], "threat": [ { @@ -88,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_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 index 62d4c160e806f..000e631380307 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Direct Outbound SMB Connection", - "note": "## Triage and analysis\n\n### Investigating Direct Outbound SMB Connection\n\nThis rule looks for unexpected processes making network connections over port 445. Windows file sharing is typically\nimplemented over Server Message Block (SMB), which communicates between hosts using port 445. When legitimate, these\nnetwork connections are established by the kernel (PID 4). Occurrences of non-system processes using this port can indicate\nport scanners, exploits, and tools used to move laterally on the environment.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Direct Outbound SMB Connection\n\nThis rule looks for unexpected processes making network connections over port 445. Windows file sharing is typically\nimplemented over Server Message Block (SMB), which communicates between hosts using port 445. When legitimate, these\nnetwork connections are established by the kernel (PID 4). Occurrences of non-system processes using this port can indicate\nport scanners, exploits, and tools used to move laterally on the environment.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- If this rule is noisy in your environment due to expected activity, consider adding exceptions \u2014 preferably with a combination\nof user and command line conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by process.entity_id\n [process where event.type == \"start\" and host.os.name == \"Windows\" and process.pid != 4 and\n not (process.executable : \"D:\\\\EnterpriseCare\\\\tools\\\\jre.1\\\\bin\\\\java.exe\" and process.args : \"com.emeraldcube.prism.launcher.Invoker\") and\n not (process.executable : \"C:\\\\Docusnap 11\\\\Tools\\\\nmap\\\\nmap.exe\" and process.args : \"smb-os-discovery.nse\") and\n not process.executable :\n (\"?:\\\\Program Files\\\\SentinelOne\\\\Sentinel Agent *\\\\Ranger\\\\SentinelRanger.exe\",\n \"?:\\\\Program Files\\\\Ivanti\\\\Security Controls\\\\ST.EngineHost.exe\",\n \"?:\\\\Program Files (x86)\\\\Fortinet\\\\FSAE\\\\collectoragent.exe\",\n \"?:\\\\Program Files (x86)\\\\Nmap\\\\nmap.exe\",\n \"?:\\\\Program Files\\\\Azure Advanced Threat Protection Sensor\\\\*\\\\Microsoft.Tri.Sensor.exe\",\n \"?:\\\\Program Files\\\\CloudMatters\\\\auvik\\\\AuvikService-release-*\\\\AuvikService.exe\",\n \"?:\\\\Program Files\\\\uptime software\\\\uptime\\\\UptimeDataCollector.exe\",\n \"?:\\\\Program Files\\\\CloudMatters\\\\auvik\\\\AuvikAgentService.exe\",\n \"?:\\\\Program Files\\\\Rumble\\\\rumble-agent-*.exe\")]\n [network where destination.port == 445 and process.pid != 4 and\n not cidrmatch(destination.ip, \"127.0.0.1\", \"::1\")]\n", "required_fields": [ { @@ -64,7 +64,8 @@ "Host", "Windows", "Threat Detection", - "Lateral Movement" + "Lateral Movement", + "has_guide" ], "threat": [ { @@ -91,5 +92,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_dns_server_overflow.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_dns_server_overflow.json index be4535a908006..1d985fb800a68 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_dns_server_overflow.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_dns_server_overflow.json @@ -59,7 +59,8 @@ "Elastic", "Network", "Threat Detection", - "Lateral Movement" + "Lateral Movement", + "has_guide" ], "threat": [ { @@ -80,5 +81,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_executable_tool_transfer_smb.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_executable_tool_transfer_smb.json index 5c463878f146e..cd1de0b09dc00 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_executable_tool_transfer_smb.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_executable_tool_transfer_smb.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential Lateral Tool Transfer via SMB Share", - "note": "## Triage and analysis\n\n### Investigating Potential Lateral Tool Transfer via SMB Share\n\nAdversaries can use network shares to host tooling to support the compromise of other hosts in the environment. These tools\ncan include discovery utilities, credential dumpers, malware, etc. Attackers can also leverage file shares that employees\nfrequently access to host malicious files to gain a foothold in other machines.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the created file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity can happen legitimately. Consider adding exceptions if it is expected and noisy in your environment.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Review the privileges needed to write to the network share and restrict write access as needed.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Potential Lateral Tool Transfer via SMB Share\n\nAdversaries can use network shares to host tooling to support the compromise of other hosts in the environment. These tools\ncan include discovery utilities, credential dumpers, malware, etc. Attackers can also leverage file shares that employees\nfrequently access to host malicious files to gain a foothold in other machines.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account owner and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the created file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity can happen legitimately. Consider adding exceptions if it is expected and noisy in your environment.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Review the privileges needed to write to the network share and restrict write access as needed.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by host.id with maxspan=30s\n [network where event.type == \"start\" and process.pid == 4 and destination.port == 445 and\n network.direction : (\"incoming\", \"ingress\") and\n network.transport == \"tcp\" and source.ip != \"127.0.0.1\" and source.ip != \"::1\"\n ] by process.entity_id\n /* add more executable extensions here if they are not noisy in your environment */\n [file where event.type in (\"creation\", \"change\") and process.pid == 4 and file.extension : (\"exe\", \"dll\", \"bat\", \"cmd\")] by process.entity_id\n", "required_fields": [ { @@ -69,7 +69,8 @@ "Host", "Windows", "Threat Detection", - "Lateral Movement" + "Lateral Movement", + "has_guide" ], "threat": [ { @@ -101,5 +102,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_execution_via_file_shares_sequence.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_execution_via_file_shares_sequence.json index 0e6aab67cf050..301ce56a51f5d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_execution_via_file_shares_sequence.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_execution_via_file_shares_sequence.json @@ -12,6 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Remote Execution via File Shares", + "note": "## Triage and analysis\n\n### Investigating Remote Execution via File Shares\n\nAdversaries can use network shares to host tooling to support the compromise of other hosts in the environment. These\ntools can include discovery utilities, credential dumpers, malware, etc.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Review adjacent login events (e.g., 4624) in the alert timeframe to identify the account used to perform this action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity can happen legitimately. Consider adding exceptions if it is expected and noisy in your environment.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Review the privileges needed to write to the network share and restrict write access as needed.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence with maxspan=1m\n [file where event.type in (\"creation\", \"change\") and process.pid == 4 and file.extension : \"exe\"] by host.id, file.path\n [process where event.type == \"start\"] by host.id, process.executable\n", "references": [ "https://blog.menasec.net/2020/08/new-trick-to-detect-lateral-movement.html" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_rdp_enabled_registry.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_rdp_enabled_registry.json index bc3a4e3b0ac95..12f9216c7b6ec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_rdp_enabled_registry.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_rdp_enabled_registry.json @@ -55,7 +55,8 @@ "Host", "Windows", "Threat Detection", - "Lateral Movement" + "Lateral Movement", + "has_guide" ], "threat": [ { @@ -83,5 +84,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_remote_services.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_remote_services.json index d0504020fcad3..45144cc486895 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_remote_services.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_remote_services.json @@ -12,7 +12,11 @@ "language": "eql", "license": "Elastic License v2", "name": "Remotely Started Services via RPC", + "note": "## Triage and analysis\n\n### Investigating Remotely Started Services via RPC\n\nThe Service Control Manager Remote Protocol is a client/server protocol used for configuring and controlling service\nprograms running on a remote computer. A remote service management session begins with the client initiating the\nconnection request to the server. If the server grants the request, the connection is established. The client can then\nmake multiple requests to modify, query the configuration, or start and stop services on the server by using the same\nsession until the session is terminated.\n\nThis rule detects the remote creation or start of a service by correlating a `services.exe` network connection and the\nspawn of a child process.\n\n#### Possible investigation steps\n\n- Review login events (e.g., 4624) in the alert timeframe to identify the account used to perform this action. Use the\n`source.address` field to help identify the source system.\n- Review network events from the source system using the source port identified on the alert and try to identify the\nprogram used to initiate the action.\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate if the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Remote management software like SCCM may trigger this rule. If noisy on your environment, consider adding exceptions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved hosts to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence with maxspan=1s\n [network where process.name : \"services.exe\" and\n network.direction : (\"incoming\", \"ingress\") and network.transport == \"tcp\" and\n source.port >= 49152 and destination.port >= 49152 and source.ip != \"127.0.0.1\" and source.ip != \"::1\"\n ] by host.id, process.entity_id\n\n [process where event.type == \"start\" and process.parent.name : \"services.exe\" and \n not (process.name : \"svchost.exe\" and process.args : \"tiledatamodelsvc\") and\n not (process.name : \"msiexec.exe\" and process.args : \"/V\") and\n not process.executable :\n (\"?:\\\\Windows\\\\ADCR_Agent\\\\adcrsvc.exe\",\n \"?:\\\\Windows\\\\System32\\\\VSSVC.exe\",\n \"?:\\\\Windows\\\\servicing\\\\TrustedInstaller.exe\",\n \"?:\\\\Windows\\\\System32\\\\svchost.exe\",\n \"?:\\\\Program Files (x86)\\\\*.exe\",\n \"?:\\\\Program Files\\\\*.exe\",\n \"?:\\\\Windows\\\\PSEXESVC.EXE\",\n \"?:\\\\Windows\\\\System32\\\\sppsvc.exe\",\n \"?:\\\\Windows\\\\System32\\\\wbem\\\\WmiApSrv.exe\",\n \"?:\\\\WINDOWS\\\\RemoteAuditService.exe\",\n \"?:\\\\Windows\\\\VeeamVssSupport\\\\VeeamGuestHelper.exe\",\n \"?:\\\\Windows\\\\VeeamLogShipper\\\\VeeamLogShipper.exe\",\n \"?:\\\\Windows\\\\CAInvokerService.exe\",\n \"?:\\\\Windows\\\\System32\\\\upfc.exe\",\n \"?:\\\\Windows\\\\AdminArsenal\\\\PDQ*.exe\",\n \"?:\\\\Windows\\\\System32\\\\vds.exe\",\n \"?:\\\\Windows\\\\Veeam\\\\Backup\\\\VeeamDeploymentSvc.exe\",\n \"?:\\\\Windows\\\\ProPatches\\\\Scheduler\\\\STSchedEx.exe\",\n \"?:\\\\Windows\\\\System32\\\\certsrv.exe\",\n \"?:\\\\Windows\\\\eset-remote-install-service.exe\",\n \"?:\\\\Pella Corporation\\\\Pella Order Management\\\\GPAutoSvc.exe\",\n \"?:\\\\Pella Corporation\\\\OSCToGPAutoService\\\\OSCToGPAutoSvc.exe\",\n \"?:\\\\Pella Corporation\\\\Pella Order Management\\\\GPAutoSvc.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\NwxExeSvc\\\\NwxExeSvc.exe\",\n \"?:\\\\Windows\\\\System32\\\\taskhostex.exe\")\n ] by host.id, process.parent.entity_id\n", + "references": [ + "https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/705b624a-13de-43cc-b8a2-99573da3635f" + ], "required_fields": [ { "ecs": true, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_scheduled_task_target.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_scheduled_task_target.json index 1896f18299853..06dd1913a6f1b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_scheduled_task_target.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_scheduled_task_target.json @@ -64,7 +64,8 @@ "Host", "Windows", "Threat Detection", - "Lateral Movement" + "Lateral Movement", + "has_guide" ], "threat": [ { @@ -106,5 +107,5 @@ } ], "type": "eql", - "version": 100 + "version": 101 } 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 index 8ccc5adc9dce2..112767349fb88 100644 --- 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 @@ -25,8 +25,9 @@ "Elastic", "Cloud", "AWS", - "ML" + "ML", + "has_guide" ], "type": "machine_learning", - "version": 100 + "version": 101 } 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 index eba9e157895ee..649df5bcfb66e 100644 --- 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 @@ -25,8 +25,9 @@ "Elastic", "Cloud", "AWS", - "ML" + "ML", + "has_guide" ], "type": "machine_learning", - "version": 100 + "version": 101 } 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 index d17e1053e2ccc..1368f04639b5c 100644 --- 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 @@ -25,8 +25,9 @@ "Elastic", "Cloud", "AWS", - "ML" + "ML", + "has_guide" ], "type": "machine_learning", - "version": 100 + "version": 101 } 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 index c170c6a338b30..4719a47dc5d9d 100644 --- 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 @@ -25,8 +25,9 @@ "Elastic", "Cloud", "AWS", - "ML" + "ML", + "has_guide" ], "type": "machine_learning", - "version": 100 + "version": 101 } 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 index 22ef1411a537c..74f190786b086 100644 --- 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 @@ -25,8 +25,9 @@ "Elastic", "Cloud", "AWS", - "ML" + "ML", + "has_guide" ], "type": "machine_learning", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json index 02bcc8eff6864..9624d0b995c11 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Adobe Hijack Persistence", - "note": "## Triage and analysis\n\n### Investigating Adobe Hijack Persistence\n\nAttackers can replace the `RdrCEF.exe` executable with their own to maintain their access, which will be launched\nwhenever Adobe Acrobat Reader is executed.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Adobe Hijack Persistence\n\nAttackers can replace the `RdrCEF.exe` executable with their own to maintain their access, which will be launched\nwhenever Adobe Acrobat Reader is executed.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type == \"creation\" and\n file.path : (\"?:\\\\Program Files (x86)\\\\Adobe\\\\Acrobat Reader DC\\\\Reader\\\\AcroCEF\\\\RdrCEF.exe\",\n \"?:\\\\Program Files\\\\Adobe\\\\Acrobat Reader DC\\\\Reader\\\\AcroCEF\\\\RdrCEF.exe\") and\n not process.name : \"msiexec.exe\"\n", "references": [ "https://twitter.com/pabraeken/status/997997818362155008" @@ -43,7 +43,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -71,5 +72,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_azure_privileged_identity_management_role_modified.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_azure_privileged_identity_management_role_modified.json index ca2be5273f8f2..80720e7aff6ce 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_azure_privileged_identity_management_role_modified.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_azure_privileged_identity_management_role_modified.json @@ -50,7 +50,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -86,5 +87,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_dontexpirepasswd_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_dontexpirepasswd_account.json index e335f4cea7319..6b20c9653773b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_dontexpirepasswd_account.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_dontexpirepasswd_account.json @@ -51,7 +51,8 @@ "Windows", "Threat Detection", "Persistence", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -72,5 +73,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_hidden_local_account_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_hidden_local_account_creation.json index 6f3aa83b004b6..ab09c9a6cf354 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_hidden_local_account_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_hidden_local_account_creation.json @@ -34,7 +34,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -62,5 +63,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_registry_startup_shell_folder_modified.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_registry_startup_shell_folder_modified.json index c1547b38e67b6..e1b8862c4424a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_registry_startup_shell_folder_modified.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_evasion_registry_startup_shell_folder_modified.json @@ -10,7 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious Startup Shell Folder Modification", - "note": "## Triage and analysis\n\n### Investigating Suspicious Startup Shell Folder Modification\n\nTechniques used within malware and by adversaries often leverage the Windows registry to store malicious programs for\npersistence. Startup shell folders are often targeted as they are not as prevalent as normal Startup folder paths so this\nbehavior may evade existing AV/EDR solutions. These programs may also run with higher privileges which can be ideal for\nan attacker.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Review the source process and related file tied to the Windows Registry entry.\n- Validate the activity is not related to planned patches, updates, network administrator activity or legitimate software\ninstallations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There is a high possibility of benign legitimate programs being added to shell folders. This activity could be based\non new software installations, patches, or other network administrator activity. Before entering further investigation,\nit should be verified that this activity is not benign.\n\n### Related rules\n\n- Startup or Run Key Registry Modification - 97fc44d3-8dae-4019-ae83-298c3015600f\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Suspicious Startup Shell Folder Modification\n\nTechniques used within malware and by adversaries often leverage the Windows registry to store malicious programs for\npersistence. Startup shell folders are often targeted as they are not as prevalent as normal Startup folder paths so this\nbehavior may evade existing AV/EDR solutions. These programs may also run with higher privileges which can be ideal for\nan attacker.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Review the source process and related file tied to the Windows Registry entry.\n- Validate the activity is not related to planned patches, updates, network administrator activity or legitimate software\ninstallations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There is a high possibility of benign legitimate programs being added to shell folders. This activity could be based\non new software installations, patches, or other network administrator activity. Before undertaking further investigation,\nit should be verified that this activity is not benign.\n\n### Related rules\n\n- Startup or Run Key Registry Modification - 97fc44d3-8dae-4019-ae83-298c3015600f\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- If the malicious file was delivered via phishing:\n - Block the email sender from sending future emails.\n - Block the malicious web pages.\n - Remove emails from the sender from mailboxes.\n - Consider improvements to the security awareness program.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "registry where\n registry.path : (\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\\\\Common Startup\",\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Shell Folders\\\\Common Startup\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\\\\Startup\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Shell Folders\\\\Startup\"\n ) and\n registry.data.strings != null and\n /* Normal Startup Folder Paths */\n not registry.data.strings : (\n \"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\",\n \"%ProgramData%\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\",\n \"%USERPROFILE%\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\",\n \"C:\\\\Users\\\\*\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\"\n )\n", "required_fields": [ { @@ -32,7 +32,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -60,5 +61,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_gpo_schtask_service_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_gpo_schtask_service_creation.json index 6d014886b1fa4..36fdb7f9316dd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_gpo_schtask_service_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_gpo_schtask_service_creation.json @@ -13,7 +13,7 @@ "license": "Elastic License v2", "name": "Creation or Modification of a new GPO Scheduled Task or Service", "note": "", - "query": "file where event.type != \"deletion\" and\n file.path : (\"?:\\\\Windows\\\\SYSVOL\\\\domain\\\\Policies\\\\*\\\\MACHINE\\\\Preferences\\\\ScheduledTasks\\\\ScheduledTasks.xml\",\n \"?:\\\\Windows\\\\SYSVOL\\\\domain\\\\Policies\\\\*\\\\MACHINE\\\\Preferences\\\\Preferences\\\\Services\\\\Services.xml\") and\n not process.name : \"dfsrs.exe\"\n", + "query": "file where event.type != \"deletion\" and\n file.path : (\"?:\\\\Windows\\\\SYSVOL\\\\domain\\\\Policies\\\\*\\\\MACHINE\\\\Preferences\\\\ScheduledTasks\\\\ScheduledTasks.xml\",\n \"?:\\\\Windows\\\\SYSVOL\\\\domain\\\\Policies\\\\*\\\\MACHINE\\\\Preferences\\\\Services\\\\Services.xml\") and\n not process.name : \"dfsrs.exe\"\n", "required_fields": [ { "ecs": true, @@ -68,5 +68,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_mfa_disabled_for_azure_user.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_mfa_disabled_for_azure_user.json index 67c7c9ad84ddc..8b21e5358f71b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_mfa_disabled_for_azure_user.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_mfa_disabled_for_azure_user.json @@ -46,7 +46,8 @@ "Azure", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -67,5 +68,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ml_rare_process_by_host_windows.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ml_rare_process_by_host_windows.json index 7ae8401cf782d..8c79a775a7779 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ml_rare_process_by_host_windows.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ml_rare_process_by_host_windows.json @@ -27,7 +27,8 @@ "Windows", "Threat Detection", "ML", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -54,5 +55,5 @@ } ], "type": "machine_learning", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_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 index 30786d630001c..385f0aee4aab5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential Modification of Accessibility Binaries", - "note": "## Triage and analysis\n\n### Investigating Potential Modification of Accessibility Binaries\n\nAdversaries may establish persistence and/or elevate privileges by executing malicious content triggered by\naccessibility features. Windows contains accessibility features that may be launched with a key combination before a\nuser has logged in (ex: when the user is on the Windows logon screen). An adversary can modify the way these programs\nare launched to get a command prompt or backdoor without logging in to the system.\n\nMore details can be found [here](https://attack.mitre.org/techniques/T1546/008/).\n\nThis rule looks for the execution of supposed accessibility binaries that don't match any of the accessibility features\nbinaries' original file names, which is likely a custom binary deployed by the attacker.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account and system owners and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true positive\n(B-TP), as this configuration can put the user and the domain at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Potential Modification of Accessibility Binaries\n\nAdversaries may establish persistence and/or elevate privileges by executing malicious content triggered by\naccessibility features. Windows contains accessibility features that may be launched with a key combination before a\nuser has logged in (ex: when the user is on the Windows logon screen). An adversary can modify the way these programs\nare launched to get a command prompt or backdoor without logging in to the system.\n\nMore details can be found [here](https://attack.mitre.org/techniques/T1546/008/).\n\nThis rule looks for the execution of supposed accessibility binaries that don't match any of the accessibility features\nbinaries' original file names, which is likely a custom binary deployed by the attacker.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Contact the account and system owners and confirm whether they are aware of this activity.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity should not happen legitimately. The security team should address any potential benign true positive\n(B-TP), as this configuration can put the user and the domain at risk.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : (\"Utilman.exe\", \"winlogon.exe\") and user.name == \"SYSTEM\" and\n process.args :\n (\n \"C:\\\\Windows\\\\System32\\\\osk.exe\",\n \"C:\\\\Windows\\\\System32\\\\Magnify.exe\",\n \"C:\\\\Windows\\\\System32\\\\Narrator.exe\",\n \"C:\\\\Windows\\\\System32\\\\Sethc.exe\",\n \"utilman.exe\",\n \"ATBroker.exe\",\n \"DisplaySwitch.exe\",\n \"sethc.exe\"\n )\n and not process.pe.original_file_name in\n (\n \"osk.exe\",\n \"sethc.exe\",\n \"utilman2.exe\",\n \"DisplaySwitch.exe\",\n \"ATBroker.exe\",\n \"ScreenMagnifier.exe\",\n \"SR.exe\",\n \"Narrator.exe\",\n \"magnify.exe\",\n \"MAGNIFY.EXE\"\n )\n\n/* uncomment once in winlogbeat to avoid bypass with rogue process with matching pe original file name */\n/* and process.code_signature.subject_name == \"Microsoft Windows\" and process.code_signature.status == \"trusted\" */\n", "references": [ "https://www.elastic.co/blog/practical-security-engineering-stateful-detection" @@ -53,7 +53,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_run_key_and_startup_broad.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_run_key_and_startup_broad.json index 7541049e4fd3e..04da402d1caf9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_run_key_and_startup_broad.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_run_key_and_startup_broad.json @@ -10,6 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Startup or Run Key Registry Modification", + "note": "## Triage and analysis\n\n### Investigating Startup or Run Key Registry Modification\n\nAdversaries may achieve persistence by referencing a program with a registry run key. Adding an entry to the run keys\nin the registry will cause the program referenced to be executed when a user logs in. These programs will executed\nunder the context of the user and will have the account's permissions. This rule looks for this behavior by monitoring\na range of registry run keys.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There is a high possibility of benign legitimate programs being added to registry run keys. This activity could be\nbased on new software installations, patches, or any kind of network administrator related activity. Before undertaking\nfurther investigation, verify that this activity is not benign.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n- Startup Folder Persistence via Unsigned Process - 2fba96c0-ade5-4bce-b92f-a5df2509da3f\n- Startup Persistence by a Suspicious Process - 440e2db4-bc7f-4c96-a068-65b78da59bde\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "registry where registry.data.strings != null and\n registry.path : (\n /* Machine Hive */\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\\\\*\",\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnce\\\\*\",\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnceEx\\\\*\",\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\\\\Run\\\\*\",\n \"HKLM\\\\Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\Shell\\\\*\",\n /* Users Hive */\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\\\\*\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnce\\\\*\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnceEx\\\\*\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\\\\Run\\\\*\",\n \"HKEY_USERS\\\\*\\\\Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\Shell\\\\*\"\n ) and\n /* add common legitimate changes without being too restrictive as this is one of the most abused AESPs */\n not registry.data.strings : \"ctfmon.exe /n\" and\n not (registry.value : \"Application Restart #*\" and process.name : \"csrss.exe\") and\n user.id not in (\"S-1-5-18\", \"S-1-5-19\", \"S-1-5-20\") and\n not registry.data.strings : (\"?:\\\\Program Files\\\\*.exe\", \"?:\\\\Program Files (x86)\\\\*.exe\") and\n not process.executable : (\"?:\\\\Windows\\\\System32\\\\msiexec.exe\", \"?:\\\\Windows\\\\SysWOW64\\\\msiexec.exe\") and\n not (process.name : \"OneDriveSetup.exe\" and\n registry.value : (\"Delete Cached Standalone Update Binary\", \"Delete Cached Update Binary\", \"amd64\", \"Uninstall *\") and\n registry.data.strings : \"?:\\\\Windows\\\\system32\\\\cmd.exe /q /c * \\\"?:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Microsoft\\\\OneDrive\\\\*\\\"\")\n", "required_fields": [ { @@ -81,5 +82,5 @@ "timeline_title": "Comprehensive Registry Timeline", "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_sdprop_exclusion_dsheuristics.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_sdprop_exclusion_dsheuristics.json index 9d524bd69b5a8..13da283b0097d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_sdprop_exclusion_dsheuristics.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_sdprop_exclusion_dsheuristics.json @@ -49,7 +49,8 @@ "Windows", "Threat Detection", "Persistence", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -64,5 +65,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_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 index db214d1b94467..a9375cd4f50ff 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_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 @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License v2", "name": "Potential Shell via Web Server", + "note": "## Triage and analysis\n\n### Investigating Potential Shell via Web Server\n\nAdversaries may backdoor web servers with web shells to establish persistent access to systems. A web shell is a web\nscript that is placed on an openly accessible web server to allow an adversary to use the web server as a gateway into a\nnetwork. A web shell may provide a set of functions to execute or a command line interface on the system that hosts the\nweb server.\n\nThis rule detects a web server process spawning script and command line interface programs, potentially indicating\nattackers executing commands using the web shell.\n\n#### Possible investigation steps\n\n- Investigate abnormal behaviors observed by the subject process such as network connections, file modifications, and\nany other spawned child processes.\n- Examine the command line to determine which commands or scripts were executed.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- If scripts or executables were dropped, retrieve the files and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - Check if the domain is newly registered or unexpected.\n - Check the reputation of the domain or IP address.\n - File access, modification, and creation activities.\n - Cron jobs, services and other persistence mechanisms.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Any activity that triggered the alert and is not inherently\nmalicious must be monitored by the security team.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "event.category:process and event.type:(start or process_started) and\nprocess.name:(bash or dash or ash or zsh or \"python*\" or \"perl*\" or \"php*\") and\nprocess.parent.name:(\"apache\" or \"nginx\" or \"www\" or \"apache2\" or \"httpd\" or \"www-data\")\n", "references": [ "https://pentestlab.blog/tag/web-shell/" @@ -76,5 +77,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_suspicious_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_suspicious_process.json index d3e19871a157d..b477cd0148352 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_suspicious_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_suspicious_process.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Startup Persistence by a Suspicious Process", - "note": "## Triage and analysis\n\n### Investigating Startup Persistence by a Suspicious Process\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule monitors for commonly abused processes writing to the Startup folder locations.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Administrators may add programs to this mechanism via command-line shells. Before the further investigation,\nverify that this activity is not benign.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Startup Persistence by a Suspicious Process\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule monitors for commonly abused processes writing to the Startup folder locations.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Administrators may add programs to this mechanism via command-line shells. Before the further investigation,\nverify that this activity is not benign.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type != \"deletion\" and\n user.domain != \"NT AUTHORITY\" and\n file.path : (\"C:\\\\Users\\\\*\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\\\\*\",\n \"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\StartUp\\\\*\") and\n process.name : (\"cmd.exe\",\n \"powershell.exe\",\n \"wmic.exe\",\n \"mshta.exe\",\n \"pwsh.exe\",\n \"cscript.exe\",\n \"wscript.exe\",\n \"regsvr32.exe\",\n \"RegAsm.exe\",\n \"rundll32.exe\",\n \"EQNEDT32.EXE\",\n \"WINWORD.EXE\",\n \"EXCEL.EXE\",\n \"POWERPNT.EXE\",\n \"MSPUB.EXE\",\n \"MSACCESS.EXE\",\n \"iexplore.exe\",\n \"InstallUtil.exe\")\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -73,5 +74,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_unsigned_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_unsigned_process.json index 8d8a6b31fd0f9..82aa2eba13fe1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_unsigned_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_file_written_by_unsigned_process.json @@ -10,7 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Startup Folder Persistence via Unsigned Process", - "note": "## Triage and analysis\n\n### Investigating Startup Folder Persistence via Unsigned Process\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule looks for unsigned processes writing to the Startup folder locations.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There is a high possibility of benign legitimate programs being added to Startup folders. This activity could be based\non new software installations, patches, or any kind of network administrator related activity. Before entering further\ninvestigation, verify that this activity is not benign.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", + "note": "## Triage and analysis\n\n### Investigating Startup Folder Persistence via Unsigned Process\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule looks for unsigned processes writing to the Startup folder locations.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- There is a high possibility of benign legitimate programs being added to Startup folders. This activity could be based\non new software installations, patches, or any kind of network administrator related activity. Before undertaking further\ninvestigation, verify that this activity is not benign.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Persistent Scripts in the Startup Directory - f7c4dc5a-a58d-491d-9f14-9b66507121c0\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).\n", "query": "sequence by host.id, process.entity_id with maxspan=5s\n [process where event.type == \"start\" and process.code_signature.trusted == false and\n /* suspicious paths can be added here */\n process.executable : (\"C:\\\\Users\\\\*.exe\",\n \"C:\\\\ProgramData\\\\*.exe\",\n \"C:\\\\Windows\\\\Temp\\\\*.exe\",\n \"C:\\\\Windows\\\\Tasks\\\\*.exe\",\n \"C:\\\\Intel\\\\*.exe\",\n \"C:\\\\PerfLogs\\\\*.exe\")\n ]\n [file where event.type != \"deletion\" and user.domain != \"NT AUTHORITY\" and\n file.path : (\"C:\\\\Users\\\\*\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\\\\*\",\n \"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\StartUp\\\\*\")\n ]\n", "required_fields": [ { @@ -57,7 +57,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_scripts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_scripts.json index 5fce4a0cacfb0..0ba6a1a05c026 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_scripts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_startup_folder_scripts.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Persistent Scripts in the Startup Directory", - "note": "## Triage and analysis\n\n### Investigating Persistent Scripts in the Startup Directory\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule looks for shortcuts created by wscript.exe or cscript.exe, or js/vbs scripts created by any process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Startup Folder Persistence via Unsigned Process - 2fba96c0-ade5-4bce-b92f-a5df2509da3f\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Persistent Scripts in the Startup Directory\n\nThe Windows Startup folder is a special folder in Windows. Programs added to this folder are executed during account\nlogon, without user interaction, providing an excellent way for attackers to maintain persistence.\n\nThis rule looks for shortcuts created by wscript.exe or cscript.exe, or js/vbs scripts created by any process.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate\nsoftware installations.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Related rules\n\n- Suspicious Startup Shell Folder Modification - c8b150f0-0164-475b-a75e-74b47800a9ff\n- Startup Folder Persistence via Unsigned Process - 2fba96c0-ade5-4bce-b92f-a5df2509da3f\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type != \"deletion\" and user.domain != \"NT AUTHORITY\" and\n\n /* detect shortcuts created by wscript.exe or cscript.exe */\n (file.path : \"C:\\\\*\\\\Programs\\\\Startup\\\\*.lnk\" and\n process.name : (\"wscript.exe\", \"cscript.exe\")) or\n\n /* detect vbs or js files created by any process */\n file.path : (\"C:\\\\*\\\\Programs\\\\Startup\\\\*.vbs\",\n \"C:\\\\*\\\\Programs\\\\Startup\\\\*.vbe\",\n \"C:\\\\*\\\\Programs\\\\Startup\\\\*.wsh\",\n \"C:\\\\*\\\\Programs\\\\Startup\\\\*.wsf\",\n \"C:\\\\*\\\\Programs\\\\Startup\\\\*.js\")\n", "required_fields": [ { @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -73,5 +74,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_suspicious_com_hijack_registry.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_suspicious_com_hijack_registry.json index a742c05003a0f..35a9201a43fa5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_suspicious_com_hijack_registry.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_suspicious_com_hijack_registry.json @@ -10,7 +10,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Component Object Model Hijacking", - "note": "## Triage and analysis\n\n### Investigating Component Object Model Hijacking\n\nAdversaries can insert malicious code that can be executed in place of legitimate software through hijacking the COM references and relationships as a means of persistence.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file referenced in the registry and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Some Microsoft executables will reference the LocalServer32 registry key value for the location of external COM objects.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Component Object Model Hijacking\n\nAdversaries can insert malicious code that can be executed in place of legitimate software through hijacking the COM references and relationships as a means of persistence.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Identify the user account that performed the action and whether it should perform this kind of action.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file referenced in the registry and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Some Microsoft executables will reference the LocalServer32 registry key value for the location of external COM objects.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where\n (registry.path : \"HK*}\\\\InprocServer32\\\\\" and registry.data.strings: (\"scrobj.dll\", \"C:\\\\*\\\\scrobj.dll\") and\n not registry.path : \"*\\\\{06290BD*-48AA-11D2-8432-006008C3FBFC}\\\\*\")\n or\n /* in general COM Registry changes on Users Hive is less noisy and worth alerting */\n (registry.path : (\"HKEY_USERS\\\\*Classes\\\\*\\\\InprocServer32\\\\\",\n \"HKEY_USERS\\\\*Classes\\\\*\\\\LocalServer32\\\\\",\n \"HKEY_USERS\\\\*Classes\\\\*\\\\DelegateExecute\\\\\",\n \"HKEY_USERS\\\\*Classes\\\\*\\\\TreatAs\\\\\",\n \"HKEY_USERS\\\\*Classes\\\\CLSID\\\\*\\\\ScriptletURL\\\\\") and\n not (process.executable : \"?:\\\\Program Files*\\\\Veeam\\\\Backup and Replication\\\\Console\\\\veeam.backup.shell.exe\" and\n registry.path : \"HKEY_USERS\\\\S-1-5-21-*_Classes\\\\CLSID\\\\*\\\\LocalServer32\\\\\") and\n /* not necessary but good for filtering privileged installations */\n user.domain != \"NT AUTHORITY\"\n ) and\n /* removes false-positives generated by OneDrive and Teams */\n not process.name : (\"OneDrive.exe\",\"OneDriveSetup.exe\",\"FileSyncConfig.exe\",\"Teams.exe\") and\n /* Teams DLL loaded by regsvr */\n not (process.name: \"regsvr32.exe\" and\n registry.data.strings : \"*Microsoft.Teams.*.dll\")\n", "references": [ "https://bohops.com/2018/08/18/abusing-the-com-registry-structure-part-2-loading-techniques-for-evasion-and-persistence/" @@ -51,7 +51,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -79,5 +80,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json index 99f03033656ae..4c52791fc0a9c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_added_to_privileged_group_ad.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_added_to_privileged_group_ad.json index c0544624f0377..ec9c831670716 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_added_to_privileged_group_ad.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_added_to_privileged_group_ad.json @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { @@ -59,5 +60,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json index 0734ca15c8ba8..85997cb5399cd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json @@ -45,7 +45,8 @@ "Host", "Windows", "Threat Detection", - "Persistence" + "Persistence", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_update_orchestrator_service_hijack.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_update_orchestrator_service_hijack.json index 32f295c0e81d1..4836132746057 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_update_orchestrator_service_hijack.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_update_orchestrator_service_hijack.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Persistence via Update Orchestrator Service Hijack", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Persistence via Update Orchestrator Service Hijack\n\nWindows Update Orchestrator Service is a DCOM service used by other components to install Windows updates that are\nalready downloaded. Windows Update Orchestrator Service was vulnerable to elevation of privileges (any user to local\nsystem) due to an improper authorization of the callers. The vulnerability affected the Windows 10 and Windows Server\nCore products. Fixed by Microsoft on Patch Tuesday June 2020.\n\nThis rule will detect uncommon processes spawned by `svchost.exe` with `UsoSvc` as the command line parameters.\nAttackers can leverage this technique to elevate privileges or maintain persistence.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.executable : \"C:\\\\Windows\\\\System32\\\\svchost.exe\" and\n process.parent.args : \"UsoSvc\" and\n not process.executable :\n (\"?:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\UUS\\\\Packages\\\\*\\\\amd64\\\\MoUsoCoreWorker.exe\",\n \"?:\\\\Windows\\\\System32\\\\UsoClient.exe\",\n \"?:\\\\Windows\\\\System32\\\\MusNotification.exe\",\n \"?:\\\\Windows\\\\System32\\\\MusNotificationUx.exe\",\n \"?:\\\\Windows\\\\System32\\\\MusNotifyIcon.exe\",\n \"?:\\\\Windows\\\\System32\\\\WerFault.exe\",\n \"?:\\\\Windows\\\\System32\\\\WerMgr.exe\",\n \"?:\\\\Windows\\\\UUS\\\\amd64\\\\MoUsoCoreWorker.exe\",\n \"?:\\\\Windows\\\\System32\\\\MoUsoCoreWorker.exe\",\n \"?:\\\\Windows\\\\UUS\\\\amd64\\\\UsoCoreWorker.exe\",\n \"?:\\\\Windows\\\\System32\\\\UsoCoreWorker.exe\",\n \"?:\\\\Program Files\\\\Common Files\\\\microsoft shared\\\\ClickToRun\\\\OfficeC2RClient.exe\") and\n not process.name : (\"MoUsoCoreWorker.exe\", \"OfficeC2RClient.exe\")\n", "references": [ "https://github.com/irsl/CVE-2020-1313" @@ -82,5 +82,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_webshell_detection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_webshell_detection.json index 4bb454dae5cf2..69130e81a668a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_webshell_detection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_webshell_detection.json @@ -14,8 +14,8 @@ ], "language": "eql", "license": "Elastic License v2", - "name": "Webshell Detection: Script Process Child of Common Web Processes", - "note": "## Triage and analysis\n\nDetections should be investigated to identify if the activity corresponds to legitimate activity. As this rule detects post-exploitation process activity, investigations into this should be prioritized.", + "name": "Web Shell Detection: Script Process Child of Common Web Processes", + "note": "## Triage and analysis\n\n### Investigating Web Shell Detection: Script Process Child of Common Web Processes\n\nAdversaries may backdoor web servers with web shells to establish persistent access to systems. A web shell is a web\nscript that is placed on an openly accessible web server to allow an adversary to use the web server as a gateway into a\nnetwork. A web shell may provide a set of functions to execute or a command-line interface on the system that hosts the\nweb server.\n\nThis rule detects a web server process spawning script and command-line interface programs, potentially indicating\nattackers executing commands using the web shell.\n\n#### Possible investigation steps\n\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any other spawned child processes.\n- Examine the command line to determine which commands or scripts were executed.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- If scripts or executables were dropped, retrieve the files and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Any activity that triggered the alert and is not inherently\nmalicious must be monitored by the security team.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : (\"w3wp.exe\", \"httpd.exe\", \"nginx.exe\", \"php.exe\", \"php-cgi.exe\", \"tomcat.exe\") and\n process.name : (\"cmd.exe\", \"cscript.exe\", \"powershell.exe\", \"pwsh.exe\", \"powershell_ise.exe\", \"wmic.exe\", \"wscript.exe\")\n", "references": [ "https://www.microsoft.com/security/blog/2020/02/04/ghost-in-the-shell-investigating-web-shell-attacks/" @@ -89,5 +89,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_disable_uac_registry.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_disable_uac_registry.json index e54cad33c0830..04291353bfe13 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_disable_uac_registry.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_disable_uac_registry.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Disabling User Account Control via Registry Modification", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Disabling User Account Control via Registry Modification\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nAttackers may disable UAC to execute code directly in high integrity. This rule identifies registry value changes to\nbypass the UAC protection.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Analyze non-system processes executed with high integrity after UAC was disabled for unknown or suspicious processes.\n- Retrieve the suspicious processes' executables and determine if they are malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Restore UAC settings to the desired state.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "registry where event.type == \"change\" and\n registry.path :\n (\n \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\\\\EnableLUA\",\n \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\\\\ConsentPromptBehaviorAdmin\",\n \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\\\\PromptOnSecureDesktop\"\n ) and\n registry.data.strings : (\"0\", \"0x00000000\")\n", "references": [ "https://www.greyhathacker.net/?p=796", @@ -95,5 +95,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_iniscript.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_iniscript.json index e7901f8073390..b13f11a0a0994 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_iniscript.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_iniscript.json @@ -67,7 +67,8 @@ "Windows", "Threat Detection", "Privilege Escalation", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -100,5 +101,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_privileged_groups.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_privileged_groups.json index f5b8c4604f6ac..aa888ff8e3f5e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_privileged_groups.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_privileged_groups.json @@ -43,7 +43,8 @@ "Windows", "Threat Detection", "Privilege Escalation", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -71,5 +72,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_scheduled_task.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_scheduled_task.json index 6569ffb3bf6bc..f43123163d210 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_scheduled_task.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_group_policy_scheduled_task.json @@ -66,7 +66,8 @@ "Windows", "Threat Detection", "Privilege Escalation", - "Active Directory" + "Active Directory", + "has_guide" ], "threat": [ { @@ -106,5 +107,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_installertakeover.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_installertakeover.json index 87b5e7f040d5e..66325135325b2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_installertakeover.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_installertakeover.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Potential Privilege Escalation via InstallerFileTakeOver", - "note": "## Triage and analysis\n\n### Investigating Potential Privilege Escalation via InstallerFileTakeOver\n\nInstallerFileTakeOver is a weaponized escalation of privilege proof of concept (EoP PoC) to the CVE-2021-41379 vulnerability. Upon successful exploitation, an\nunprivileged user will escalate privileges to SYSTEM/NT AUTHORITY.\n\nThis rule detects the default execution of the PoC, which overwrites the `elevation_service.exe` DACL and copies itself\nto the location to escalate privileges. An attacker is able to still take over any file that is not in use (locked),\nwhich is outside the scope of this rule.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Look for additional processes spawned by the process, command lines, and network communications.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Verify whether a digital signature exists in the executable, and if it is valid.\n\n### Related rules\n\n- Suspicious DLL Loaded for Persistence or Privilege Escalation - bfeaf89b-a2a7-48a3-817f-e41829dc61ee\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Potential Privilege Escalation via InstallerFileTakeOver\n\nInstallerFileTakeOver is a weaponized escalation of privilege proof of concept (EoP PoC) to the CVE-2021-41379 vulnerability. Upon successful exploitation, an\nunprivileged user will escalate privileges to SYSTEM/NT AUTHORITY.\n\nThis rule detects the default execution of the PoC, which overwrites the `elevation_service.exe` DACL and copies itself\nto the location to escalate privileges. An attacker is able to still take over any file that is not in use (locked),\nwhich is outside the scope of this rule.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Look for additional processes spawned by the process, command lines, and network communications.\n- Assess whether this behavior is prevalent in the environment by looking for similar occurrences across hosts.\n- Retrieve the file and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- Verify whether a digital signature exists in the executable, and if it is valid.\n\n### Related rules\n\n- Suspicious DLL Loaded for Persistence or Privilege Escalation - bfeaf89b-a2a7-48a3-817f-e41829dc61ee\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "/* This rule is compatible with both Sysmon and Elastic Endpoint */\n\nprocess where event.type == \"start\" and\n (?process.Ext.token.integrity_level_name : \"System\" or\n ?winlog.event_data.IntegrityLevel : \"System\") and\n (\n (process.name : \"elevation_service.exe\" and\n not process.pe.original_file_name == \"elevation_service.exe\") or\n\n (process.parent.name : \"elevation_service.exe\" and\n process.name : (\"rundll32.exe\", \"cmd.exe\", \"powershell.exe\"))\n )\n", "references": [ "https://github.com/klinix5/InstallerFileTakeOver" @@ -58,7 +58,8 @@ "Host", "Windows", "Threat Detection", - "Privilege Escalation" + "Privilege Escalation", + "has_guide" ], "threat": [ { @@ -79,5 +80,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_persistence_phantom_dll.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_persistence_phantom_dll.json index 196676058b1fa..b116edce296b6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_persistence_phantom_dll.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_persistence_phantom_dll.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Suspicious DLL Loaded for Persistence or Privilege Escalation", - "note": "", + "note": "## Triage and analysis\n\n### Investigating Suspicious DLL Loaded for Persistence or Privilege Escalation\n\nAttackers can execute malicious code by abusing missing modules that processes try to load, enabling them to escalate\nprivileges or gain persistence. This rule identifies the loading of a non-Microsoft-signed DLL that is missing on a\ndefault Windows installation or one that can be loaded from a different location by a native Windows process.\n\n#### Possible investigation steps\n\n- Examine the DLL signature and identify the process that created it.\n - Investigate any abnormal behaviors by the process such as network connections, registry or file modifications, and\n any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Retrieve the DLL and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Any activity that triggered the alert and is not inherently\nmalicious must be monitored by the security team.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "any where\n (event.category == \"library\" or (event.category == \"process\" and event.action : \"Image loaded*\")) and\n (\n /* compatible with Elastic Endpoint Library Events */\n (dll.name : (\"wlbsctrl.dll\", \"wbemcomn.dll\", \"WptsExtensions.dll\", \"Tsmsisrv.dll\", \"TSVIPSrv.dll\", \"Msfte.dll\",\n \"wow64log.dll\", \"WindowsCoreDeviceInfo.dll\", \"Ualapi.dll\", \"wlanhlp.dll\", \"phoneinfo.dll\", \"EdgeGdi.dll\",\n \"cdpsgshims.dll\", \"windowsperformancerecordercontrol.dll\", \"diagtrack_win.dll\")\n and (dll.code_signature.trusted == false or dll.code_signature.exists == false)) or\n\n /* compatible with Sysmon EventID 7 - Image Load */\n (file.name : (\"wlbsctrl.dll\", \"wbemcomn.dll\", \"WptsExtensions.dll\", \"Tsmsisrv.dll\", \"TSVIPSrv.dll\", \"Msfte.dll\",\n \"wow64log.dll\", \"WindowsCoreDeviceInfo.dll\", \"Ualapi.dll\", \"wlanhlp.dll\", \"phoneinfo.dll\", \"EdgeGdi.dll\",\n \"cdpsgshims.dll\", \"windowsperformancerecordercontrol.dll\", \"diagtrack_win.dll\")\n and not file.code_signature.status == \"Valid\")\n )\n", "references": [ "https://itm4n.github.io/windows-dll-hijacking-clarified/", @@ -119,5 +119,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_printspooler_suspicious_spl_file.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_printspooler_suspicious_spl_file.json index 03828b39ddf49..365caf6dd1426 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_printspooler_suspicious_spl_file.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_printspooler_suspicious_spl_file.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Detects attempts to exploit privilege escalation vulnerabilities related to the Print Spooler service including CVE-2020-1048 and CVE-2020-1337. .", + "description": "Detects attempts to exploit privilege escalation vulnerabilities related to the Print Spooler service including CVE-2020-1048 and CVE-2020-1337.", "from": "now-9m", "index": [ "winlogbeat-*", @@ -11,8 +11,8 @@ ], "language": "eql", "license": "Elastic License v2", - "name": "Suspicious PrintSpooler SPL File Created", - "note": "## Threat intel\n\nRefer to CVEs, CVE-2020-1048 and CVE-2020-1337 for further information on the vulnerability and exploit. Verify that the relevant system is patched.", + "name": "Suspicious Print Spooler SPL File Created", + "note": "## Triage and analysis\n\n### Investigating Suspicious Print Spooler SPL File Created\n\nPrint Spooler is a Windows service enabled by default in all Windows clients and servers. The service manages print jobs\nby loading printer drivers, receiving files to be printed, queuing them, scheduling, etc.\n\nThe Print Spooler service has some known vulnerabilities that attackers can abuse to escalate privileges to SYSTEM, like\nCVE-2020-1048 and CVE-2020-1337. This rule looks for unusual processes writing SPL files to the location\n`?:\\Windows\\System32\\spool\\PRINTERS\\`, which is an essential step in exploiting these vulnerabilities.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- If this activity is expected and noisy in your environment, consider adding exceptions \u2014 preferably with a combination\nof process executable and file conditions.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Ensure that the machine has the latest security updates and is not running legacy Windows versions.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "file where event.type != \"deletion\" and\n file.extension : \"spl\" and\n file.path : \"?:\\\\Windows\\\\System32\\\\spool\\\\PRINTERS\\\\*\" and\n not process.name : (\"spoolsv.exe\",\n \"printfilterpipelinesvc.exe\",\n \"PrintIsolationHost.exe\",\n \"splwow64.exe\",\n \"msiexec.exe\",\n \"poqexec.exe\")\n", "references": [ "https://safebreach.com/Post/How-we-bypassed-CVE-2020-1048-Patch-and-got-CVE-2020-1337" @@ -69,5 +69,5 @@ ], "timestamp_override": "event.ingested", "type": "eql", - "version": 100 + "version": 101 } 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 index 8dc5e6ec6f221..01b6ebd880189 100644 --- 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 @@ -69,7 +69,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -90,5 +91,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_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 index 217b774ef77c1..6aeccd8896875 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Bypass UAC via Event Viewer", - "note": "## Triage and analysis\n\n### Investigating Bypass UAC via Event Viewer\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nDuring startup, `eventvwr.exe` checks the registry value of the `HKCU\\Software\\Classes\\mscfile\\shell\\open\\command`\nregistry key for the location of `mmc.exe`, which is used to open the `eventvwr.msc` saved console file. If the location\nof another binary or script is added to this registry value, it will be executed as a high-integrity process without a\nUAC prompt being displayed to the user. This rule detects this UAC bypass by monitoring processes spawned by\n`eventvwr.exe` other than `mmc.exe` and `werfault.exe`.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Bypass UAC via Event Viewer\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nDuring startup, `eventvwr.exe` checks the registry value of the `HKCU\\Software\\Classes\\mscfile\\shell\\open\\command`\nregistry key for the location of `mmc.exe`, which is used to open the `eventvwr.msc` saved console file. If the location\nof another binary or script is added to this registry value, it will be executed as a high-integrity process without a\nUAC prompt being displayed to the user. This rule detects this UAC bypass by monitoring processes spawned by\n`eventvwr.exe` other than `mmc.exe` and `werfault.exe`.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name : \"eventvwr.exe\" and\n not process.executable :\n (\"?:\\\\Windows\\\\SysWOW64\\\\mmc.exe\",\n \"?:\\\\Windows\\\\System32\\\\mmc.exe\",\n \"?:\\\\Windows\\\\SysWOW64\\\\WerFault.exe\",\n \"?:\\\\Windows\\\\System32\\\\WerFault.exe\")\n", "required_fields": [ { @@ -40,7 +40,8 @@ "Host", "Windows", "Threat Detection", - "Privilege Escalation" + "Privilege Escalation", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_mock_windir.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_mock_windir.json index a4621ff4b883a..a1ae394cbcd9a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_mock_windir.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_mock_windir.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "UAC Bypass Attempt via Windows Directory Masquerading", - "note": "## Triage and analysis\n\n### Investigating UAC Bypass Attempt via Windows Directory Masquerading\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nThis rule identifies an attempt to bypass User Account Control (UAC) by masquerading as a Microsoft trusted Windows\ndirectory. Attackers may bypass UAC to stealthily execute code with elevated permissions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- If any of the spawned processes are suspicious, retrieve them and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating UAC Bypass Attempt via Windows Directory Masquerading\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nThis rule identifies an attempt to bypass User Account Control (UAC) by masquerading as a Microsoft trusted Windows\ndirectory. Attackers may bypass UAC to stealthily execute code with elevated permissions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- If any of the spawned processes are suspicious, retrieve them and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.args : (\"C:\\\\Windows \\\\system32\\\\*.exe\", \"C:\\\\Windows \\\\SysWOW64\\\\*.exe\")\n", "references": [ "https://medium.com/tenable-techblog/uac-bypass-by-mocking-trusted-directories-24a96675f6e" @@ -38,7 +38,8 @@ "Host", "Windows", "Threat Detection", - "Privilege Escalation" + "Privilege Escalation", + "has_guide" ], "threat": [ { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_winfw_mmc_hijack.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_winfw_mmc_hijack.json index 0ed27cf021601..877d0a3ca31a6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_winfw_mmc_hijack.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_winfw_mmc_hijack.json @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "UAC Bypass via Windows Firewall Snap-In Hijack", - "note": "## Triage and analysis\n\n### Investigating UAC Bypass via Windows Firewall Snap-In Hijack\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nThis rule identifies attempts to bypass User Account Control (UAC) by hijacking the Microsoft Management Console (MMC)\nWindows Firewall snap-in. Attackers bypass UAC to stealthily execute code with elevated permissions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behaviors in the alert timeframe.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- If any of the spawned processes are suspicious, retrieve them and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating UAC Bypass via Windows Firewall Snap-In Hijack\n\nWindows User Account Control (UAC) allows a program to elevate its privileges (tracked as low to high integrity levels)\nto perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\nUAC can deny an operation under high-integrity enforcement, or allow the user to perform the action if they are in the\nlocal administrators group and enter an administrator password when prompted.\n\nFor more information about the UAC and how it works, check the [official Microsoft docs page](https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works).\n\nThis rule identifies attempts to bypass User Account Control (UAC) by hijacking the Microsoft Management Console (MMC)\nWindows Firewall snap-in. Attackers bypass UAC to stealthily execute code with elevated permissions.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Inspect the host for suspicious or abnormal behavior in the alert timeframe.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- If any of the spawned processes are suspicious, retrieve them and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell `Get-FileHash` cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are\nidentified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business\nsystems, and web services.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\n process.parent.name == \"mmc.exe\" and\n /* process.Ext.token.integrity_level_name == \"high\" can be added in future for tuning */\n /* args of the Windows Firewall SnapIn */\n process.parent.args == \"WF.msc\" and process.name != \"WerFault.exe\"\n", "references": [ "https://github.com/AzAgarampur/byeintegrity-uac" @@ -48,7 +48,8 @@ "Host", "Windows", "Threat Detection", - "Privilege Escalation" + "Privilege Escalation", + "has_guide" ], "threat": [ { 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 index addabf9f61bdd..253a10c4d45a0 100644 --- 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 @@ -12,7 +12,7 @@ "language": "eql", "license": "Elastic License v2", "name": "Unusual Parent-Child Relationship", - "note": "## Triage and analysis\n\n### Investigating Unusual Parent-Child Relationship\n\nWindows internal/system processes have some characteristics that can be used to spot suspicious activities. One of these\ncharacteristics is parent-child relationships. These relationships can be used to baseline the typical behavior of the\nsystem and then alert on occurrences that don't comply with the baseline.\n\nThis rule uses this information to spot suspicious parent and child processes.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate abnormal behaviors observed by the subject process such as network connections, registry or file\nmodifications, and any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled tasks creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", + "note": "## Triage and analysis\n\n### Investigating Unusual Parent-Child Relationship\n\nWindows internal/system processes have some characteristics that can be used to spot suspicious activities. One of these\ncharacteristics is parent-child relationships. These relationships can be used to baseline the typical behavior of the\nsystem and then alert on occurrences that don't comply with the baseline.\n\nThis rule uses this information to spot suspicious parent and child processes.\n\n#### Possible investigation steps\n\n- Investigate the process execution chain (parent process tree) for unknown processes. Examine their executable files\nfor prevalence, whether they are located in expected locations, and if they are signed with valid digital signatures.\n- Investigate other alerts associated with the user/host during the past 48 hours.\n- Investigate any abnormal behavior by the subject process such as network connections, registry or file modifications,\nand any spawned child processes.\n- Retrieve the process executable and determine if it is malicious:\n - Use a private sandboxed malware analysis system to perform analysis.\n - Observe and collect information about the following activities:\n - Attempts to contact external domains and addresses.\n - File and registry access, modification, and creation activities.\n - Service creation and launch activities.\n - Scheduled task creation.\n - Use the PowerShell Get-FileHash cmdlet to get the files' SHA-256 hash values.\n - Search for the existence and reputation of the hashes in resources like VirusTotal, Hybrid-Analysis, CISCO Talos, Any.run, etc.\n\n### False positive analysis\n\n- This activity is unlikely to happen legitimately. Benign true positives (B-TPs) can be added as exceptions if necessary.\n\n### Response and remediation\n\n- Initiate the incident response process based on the outcome of the triage.\n- Isolate the involved host to prevent further post-compromise behavior.\n- If the triage identified malware, search the environment for additional compromised hosts.\n - Implement temporary network rules, procedures, and segmentation to contain the malware.\n - Stop suspicious processes.\n - Immediately block the identified indicators of compromise (IoCs).\n - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that\n attackers could use to reinfect the system.\n- Remove and block malicious artifacts identified during triage.\n- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and\nmalware components.\n- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.\n- Using the incident response data, update logging and audit policies to improve the mean time to detect (MTTD) and the\nmean time to respond (MTTR).", "query": "process where event.type == \"start\" and\nprocess.parent.name != null and\n (\n /* suspicious parent processes */\n (process.name:\"autochk.exe\" and not process.parent.name:\"smss.exe\") or\n (process.name:(\"fontdrvhost.exe\", \"dwm.exe\") and not process.parent.name:(\"wininit.exe\", \"winlogon.exe\")) or\n (process.name:(\"consent.exe\", \"RuntimeBroker.exe\", \"TiWorker.exe\") and not process.parent.name:\"svchost.exe\") or\n (process.name:\"SearchIndexer.exe\" and not process.parent.name:\"services.exe\") or\n (process.name:\"SearchProtocolHost.exe\" and not process.parent.name:(\"SearchIndexer.exe\", \"dllhost.exe\")) or\n (process.name:\"dllhost.exe\" and not process.parent.name:(\"services.exe\", \"svchost.exe\")) or\n (process.name:\"smss.exe\" and not process.parent.name:(\"System\", \"smss.exe\")) or\n (process.name:\"csrss.exe\" and not process.parent.name:(\"smss.exe\", \"svchost.exe\")) or\n (process.name:\"wininit.exe\" and not process.parent.name:\"smss.exe\") or\n (process.name:\"winlogon.exe\" and not process.parent.name:\"smss.exe\") or\n (process.name:(\"lsass.exe\", \"LsaIso.exe\") and not process.parent.name:\"wininit.exe\") or\n (process.name:\"LogonUI.exe\" and not process.parent.name:(\"wininit.exe\", \"winlogon.exe\")) or\n (process.name:\"services.exe\" and not process.parent.name:\"wininit.exe\") or\n (process.name:\"svchost.exe\" and not process.parent.name:(\"MsMpEng.exe\", \"services.exe\")) or\n (process.name:\"spoolsv.exe\" and not process.parent.name:\"services.exe\") or\n (process.name:\"taskhost.exe\" and not process.parent.name:(\"services.exe\", \"svchost.exe\")) or\n (process.name:\"taskhostw.exe\" and not process.parent.name:(\"services.exe\", \"svchost.exe\")) or\n (process.name:\"userinit.exe\" and not process.parent.name:(\"dwm.exe\", \"winlogon.exe\")) or\n (process.name:(\"wmiprvse.exe\", \"wsmprovhost.exe\", \"winrshost.exe\") and not process.parent.name:\"svchost.exe\") or\n /* suspicious child processes */\n (process.parent.name:(\"SearchProtocolHost.exe\", \"taskhost.exe\", \"csrss.exe\") and not process.name:(\"werfault.exe\", \"wermgr.exe\", \"WerFaultSecure.exe\")) or\n (process.parent.name:\"autochk.exe\" and not process.name:(\"chkdsk.exe\", \"doskey.exe\", \"WerFault.exe\")) or\n (process.parent.name:\"smss.exe\" and not process.name:(\"autochk.exe\", \"smss.exe\", \"csrss.exe\", \"wininit.exe\", \"winlogon.exe\", \"setupcl.exe\", \"WerFault.exe\")) or\n (process.parent.name:\"wermgr.exe\" and not process.name:(\"WerFaultSecure.exe\", \"wermgr.exe\", \"WerFault.exe\")) or\n (process.parent.name:\"conhost.exe\" and not process.name:(\"mscorsvw.exe\", \"wermgr.exe\", \"WerFault.exe\", \"WerFaultSecure.exe\"))\n )\n", "references": [ "https://github.com/sbousseaden/Slides/blob/master/Hunting%20MindMaps/PNG/Windows%20Processes%20TH.map.png", @@ -44,7 +44,8 @@ "Host", "Windows", "Threat Detection", - "Privilege Escalation" + "Privilege Escalation", + "has_guide" ], "threat": [ { 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 index 9045cc9217fbb..b632697515ada 100644 --- 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 @@ -59,7 +59,8 @@ "AWS", "Continuous Monitoring", "SecOps", - "Identity and Access" + "Identity and Access", + "has_guide" ], "threat": [ { @@ -80,5 +81,5 @@ ], "timestamp_override": "event.ingested", "type": "query", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_filebeat8x.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_filebeat8x.json index 8c4ad87e57532..2e1094d9b4fca 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_filebeat8x.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_filebeat8x.json @@ -63,7 +63,8 @@ "Network", "Continuous Monitoring", "SecOps", - "Monitoring" + "Monitoring", + "has_guide" ], "threat_filters": [ { @@ -226,5 +227,5 @@ "timeline_id": "495ad7a7-316e-4544-8a0f-9c098daee76e", "timeline_title": "Generic Threat Match Timeline", "type": "threat_match", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_fleet_integrations.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_fleet_integrations.json index b35e5f72b20fb..62a1da18f9e6f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_fleet_integrations.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/threat_intel_fleet_integrations.json @@ -63,7 +63,8 @@ "Network", "Continuous Monitoring", "SecOps", - "Monitoring" + "Monitoring", + "has_guide" ], "threat_filters": [ { @@ -226,5 +227,5 @@ "timeline_id": "495ad7a7-316e-4544-8a0f-9c098daee76e", "timeline_title": "Generic Threat Match Timeline", "type": "threat_match", - "version": 100 + "version": 101 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.test.ts index d19e7cabe6769..93e37c41c8ab3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.test.ts @@ -45,7 +45,7 @@ describe('eql_executor', () => { describe('eqlExecutor', () => { it('should set a warning when exception list for eql rule contains value list exceptions', async () => { - await eqlExecutor({ + const result = await eqlExecutor({ inputIndex: DEFAULT_INDEX_PATTERN, runtimeMappings: {}, completeRule: eqlCompleteRule, @@ -60,10 +60,11 @@ describe('eql_executor', () => { exceptionFilter: undefined, unprocessedExceptions: [getExceptionListItemSchemaMock()], }); - expect(ruleExecutionLogger.warn).toHaveBeenCalled(); - expect(ruleExecutionLogger.warn.mock.calls[0][0]).toContain( - "The following exceptions won't be applied to rule execution" - ); + expect(result.warningMessages).toEqual([ + `The following exceptions won't be applied to rule execution: ${ + getExceptionListItemSchemaMock().name + }`, + ]); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.ts index 9622e09d37374..436ebec9c27c1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/eql.ts @@ -29,7 +29,7 @@ import { addToSearchAfterReturn, createSearchAfterReturnType, makeFloatString, - logUnprocessedExceptionsWarnings, + getUnprocessedExceptionsWarnings, } from '../utils'; import { buildReasonMessageForEqlAlert } from '../reason_formatters'; import type { CompleteRule, EqlRuleParams } from '../../schemas/rule_schemas'; @@ -93,8 +93,10 @@ export const eqlExecutor = async ({ }); ruleExecutionLogger.debug(`EQL query request: ${JSON.stringify(request)}`); - logUnprocessedExceptionsWarnings(unprocessedExceptions, ruleExecutionLogger); - + const exceptionsWarning = getUnprocessedExceptionsWarnings(unprocessedExceptions); + if (exceptionsWarning) { + result.warningMessages.push(exceptionsWarning); + } const eqlSignalSearchStart = performance.now(); const response = await services.scopedClusterClient.asCurrentUser.eql.search( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.test.ts index dd62af6bfea13..832ffa1e5b5c4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.test.ts @@ -141,7 +141,7 @@ describe('threshold_executor', () => { [`${getThresholdTermsHash(terms2)}`]: signalHistoryRecord2, }, }; - await thresholdExecutor({ + const result = await thresholdExecutor({ completeRule: thresholdCompleteRule, tuple, services: alertServices, @@ -165,10 +165,11 @@ describe('threshold_executor', () => { exceptionFilter: undefined, unprocessedExceptions: [getExceptionListItemSchemaMock()], }); - expect(ruleExecutionLogger.warn).toHaveBeenCalled(); - expect(ruleExecutionLogger.warn.mock.calls[0][0]).toContain( - "The following exceptions won't be applied to rule execution" - ); + expect(result.warningMessages).toEqual([ + `The following exceptions won't be applied to rule execution: ${ + getExceptionListItemSchemaMock().name + }`, + ]); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.ts index 398bce577689b..ed82f7cdb1f8a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/executors/threshold.ts @@ -34,7 +34,7 @@ import type { import { addToSearchAfterReturn, createSearchAfterReturnType, - logUnprocessedExceptionsWarnings, + getUnprocessedExceptionsWarnings, } from '../utils'; import { withSecuritySpan } from '../../../../utils/with_security_span'; import { buildThresholdSignalHistory } from '../threshold/build_signal_history'; @@ -81,7 +81,10 @@ export const thresholdExecutor = async ({ const ruleParams = completeRule.ruleParams; return withSecuritySpan('thresholdExecutor', async () => { - logUnprocessedExceptionsWarnings(unprocessedExceptions, ruleExecutionLogger); + const exceptionsWarning = getUnprocessedExceptionsWarnings(unprocessedExceptions); + if (exceptionsWarning) { + result.warningMessages.push(exceptionsWarning); + } // Get state or build initial state (on upgrade) const { signalHistory, searchErrors: previousSearchErrors } = state.initialized diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts index bc22ca9ea44d9..521fdf1e5a595 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts @@ -97,13 +97,10 @@ export const getFilter = async ({ index, exceptionFilter, }); - } else if (savedId && index != null) { - // if savedId present and we ending up here, then saved query failed to be fetched - // and we also didn't fall back to saved in rule query - throw Error(`Failed to fetch saved query. "${err.message}"`); } else { // user did not give any additional fall back mechanism for generating a rule // rethrow error for activity monitoring + err.message = `Failed to fetch saved query. "${err.message}"`; throw err; } } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/preview/alert_instance_factory_stub.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/preview/alert_instance_factory_stub.ts index b73119d15077a..a3cf4ebc95d7c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/preview/alert_instance_factory_stub.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/preview/alert_instance_factory_stub.ts @@ -37,16 +37,6 @@ export const alertInstanceFactoryStub = < meta: { lastScheduledActions: { group: 'default', date: new Date() } }, }); }, - scheduleActionsWithSubGroup( - actionGroup: TActionGroupIds, - subgroup: string, - alertcontext: TInstanceContext - ) { - return new Alert('', { - state: {} as TInstanceState, - meta: { lastScheduledActions: { group: 'default', date: new Date() } }, - }); - }, setContext(alertContext: TInstanceContext) { return new Alert('', { state: {} as TInstanceState, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts index d80e5cba026b0..0ab6ec2a01dda 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts @@ -65,6 +65,7 @@ export const createThreatSignals = async ({ let results: SearchAfterAndBulkCreateReturnType = { success: true, warning: false, + enrichmentTimes: [], bulkCreateTimes: [], searchAfterTimes: [], lastLookBackDate: null, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.test.ts index 981868589e4a1..0bcdc8450a830 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.test.ts @@ -55,6 +55,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -67,6 +68,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -83,6 +85,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -95,6 +98,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -111,6 +115,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -123,6 +128,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -139,6 +145,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -151,6 +158,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -162,6 +170,7 @@ describe('utils', () => { expect.objectContaining({ searchAfterTimes: ['60'], bulkCreateTimes: ['50'], + enrichmentTimes: ['6'], }) ); }); @@ -172,6 +181,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -184,6 +194,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -296,6 +307,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -307,6 +319,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['30'], // max value from existingResult.searchAfterTimes bulkCreateTimes: ['25'], // max value from existingResult.bulkCreateTimes + enrichmentTimes: ['3'], // max value from existingResult.enrichmentTimes lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -323,6 +336,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -334,6 +348,7 @@ describe('utils', () => { warning: false, searchAfterTimes: [], bulkCreateTimes: [], + enrichmentTimes: [], lastLookBackDate: undefined, createdSignalsCount: 0, createdSignals: [], @@ -345,6 +360,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['30'], // max value from existingResult.searchAfterTimes bulkCreateTimes: ['25'], // max value from existingResult.bulkCreateTimes + enrichmentTimes: ['3'], // max value from existingResult.enrichmentTimes lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -362,6 +378,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], // max is 30 bulkCreateTimes: ['5', '15', '25'], // max is 25 + enrichmentTimes: ['1', '2', '3'], // max is 3 lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -373,6 +390,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), @@ -384,6 +402,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['40', '5', '15'], bulkCreateTimes: ['50', '5', '15'], + enrichmentTimes: ['4', '2', '3'], lastLookBackDate: new Date('2020-09-16T04:34:32.390Z'), createdSignalsCount: 8, createdSignals: Array(8).fill(sampleSignalHit()), @@ -396,6 +415,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['70'], // max value between newResult1 and newResult2 + max array value of existingResult (40 + 30 = 70) bulkCreateTimes: ['75'], // max value between newResult1 and newResult2 + max array value of existingResult (50 + 25 = 75) + enrichmentTimes: ['7'], // max value between newResult1 and newResult2 + max array value of existingResult (4 + 3 = 7) lastLookBackDate: new Date('2020-09-16T04:34:32.390Z'), // max lastLookBackDate createdSignalsCount: 16, // all the signals counted together (8 + 5 + 3) createdSignals: Array(16).fill(sampleSignalHit()), @@ -413,6 +433,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], // max is 30 bulkCreateTimes: ['5', '15', '25'], // max is 25 + enrichmentTimes: ['1', '2', '3'], // max is 3 lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -424,6 +445,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), @@ -435,6 +457,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['40', '5', '15'], bulkCreateTimes: ['50', '5', '15'], + enrichmentTimes: ['5', '2', '3'], lastLookBackDate: new Date('2020-09-16T04:34:32.390Z'), createdSignalsCount: 8, createdSignals: Array(8).fill(sampleSignalHit()), @@ -447,6 +470,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['70'], // max value between newResult1 and newResult2 + max array value of existingResult (40 + 30 = 70) bulkCreateTimes: ['75'], // max value between newResult1 and newResult2 + max array value of existingResult (50 + 25 = 75) + enrichmentTimes: ['8'], // max value between newResult1 and newResult2 + max array value of existingResult (50 + 3 = 8) lastLookBackDate: new Date('2020-09-16T04:34:32.390Z'), // max lastLookBackDate createdSignalsCount: 16, // all the signals counted together (8 + 5 + 3) createdSignals: Array(16).fill(sampleSignalHit()), @@ -464,6 +488,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], // max is 30 bulkCreateTimes: ['5', '15', '25'], // max is 25 + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -475,6 +500,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), @@ -486,6 +512,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['40', '5', '15'], bulkCreateTimes: ['50', '5', '15'], + enrichmentTimes: ['5', '2', '3'], lastLookBackDate: null, createdSignalsCount: 8, createdSignals: Array(8).fill(sampleSignalHit()), @@ -498,6 +525,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['70'], // max value between newResult1 and newResult2 + max array value of existingResult (40 + 30 = 70) bulkCreateTimes: ['75'], // max value between newResult1 and newResult2 + max array value of existingResult (50 + 25 = 75) + enrichmentTimes: ['8'], // max value between newResult1 and newResult2 + max array value of existingResult (5 + 3 = 8) lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), // max lastLookBackDate createdSignalsCount: 16, // all the signals counted together (8 + 5 + 3) createdSignals: Array(16).fill(sampleSignalHit()), @@ -515,6 +543,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -527,6 +556,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['5', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -543,6 +573,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -555,6 +586,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -571,6 +603,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -583,6 +616,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -599,6 +633,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -611,6 +646,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -632,6 +668,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: undefined, createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), @@ -644,6 +681,7 @@ describe('utils', () => { warning: false, searchAfterTimes: ['10', '20', '30'], bulkCreateTimes: ['5', '15', '25'], + enrichmentTimes: ['1', '2', '3'], lastLookBackDate: new Date('2020-09-16T03:34:32.390Z'), createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.ts index bfba9a6fd22a1..a73ead0bf946d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/utils.ts @@ -70,6 +70,7 @@ export const combineResults = ( ): SearchAfterAndBulkCreateReturnType => ({ success: currentResult.success === false ? false : newResult.success, warning: currentResult.warning || newResult.warning, + enrichmentTimes: calculateAdditiveMax(currentResult.enrichmentTimes, newResult.enrichmentTimes), bulkCreateTimes: calculateAdditiveMax(currentResult.bulkCreateTimes, newResult.bulkCreateTimes), searchAfterTimes: calculateAdditiveMax( currentResult.searchAfterTimes, @@ -94,6 +95,7 @@ export const combineConcurrentResults = ( const maxedNewResult = newResult.reduce( (accum, item) => { const maxSearchAfterTime = calculateMax(accum.searchAfterTimes, item.searchAfterTimes); + const maxEnrichmentTimes = calculateMax(accum.enrichmentTimes, item.enrichmentTimes); const maxBulkCreateTimes = calculateMax(accum.bulkCreateTimes, item.bulkCreateTimes); const lastLookBackDate = calculateMaxLookBack(accum.lastLookBackDate, item.lastLookBackDate); return { @@ -101,6 +103,7 @@ export const combineConcurrentResults = ( warning: accum.warning || item.warning, searchAfterTimes: [maxSearchAfterTime], bulkCreateTimes: [maxBulkCreateTimes], + enrichmentTimes: [maxEnrichmentTimes], lastLookBackDate, createdSignalsCount: accum.createdSignalsCount + item.createdSignalsCount, createdSignals: [...accum.createdSignals, ...item.createdSignals], @@ -113,6 +116,7 @@ export const combineConcurrentResults = ( warning: false, searchAfterTimes: [], bulkCreateTimes: [], + enrichmentTimes: [], lastLookBackDate: undefined, createdSignalsCount: 0, createdSignals: [], 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 93ddadf826d73..f786a28b50044 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 @@ -286,6 +286,7 @@ export interface SearchAfterAndBulkCreateReturnType { success: boolean; warning: boolean; searchAfterTimes: string[]; + enrichmentTimes: string[]; bulkCreateTimes: string[]; lastLookBackDate: Date | null | undefined; createdSignalsCount: number; 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 afbcb355da05f..d80ed256a0de0 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 @@ -45,7 +45,7 @@ import { isDetectionAlert, getField, addToSearchAfterReturn, - logUnprocessedExceptionsWarnings, + getUnprocessedExceptionsWarnings, } from './utils'; import type { BulkResponseErrorAggregation, SearchAfterAndBulkCreateReturnType } from './types'; import { @@ -953,6 +953,7 @@ describe('utils', () => { }); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignalsCount: 0, createdSignals: [], errors: [], @@ -973,6 +974,7 @@ describe('utils', () => { }); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignalsCount: 0, createdSignals: [], errors: [], @@ -1291,6 +1293,7 @@ describe('utils', () => { const searchAfterReturnType = createSearchAfterReturnType(); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignalsCount: 0, createdSignals: [], errors: [], @@ -1306,6 +1309,7 @@ describe('utils', () => { test('createSearchAfterReturnType can override all values', () => { const searchAfterReturnType = createSearchAfterReturnType({ bulkCreateTimes: ['123'], + enrichmentTimes: [], createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), errors: ['error 1'], @@ -1317,6 +1321,7 @@ describe('utils', () => { }); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: ['123'], + enrichmentTimes: [], createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), errors: ['error 1'], @@ -1337,6 +1342,7 @@ describe('utils', () => { }); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignalsCount: 5, createdSignals: Array(5).fill(sampleSignalHit()), errors: ['error 1'], @@ -1355,6 +1361,7 @@ describe('utils', () => { const merged = mergeReturns([createSearchAfterReturnType(), createSearchAfterReturnType()]); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: [], + enrichmentTimes: [], createdSignalsCount: 0, createdSignals: [], errors: [], @@ -1411,6 +1418,7 @@ describe('utils', () => { const merged = mergeReturns([ createSearchAfterReturnType({ bulkCreateTimes: ['123'], + enrichmentTimes: [], createdSignalsCount: 3, createdSignals: Array(3).fill(sampleSignalHit()), errors: ['error 1', 'error 2'], @@ -1421,6 +1429,7 @@ describe('utils', () => { }), createSearchAfterReturnType({ bulkCreateTimes: ['456'], + enrichmentTimes: [], createdSignalsCount: 2, createdSignals: Array(2).fill(sampleSignalHit()), errors: ['error 3'], @@ -1433,6 +1442,7 @@ describe('utils', () => { ]); const expected: SearchAfterAndBulkCreateReturnType = { bulkCreateTimes: ['123', '456'], // concatenates the prev and next together + enrichmentTimes: [], createdSignalsCount: 5, // Adds the 3 and 2 together createdSignals: Array(5).fill(sampleSignalHit()), errors: ['error 1', 'error 2', 'error 3'], // concatenates the prev and next together @@ -1452,6 +1462,7 @@ describe('utils', () => { const next: GenericBulkCreateResponse = { success: false, bulkCreateDuration: '100', + enrichmentDuration: '0', createdItemsCount: 1, createdItems: [], errors: ['new error'], @@ -1469,6 +1480,7 @@ describe('utils', () => { const next: GenericBulkCreateResponse = { success: true, bulkCreateDuration: '0', + enrichmentDuration: '0', createdItemsCount: 0, createdItems: [], errors: ['error 1'], @@ -1484,6 +1496,7 @@ describe('utils', () => { const next: GenericBulkCreateResponse = { success: true, bulkCreateDuration: '0', + enrichmentDuration: '0', createdItemsCount: 0, createdItems: [], errors: ['error 2'], @@ -1667,14 +1680,13 @@ describe('utils', () => { describe('logUnprocessedExceptionsWarnings', () => { test('does not log anything when the array is empty', () => { - logUnprocessedExceptionsWarnings([], ruleExecutionLogger); - expect(ruleExecutionLogger.warn).not.toHaveBeenCalled(); + const result = getUnprocessedExceptionsWarnings([]); + expect(result).toBeUndefined(); }); test('logs the exception names when there are unprocessed exceptions', () => { - logUnprocessedExceptionsWarnings([getExceptionListItemSchemaMock()], ruleExecutionLogger); - expect(ruleExecutionLogger.warn).toHaveBeenCalled(); - expect(ruleExecutionLogger.warn.mock.calls[0][0]).toContain( + const result = getUnprocessedExceptionsWarnings([getExceptionListItemSchemaMock()]); + expect(result).toEqual( `The following exceptions won't be applied to rule execution: ${ getExceptionListItemSchemaMock().name }` 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 a7fe9dfaf6c30..24b5b068d5689 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 @@ -649,6 +649,7 @@ export const createSearchAfterReturnType = ({ success, warning, searchAfterTimes, + enrichmentTimes, bulkCreateTimes, lastLookBackDate, createdSignalsCount, @@ -659,6 +660,7 @@ export const createSearchAfterReturnType = ({ success?: boolean | undefined; warning?: boolean; searchAfterTimes?: string[] | undefined; + enrichmentTimes?: string[] | undefined; bulkCreateTimes?: string[] | undefined; lastLookBackDate?: Date | undefined; createdSignalsCount?: number | undefined; @@ -670,6 +672,7 @@ export const createSearchAfterReturnType = ({ success: success ?? true, warning: warning ?? false, searchAfterTimes: searchAfterTimes ?? [], + enrichmentTimes: enrichmentTimes ?? [], bulkCreateTimes: bulkCreateTimes ?? [], lastLookBackDate: lastLookBackDate ?? null, createdSignalsCount: createdSignalsCount ?? 0, @@ -715,6 +718,7 @@ export const addToSearchAfterReturn = ({ current.createdSignalsCount += next.createdItemsCount; current.createdSignals.push(...next.createdItems); current.bulkCreateTimes.push(next.bulkCreateDuration); + current.enrichmentTimes.push(next.enrichmentDuration); current.errors = [...new Set([...current.errors, ...next.errors])]; }; @@ -727,6 +731,7 @@ export const mergeReturns = ( warning: existingWarning, searchAfterTimes: existingSearchAfterTimes, bulkCreateTimes: existingBulkCreateTimes, + enrichmentTimes: existingEnrichmentTimes, lastLookBackDate: existingLastLookBackDate, createdSignalsCount: existingCreatedSignalsCount, createdSignals: existingCreatedSignals, @@ -738,6 +743,7 @@ export const mergeReturns = ( success: newSuccess, warning: newWarning, searchAfterTimes: newSearchAfterTimes, + enrichmentTimes: newEnrichmentTimes, bulkCreateTimes: newBulkCreateTimes, lastLookBackDate: newLastLookBackDate, createdSignalsCount: newCreatedSignalsCount, @@ -750,6 +756,7 @@ export const mergeReturns = ( success: existingSuccess && newSuccess, warning: existingWarning || newWarning, searchAfterTimes: [...existingSearchAfterTimes, ...newSearchAfterTimes], + enrichmentTimes: [...existingEnrichmentTimes, ...newEnrichmentTimes], bulkCreateTimes: [...existingBulkCreateTimes, ...newBulkCreateTimes], lastLookBackDate: newLastLookBackDate ?? existingLastLookBackDate, createdSignalsCount: existingCreatedSignalsCount + newCreatedSignalsCount, @@ -972,14 +979,13 @@ export const getField = (event: SimpleHit, field: string): SearchTypes | undefin } }; -export const logUnprocessedExceptionsWarnings = ( - unprocessedExceptions: ExceptionListItemSchema[], - ruleExecutionLogger: IRuleExecutionLogForExecutors -) => { +export const getUnprocessedExceptionsWarnings = ( + unprocessedExceptions: ExceptionListItemSchema[] +): string | undefined => { if (unprocessedExceptions.length > 0) { const exceptionNames = unprocessedExceptions.map((exception) => exception.name); - ruleExecutionLogger.warn( - `The following exceptions won't be applied to rule execution: ${exceptionNames.join(', ')}` - ); + return `The following exceptions won't be applied to rule execution: ${exceptionNames.join( + ', ' + )}`; } }; diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/artifact.ts b/x-pack/plugins/security_solution/server/lib/telemetry/artifact.ts index 46d0d6e665c4f..07ec2b6f2e49a 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/artifact.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/artifact.ts @@ -26,7 +26,7 @@ class Artifact implements IArtifact { this.receiver = receiver; this.esClusterInfo = await this.receiver.fetchClusterInfo(); const version = this.esClusterInfo?.version?.number; - this.manifestUrl = `${this.CDN_URL}/downloads/endpoint/manifest/artifacts-${version}.zip`; + this.manifestUrl = `${this.CDN_URL}/downloads/kibana/manifest/artifacts-${version}.zip`; } public async getArtifact(name: string): Promise { diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts index f664fccbf75d8..d266d2f1c7699 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts @@ -29,7 +29,7 @@ export function createTelemetryConfigurationTaskConfig() { taskExecutionPeriod: TaskExecutionPeriod ) => { try { - const artifactName = 'telemetry-configuration-v1'; + const artifactName = 'telemetry-buffer-and-batch-sizes-v1'; const configArtifact = (await artifactService.getArtifact( artifactName )) as unknown as TelemetryConfiguration; diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index 0552f9bb2bd00..a71048462b5e6 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -307,7 +307,9 @@ export class Plugin implements ISecuritySolutionPlugin { NEW_TERMS_RULE_TYPE_ID, ]; - plugins.features.registerKibanaFeature(getKibanaPrivilegesFeaturePrivileges(ruleTypes)); + plugins.features.registerKibanaFeature( + getKibanaPrivilegesFeaturePrivileges(ruleTypes, experimentalFeatures) + ); plugins.features.registerKibanaFeature(getCasesKibanaFeature()); if (plugins.alerting != null) { @@ -471,6 +473,7 @@ export class Plugin implements ISecuritySolutionPlugin { exceptionListsClient: exceptionListClient, registerListsServerExtension: this.lists?.registerExtension, featureUsageService, + experimentalFeatures: config.experimentalFeatures, }); this.telemetryReceiver.start( diff --git a/x-pack/plugins/security_solution/server/request_context_factory.ts b/x-pack/plugins/security_solution/server/request_context_factory.ts index b0eb6b1d7dbd9..730cbd259f50e 100644 --- a/x-pack/plugins/security_solution/server/request_context_factory.ts +++ b/x-pack/plugins/security_solution/server/request_context_factory.ts @@ -79,6 +79,9 @@ export class RequestContextFactory implements IRequestContextFactory { (await context.fleet)?.authz ?? (await startPlugins.fleet?.authz.fromRequest(request)); } + const isEndpointRbacEnabled = + endpointAppContextService.experimentalFeatures.endpointRbacEnabled; + const coreContext = await context.core; return { @@ -92,7 +95,12 @@ export class RequestContextFactory implements IRequestContextFactory { endpointAuthz = getEndpointAuthzInitialState(); } else { const userRoles = security?.authc.getCurrentUser(request)?.roles ?? []; - endpointAuthz = calculateEndpointAuthz(licenseService, fleetAuthz, userRoles); + endpointAuthz = calculateEndpointAuthz( + licenseService, + fleetAuthz, + userRoles, + isEndpointRbacEnabled + ); } } diff --git a/x-pack/plugins/security_solution/server/usage/collector.ts b/x-pack/plugins/security_solution/server/usage/collector.ts index e14af8c553736..6f526051f17d1 100644 --- a/x-pack/plugins/security_solution/server/usage/collector.ts +++ b/x-pack/plugins/security_solution/server/usage/collector.ts @@ -414,6 +414,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -500,6 +514,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -586,6 +614,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -672,6 +714,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -758,6 +814,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -844,6 +914,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -946,6 +1030,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1032,6 +1130,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1118,6 +1230,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1204,6 +1330,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1290,6 +1430,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1376,6 +1530,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1478,6 +1646,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1564,6 +1746,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1650,6 +1846,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1736,6 +1946,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1822,6 +2046,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', @@ -1908,6 +2146,20 @@ export const registerCollector: RegisterCollector = ({ _meta: { description: 'The min duration' }, }, }, + enrichment_duration: { + max: { + type: 'float', + _meta: { description: 'The max duration' }, + }, + avg: { + type: 'float', + _meta: { description: 'The avg duration' }, + }, + min: { + type: 'float', + _meta: { description: 'The min duration' }, + }, + }, gap_duration: { max: { type: 'float', diff --git a/x-pack/plugins/security_solution/server/usage/detections/rules/get_initial_usage.ts b/x-pack/plugins/security_solution/server/usage/detections/rules/get_initial_usage.ts index eb32c58bda6cf..3ad6b5740b53e 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/rules/get_initial_usage.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/rules/get_initial_usage.ts @@ -144,6 +144,7 @@ export const getInitialSingleEventMetric = (): SingleEventMetric => ({ succeeded: 0, index_duration: getInitialMaxAvgMin(), search_duration: getInitialMaxAvgMin(), + enrichment_duration: getInitialMaxAvgMin(), gap_duration: getInitialMaxAvgMin(), gap_count: 0, }); diff --git a/x-pack/plugins/security_solution/server/usage/detections/rules/get_metrics.mocks.ts b/x-pack/plugins/security_solution/server/usage/detections/rules/get_metrics.mocks.ts index 129d2b32d0b3d..83eb7df28a026 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/rules/get_metrics.mocks.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/rules/get_metrics.mocks.ts @@ -155,6 +155,15 @@ export const getEventLogAllRules = (): SearchResponse ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threat_match: { @@ -2506,6 +2835,11 @@ export const getEventLogAllRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, machine_learning: { @@ -2529,6 +2863,11 @@ export const getEventLogAllRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, query: { @@ -2594,6 +2933,11 @@ export const getEventLogAllRulesResult = (): SingleEventLogStatusMetric => ({ avg: 4246.375, min: 2811, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 6, }, saved_query: { @@ -2617,6 +2961,11 @@ export const getEventLogAllRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threshold: { @@ -2640,6 +2989,11 @@ export const getEventLogAllRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, total: { @@ -2676,6 +3030,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threat_match: { @@ -2699,6 +3058,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, machine_learning: { @@ -2722,6 +3086,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, query: { @@ -2772,6 +3141,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 4141.75, min: 2811, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 4, }, saved_query: { @@ -2795,6 +3169,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threshold: { @@ -2818,6 +3197,11 @@ export const getEventLogElasticRulesResult = (): SingleEventLogStatusMetric => ( avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, total: { @@ -2854,6 +3238,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threat_match: { @@ -2877,6 +3266,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, machine_learning: { @@ -2900,6 +3294,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, query: { @@ -2940,6 +3339,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 4351, min: 3051, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 2, }, saved_query: { @@ -2963,6 +3367,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, threshold: { @@ -2986,6 +3395,11 @@ export const getEventLogCustomRulesResult = (): SingleEventLogStatusMetric => ({ avg: 0, min: 0, }, + enrichment_duration: { + max: 0, + avg: 0, + min: 0, + }, gap_count: 0, }, total: { diff --git a/x-pack/plugins/security_solution/server/usage/detections/rules/types.ts b/x-pack/plugins/security_solution/server/usage/detections/rules/types.ts index 499c79b11fcfa..84fb656f793d4 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/rules/types.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/rules/types.ts @@ -85,6 +85,7 @@ export interface SingleEventMetric { succeeded: number; index_duration: MaxAvgMin; search_duration: MaxAvgMin; + enrichment_duration: MaxAvgMin; gap_duration: MaxAvgMin; gap_count: number; } diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.test.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.test.ts index 09a988fbf02ef..693e3579d7c3a 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.test.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.test.ts @@ -68,6 +68,21 @@ describe('get_event_log_agg_by_rule_type_metrics', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }); }); diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.ts index 6fe8103e29a0d..957f56809d64f 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_type_metrics.ts @@ -74,6 +74,21 @@ export const getEventLogAggByRuleTypeMetrics = ( field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }; }; diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_types_metrics.test.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_types_metrics.test.ts index 22261ac48812c..4673ca1b6bcb8 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_types_metrics.test.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_rule_types_metrics.test.ts @@ -74,6 +74,21 @@ describe('get_event_log_agg_by_rule_types_metrics', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }); @@ -139,6 +154,21 @@ describe('get_event_log_agg_by_rule_types_metrics', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }); @@ -204,6 +234,21 @@ describe('get_event_log_agg_by_rule_types_metrics', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, 'siem.indicatorRule': { @@ -263,6 +308,21 @@ describe('get_event_log_agg_by_rule_types_metrics', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }); diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_statuses.test.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_statuses.test.ts index 7d474769bd79f..a87046660fe16 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_statuses.test.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/get_event_log_agg_by_statuses.test.ts @@ -137,6 +137,21 @@ describe('get_event_log_agg_by_statuses', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }, @@ -246,6 +261,21 @@ describe('get_event_log_agg_by_statuses', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }, @@ -418,6 +448,21 @@ describe('get_event_log_agg_by_statuses', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, 'siem.thresholdRule': { @@ -477,6 +522,21 @@ describe('get_event_log_agg_by_statuses', () => { field: 'kibana.alert.rule.execution.metrics.total_search_duration_ms', }, }, + maxTotalEnrichmentDuration: { + max: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + minTotalEnrichmentDuration: { + min: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, + avgTotalEnrichmentDuration: { + avg: { + field: 'kibana.alert.rule.execution.metrics.total_enrichment_duration_ms', + }, + }, }, }, }, diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.test.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.test.ts index c64f0833fe851..9c5810011a975 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.test.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.test.ts @@ -85,6 +85,15 @@ describe('transform_single_rule_metric', () => { minTotalSearchDuration: { value: 12, }, + minTotalEnrichmentDuration: { + value: 4, + }, + maxTotalEnrichmentDuration: { + value: 2, + }, + avgTotalEnrichmentDuration: { + value: 12, + }, }, }); @@ -131,6 +140,11 @@ describe('transform_single_rule_metric', () => { avg: 2, min: 9, }, + enrichment_duration: { + max: 2, + avg: 12, + min: 4, + }, gap_count: 4, }); }); diff --git a/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.ts b/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.ts index bebd867fb195f..5b3b6f8b7ebb2 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/utils/transform_single_rule_metric.ts @@ -52,6 +52,11 @@ export const transformSingleRuleMetric = ({ avg: singleMetric.avgTotalSearchDuration.value ?? 0.0, min: singleMetric.minTotalSearchDuration.value ?? 0.0, }, + enrichment_duration: { + max: singleMetric?.maxTotalEnrichmentDuration?.value ?? 0.0, + avg: singleMetric?.avgTotalEnrichmentDuration?.value ?? 0.0, + min: singleMetric?.minTotalEnrichmentDuration?.value ?? 0.0, + }, gap_duration: { max: singleMetric.maxGapDuration.value ?? 0.0, avg: singleMetric.avgGapDuration.value ?? 0.0, diff --git a/x-pack/plugins/security_solution/server/usage/types.ts b/x-pack/plugins/security_solution/server/usage/types.ts index fe7711196303c..a6db2e3d71e91 100644 --- a/x-pack/plugins/security_solution/server/usage/types.ts +++ b/x-pack/plugins/security_solution/server/usage/types.ts @@ -121,6 +121,15 @@ export interface SingleExecutionMetricAgg { minTotalSearchDuration: { value: number | null; }; + maxTotalEnrichmentDuration: { + value: number | null; + }; + avgTotalEnrichmentDuration: { + value: number | null; + }; + minTotalEnrichmentDuration: { + value: number | null; + }; } export interface EventLogTypeStatusAggs { diff --git a/x-pack/plugins/session_view/public/components/tty_player/hooks.test.tsx b/x-pack/plugins/session_view/public/components/tty_player/hooks.test.tsx index 004bd5bc757e0..8b2161c3b1216 100644 --- a/x-pack/plugins/session_view/public/components/tty_player/hooks.test.tsx +++ b/x-pack/plugins/session_view/public/components/tty_player/hooks.test.tsx @@ -167,6 +167,21 @@ describe('TTYPlayer/hooks', () => { expect(result.current.currentLine).toBe(initialProps.lines.length - 1); }); + it('should not print the first line twice after playback starts', async () => { + const { result, rerender } = renderHook((props) => useXtermPlayer(props), { + initialProps, + }); + + rerender({ ...initialProps, isPlaying: true }); + act(() => { + // advance render loop + jest.advanceTimersByTime(DEFAULT_TTY_PLAYSPEED_MS); + }); + rerender({ ...initialProps, isPlaying: false }); + + expect(result.current.terminal.buffer.active.getLine(0)?.translateToString(true)).toBe('256'); + }); + it('will allow a plain text search highlight on the last line printed', async () => { const { result: xTermResult } = renderHook((props) => useXtermPlayer(props), { initialProps, diff --git a/x-pack/plugins/session_view/public/components/tty_player/hooks.ts b/x-pack/plugins/session_view/public/components/tty_player/hooks.ts index 08f163903b0a5..680d50283d5f1 100644 --- a/x-pack/plugins/session_view/public/components/tty_player/hooks.ts +++ b/x-pack/plugins/session_view/public/components/tty_player/hooks.ts @@ -281,13 +281,12 @@ export const useXtermPlayer = ({ useEffect(() => { if (isPlaying) { const timer = setTimeout(() => { - render(currentLine, false); - - if (currentLine === lines.length - 1) { + if (!hasNextPage && currentLine === lines.length - 1) { setIsPlaying(false); } else { const nextLine = Math.min(lines.length - 1, currentLine + TTY_LINES_PER_FRAME); setCurrentLine(nextLine); + render(nextLine, false); } }, playSpeed); diff --git a/x-pack/plugins/session_view/public/components/tty_player/index.tsx b/x-pack/plugins/session_view/public/components/tty_player/index.tsx index ba57fc9d845cc..cb2746736c02f 100644 --- a/x-pack/plugins/session_view/public/components/tty_player/index.tsx +++ b/x-pack/plugins/session_view/public/components/tty_player/index.tsx @@ -134,7 +134,12 @@ export const TTYPlayer = ({ - + diff --git a/x-pack/plugins/session_view/public/components/tty_search_bar/index.test.tsx b/x-pack/plugins/session_view/public/components/tty_search_bar/index.test.tsx index 2f952b48e9d56..06fa17a6c151c 100644 --- a/x-pack/plugins/session_view/public/components/tty_search_bar/index.test.tsx +++ b/x-pack/plugins/session_view/public/components/tty_search_bar/index.test.tsx @@ -34,6 +34,7 @@ describe('TTYSearchBar component', () => { lines, seekToLine: jest.fn(), xTermSearchFn: jest.fn(), + setIsPlaying: jest.fn(), }; }); @@ -59,6 +60,7 @@ describe('TTYSearchBar component', () => { expect(props.xTermSearchFn).toHaveBeenCalledTimes(2); expect(props.xTermSearchFn).toHaveBeenNthCalledWith(1, '', 0); expect(props.xTermSearchFn).toHaveBeenNthCalledWith(2, '-h', 6); + expect(props.setIsPlaying).toHaveBeenCalledWith(false); }); it('calls seekToline and xTermSearchFn when currentMatch changes', async () => { @@ -85,6 +87,7 @@ describe('TTYSearchBar component', () => { expect(props.xTermSearchFn).toHaveBeenNthCalledWith(1, '', 0); expect(props.xTermSearchFn).toHaveBeenNthCalledWith(2, '-h', 6); expect(props.xTermSearchFn).toHaveBeenNthCalledWith(3, '-h', 13); + expect(props.setIsPlaying).toHaveBeenCalledTimes(3); }); it('calls xTermSearchFn with empty query when search is cleared', async () => { @@ -101,5 +104,6 @@ describe('TTYSearchBar component', () => { await new Promise((r) => setTimeout(r, 100)); expect(props.xTermSearchFn).toHaveBeenNthCalledWith(3, '', 0); + expect(props.setIsPlaying).toHaveBeenCalledWith(false); }); }); diff --git a/x-pack/plugins/session_view/public/components/tty_search_bar/index.tsx b/x-pack/plugins/session_view/public/components/tty_search_bar/index.tsx index e41b3b967cfac..18b829127ab2d 100644 --- a/x-pack/plugins/session_view/public/components/tty_search_bar/index.tsx +++ b/x-pack/plugins/session_view/public/components/tty_search_bar/index.tsx @@ -19,15 +19,24 @@ export interface TTYSearchBarDeps { lines: IOLine[]; seekToLine(index: number): void; xTermSearchFn(query: string, index: number): void; + setIsPlaying(value: boolean): void; } -export const TTYSearchBar = ({ lines, seekToLine, xTermSearchFn }: TTYSearchBarDeps) => { +const STRIP_NEWLINES_REGEX = /^(\r\n|\r|\n|\n\r)/; + +export const TTYSearchBar = ({ + lines, + seekToLine, + xTermSearchFn, + setIsPlaying, +}: TTYSearchBarDeps) => { const [currentMatch, setCurrentMatch] = useState(null); const [searchQuery, setSearchQuery] = useState(''); const jumpToMatch = useCallback( (match) => { if (match) { + setIsPlaying(false); const goToLine = lines.indexOf(match.line); seekToLine(goToLine); } @@ -40,7 +49,7 @@ export const TTYSearchBar = ({ lines, seekToLine, xTermSearchFn }: TTYSearchBarD clearTimeout(timeout); }; }, - [lines, seekToLine, xTermSearchFn, searchQuery] + [setIsPlaying, lines, seekToLine, xTermSearchFn, searchQuery] ); const searchResults = useMemo(() => { @@ -53,7 +62,7 @@ export const TTYSearchBar = ({ lines, seekToLine, xTermSearchFn }: TTYSearchBarD const cursorMovement = current.value.match(/^\x1b\[\d+;(\d+)(H|d)/); const regex = new RegExp(searchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'ig'); const lineMatches = stripAnsi(current.value) - .replace(/^\r|\r?\n/, '') + .replace(STRIP_NEWLINES_REGEX, '') .matchAll(regex); if (lineMatches) { @@ -90,10 +99,14 @@ export const TTYSearchBar = ({ lines, seekToLine, xTermSearchFn }: TTYSearchBarD return matches; }, [searchQuery, lines, jumpToMatch, xTermSearchFn]); - const onSearch = useCallback((query) => { - setSearchQuery(query); - setCurrentMatch(null); - }, []); + const onSearch = useCallback( + (query) => { + setIsPlaying(false); + setSearchQuery(query); + setCurrentMatch(null); + }, + [setIsPlaying] + ); const onSetCurrentMatch = useCallback( (index) => { diff --git a/x-pack/plugins/stack_connectors/jest.config.js b/x-pack/plugins/stack_connectors/jest.config.js index 9a343089b9475..6bfda7da5ca5e 100644 --- a/x-pack/plugins/stack_connectors/jest.config.js +++ b/x-pack/plugins/stack_connectors/jest.config.js @@ -12,6 +12,6 @@ module.exports = { coverageDirectory: '/target/kibana-coverage/jest/x-pack/plugins/stack_connectors', coverageReporters: ['text', 'html'], collectCoverageFrom: [ - '/x-pack/plugins/stack_connectors/{common,server}/**/*.{js,ts,tsx}', + '/x-pack/plugins/stack_connectors/{common,public,server}/**/*.{js,ts,tsx}', ], }; diff --git a/x-pack/plugins/stack_connectors/kibana.json b/x-pack/plugins/stack_connectors/kibana.json index a2fc97ad9547e..fc55b723e5c55 100644 --- a/x-pack/plugins/stack_connectors/kibana.json +++ b/x-pack/plugins/stack_connectors/kibana.json @@ -8,6 +8,6 @@ "version": "8.0.0", "kibanaVersion": "kibana", "configPath": ["xpack", "stack_connectors"], - "requiredPlugins": ["actions"], - "ui": false + "requiredPlugins": ["actions", "esUiShared", "triggersActionsUi"], + "ui": true } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/action_variables.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/action_variables.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/action_variables.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/action_variables.ts diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/index.ts new file mode 100644 index 0000000000000..88107a4f6d517 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getCasesWebhookConnectorType } from './webhook'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/auth.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/auth.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/auth.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/auth.tsx index b356fb716d06f..85e0f5e9e31b5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/auth.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/auth.tsx @@ -23,7 +23,7 @@ import { } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { Field, TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; -import { PasswordField } from '../../../password_field'; +import { PasswordField } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from '../translations'; const { emptyField } = fieldValidators; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/create.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/create.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/create.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/create.tsx index c754a89ed89fe..ffa72576feb69 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/create.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/create.tsx @@ -10,8 +10,8 @@ import { EuiFlexGroup, EuiFlexItem, EuiSpacer, EuiText } from '@elastic/eui'; import { FIELD_TYPES, UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; +import { JsonFieldWrapper } from '@kbn/triggers-actions-ui-plugin/public'; import { containsTitleAndDesc } from '../validator'; -import { JsonFieldWrapper } from '../../../json_field_wrapper'; import { casesVars } from '../action_variables'; import { HTTP_VERBS } from '../webhook_connectors'; import * as i18n from '../translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/get.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/get.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/get.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/get.tsx index 3f0cf52dcfcb2..e8f233408a4c9 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/get.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/get.tsx @@ -10,7 +10,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; -import { MustacheTextFieldWrapper } from '../../../mustache_text_field_wrapper'; +import { MustacheTextFieldWrapper } from '@kbn/triggers-actions-ui-plugin/public'; import { containsExternalId, containsExternalIdOrTitle } from '../validator'; import { urlVars, urlVarsExt } from '../action_variables'; import * as i18n from '../translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/index.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/index.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/update.styles.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/update.styles.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/update.styles.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/update.styles.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/update.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/update.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/update.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/update.tsx index e8305e7439778..a140ecbc6a221 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/steps/update.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/steps/update.tsx @@ -10,10 +10,9 @@ import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { EuiFlexGroup, EuiFlexItem, EuiSpacer, EuiText } from '@elastic/eui'; import { FIELD_TYPES, UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; +import { JsonFieldWrapper, MustacheTextFieldWrapper } from '@kbn/triggers-actions-ui-plugin/public'; import { containsCommentsOrEmpty, containsTitleAndDesc, isUrlButCanBeEmpty } from '../validator'; -import { MustacheTextFieldWrapper } from '../../../mustache_text_field_wrapper'; import { casesVars, commentVars, urlVars } from '../action_variables'; -import { JsonFieldWrapper } from '../../../json_field_wrapper'; import { HTTP_VERBS } from '../webhook_connectors'; import { styles } from './update.styles'; import * as i18n from '../translations'; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/translations.ts new file mode 100644 index 0000000000000..1ef221566352d --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/translations.ts @@ -0,0 +1,477 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const CREATE_URL_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateUrlText', + { + defaultMessage: 'Create case URL is required.', + } +); +export const CREATE_INCIDENT_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentText', + { + defaultMessage: 'Create case object is required and must be valid JSON.', + } +); + +export const CREATE_METHOD_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateMethodText', + { + defaultMessage: 'Create case method is required.', + } +); + +export const CREATE_RESPONSE_KEY_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentResponseKeyText', + { + defaultMessage: 'Create case response case id key is required.', + } +); + +export const UPDATE_URL_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredUpdateUrlText', + { + defaultMessage: 'Update case URL is required.', + } +); +export const UPDATE_INCIDENT_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredUpdateIncidentText', + { + defaultMessage: 'Update case object is required and must be valid JSON.', + } +); + +export const UPDATE_METHOD_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredUpdateMethodText', + { + defaultMessage: 'Update case method is required.', + } +); + +export const CREATE_COMMENT_URL_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentUrlText', + { + defaultMessage: 'Create comment URL must be URL format.', + } +); +export const CREATE_COMMENT_MESSAGE = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentIncidentText', + { + defaultMessage: 'Create comment object must be valid JSON.', + } +); + +export const CREATE_COMMENT_METHOD_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentMethodText', + { + defaultMessage: 'Create comment method is required.', + } +); + +export const GET_INCIDENT_URL_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentUrlText', + { + defaultMessage: 'Get case URL is required.', + } +); +export const GET_RESPONSE_EXTERNAL_TITLE_KEY_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseExternalTitleKeyText', + { + defaultMessage: 'Get case response external case title key is re quired.', + } +); +export const GET_RESPONSE_EXTERNAL_CREATED_KEY_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseCreatedKeyText', + { + defaultMessage: 'Get case response created date key is required.', + } +); +export const GET_RESPONSE_EXTERNAL_UPDATED_KEY_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseUpdatedKeyText', + { + defaultMessage: 'Get case response updated date key is required.', + } +); +export const GET_INCIDENT_VIEW_URL_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentViewUrlKeyText', + { + defaultMessage: 'View case URL is required.', + } +); + +export const MISSING_VARIABLES = (variables: string[]) => + i18n.translate('xpack.stackConnectors.components.casesWebhook.error.missingVariables', { + defaultMessage: + 'Missing required {variableCount, plural, one {variable} other {variables}}: {variables}', + values: { variableCount: variables.length, variables: variables.join(', ') }, + }); + +export const USERNAME_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredAuthUserNameText', + { + defaultMessage: 'Username is required.', + } +); + +export const SUMMARY_REQUIRED = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.error.requiredWebhookSummaryText', + { + defaultMessage: 'Title is required.', + } +); + +export const KEY_LABEL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.keyTextFieldLabel', + { + defaultMessage: 'Key', + } +); + +export const VALUE_LABEL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.valueTextFieldLabel', + { + defaultMessage: 'Value', + } +); + +export const ADD_BUTTON = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.addHeaderButton', + { + defaultMessage: 'Add', + } +); + +export const DELETE_BUTTON = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.deleteHeaderButton', + { + defaultMessage: 'Delete', + description: 'Delete HTTP header', + } +); + +export const CREATE_INCIDENT_METHOD = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentMethodTextFieldLabel', + { + defaultMessage: 'Create Case Method', + } +); + +export const CREATE_INCIDENT_URL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentUrlTextFieldLabel', + { + defaultMessage: 'Create Case URL', + } +); + +export const CREATE_INCIDENT_JSON = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentJsonTextFieldLabel', + { + defaultMessage: 'Create Case Object', + } +); + +export const CREATE_INCIDENT_JSON_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentJsonHelpText', + { + defaultMessage: + 'JSON object to create case. Use the variable selector to add Cases data to the payload.', + } +); + +export const JSON = i18n.translate('xpack.stackConnectors.components.casesWebhook.jsonFieldLabel', { + defaultMessage: 'JSON', +}); +export const CODE_EDITOR = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.jsonCodeEditorAriaLabel', + { + defaultMessage: 'Code editor', + } +); + +export const CREATE_INCIDENT_RESPONSE_KEY = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyTextFieldLabel', + { + defaultMessage: 'Create Case Response Case Key', + } +); + +export const CREATE_INCIDENT_RESPONSE_KEY_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyHelpText', + { + defaultMessage: 'JSON key in create case response that contains the external case id', + } +); + +export const ADD_CASES_VARIABLE = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.addVariable', + { + defaultMessage: 'Add variable', + } +); + +export const GET_INCIDENT_URL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.getIncidentUrlTextFieldLabel', + { + defaultMessage: 'Get Case URL', + } +); +export const GET_INCIDENT_URL_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.getIncidentUrlHelp', + { + defaultMessage: + 'API URL to GET case details JSON from external system. Use the variable selector to add external system id to the url.', + } +); + +export const GET_INCIDENT_TITLE_KEY = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyTextFieldLabel', + { + defaultMessage: 'Get Case Response External Title Key', + } +); +export const GET_INCIDENT_TITLE_KEY_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyHelp', + { + defaultMessage: 'JSON key in get case response that contains the external case title', + } +); + +export const EXTERNAL_INCIDENT_VIEW_URL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.viewIncidentUrlTextFieldLabel', + { + defaultMessage: 'External Case View URL', + } +); +export const EXTERNAL_INCIDENT_VIEW_URL_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.viewIncidentUrlHelp', + { + defaultMessage: + 'URL to view case in external system. Use the variable selector to add external system id or external system title to the url.', + } +); + +export const UPDATE_INCIDENT_METHOD = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.updateIncidentMethodTextFieldLabel', + { + defaultMessage: 'Update Case Method', + } +); + +export const UPDATE_INCIDENT_URL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.updateIncidentUrlTextFieldLabel', + { + defaultMessage: 'Update Case URL', + } +); +export const UPDATE_INCIDENT_URL_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.updateIncidentUrlHelp', + { + defaultMessage: 'API URL to update case.', + } +); + +export const UPDATE_INCIDENT_JSON = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.updateIncidentJsonTextFieldLabel', + { + defaultMessage: 'Update Case Object', + } +); +export const UPDATE_INCIDENT_JSON_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.updateIncidentJsonHelpl', + { + defaultMessage: + 'JSON object to update case. Use the variable selector to add Cases data to the payload.', + } +); + +export const CREATE_COMMENT_METHOD = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createCommentMethodTextFieldLabel', + { + defaultMessage: 'Create Comment Method', + } +); +export const CREATE_COMMENT_URL = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createCommentUrlTextFieldLabel', + { + defaultMessage: 'Create Comment URL', + } +); + +export const CREATE_COMMENT_URL_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createCommentUrlHelp', + { + defaultMessage: 'API URL to add comment to case.', + } +); + +export const CREATE_COMMENT_JSON = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createCommentJsonTextFieldLabel', + { + defaultMessage: 'Create Comment Object', + } +); +export const CREATE_COMMENT_JSON_HELP = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.createCommentJsonHelp', + { + defaultMessage: + 'JSON object to create a comment. Use the variable selector to add Cases data to the payload.', + } +); + +export const HAS_AUTH = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.hasAuthSwitchLabel', + { + defaultMessage: 'Require authentication for this webhook', + } +); + +export const USERNAME = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.userTextFieldLabel', + { + defaultMessage: 'Username', + } +); + +export const PASSWORD = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.passwordTextFieldLabel', + { + defaultMessage: 'Password', + } +); + +export const HEADERS_SWITCH = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.viewHeadersSwitch', + { + defaultMessage: 'Add HTTP header', + } +); + +export const HEADERS_TITLE = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.httpHeadersTitle', + { + defaultMessage: 'Headers in use', + } +); + +export const AUTH_TITLE = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.authenticationLabel', + { + defaultMessage: 'Authentication', + } +); + +export const STEP_1 = i18n.translate('xpack.stackConnectors.components.casesWebhook.step1', { + defaultMessage: 'Set up connector', +}); + +export const STEP_2 = i18n.translate('xpack.stackConnectors.components.casesWebhook.step2', { + defaultMessage: 'Create case', +}); + +export const STEP_2_DESCRIPTION = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.step2Description', + { + defaultMessage: + 'Set fields to create the case in the external system. Check your service’s API documentation to understand what fields are required', + } +); + +export const STEP_3 = i18n.translate('xpack.stackConnectors.components.casesWebhook.step3', { + defaultMessage: 'Get case information', +}); + +export const STEP_3_DESCRIPTION = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.step3Description', + { + defaultMessage: + 'Set fields to add comments to the case in external system. For some systems, this may be the same method as creating updates in cases. Check your service’s API documentation to understand what fields are required.', + } +); + +export const STEP_4 = i18n.translate('xpack.stackConnectors.components.casesWebhook.step4', { + defaultMessage: 'Comments and updates', +}); + +export const STEP_4A = i18n.translate('xpack.stackConnectors.components.casesWebhook.step4a', { + defaultMessage: 'Create update in case', +}); + +export const STEP_4A_DESCRIPTION = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.step4aDescription', + { + defaultMessage: + 'Set fields to create updates to the case in external system. For some systems, this may be the same method as adding comments to cases.', + } +); + +export const STEP_4B = i18n.translate('xpack.stackConnectors.components.casesWebhook.step4b', { + defaultMessage: 'Add comment in case', +}); + +export const STEP_4B_DESCRIPTION = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.step4bDescription', + { + defaultMessage: + 'Set fields to add comments to the case in external system. For some systems, this may be the same method as creating updates in cases.', + } +); + +export const NEXT = i18n.translate('xpack.stackConnectors.components.casesWebhook.next', { + defaultMessage: 'Next', +}); + +export const PREVIOUS = i18n.translate('xpack.stackConnectors.components.casesWebhook.previous', { + defaultMessage: 'Previous', +}); + +export const CASE_TITLE_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.caseTitleDesc', + { + defaultMessage: 'Kibana case title', + } +); + +export const CASE_DESCRIPTION_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.caseDescriptionDesc', + { + defaultMessage: 'Kibana case description', + } +); + +export const CASE_TAGS_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.caseTagsDesc', + { + defaultMessage: 'Kibana case tags', + } +); + +export const CASE_COMMENT_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.caseCommentDesc', + { + defaultMessage: 'Kibana case comment', + } +); + +export const EXTERNAL_ID_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.externalIdDesc', + { + defaultMessage: 'External system id', + } +); + +export const EXTERNAL_TITLE_DESC = i18n.translate( + 'xpack.stackConnectors.components.casesWebhook.externalTitleDesc', + { + defaultMessage: 'External system title', + } +); + +export const DOC_LINK = i18n.translate('xpack.stackConnectors.components.casesWebhook.docLink', { + defaultMessage: 'Configuring Webhook - Case Management connector.', +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/types.ts similarity index 82% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/types.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/types.ts index 36e072cc8db44..68f560dd59415 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/types.ts @@ -5,12 +5,12 @@ * 2.0. */ +import { UserConfiguredActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import type { CasesWebhookPublicConfigurationType, CasesWebhookSecretConfigurationType, ExecutorSubActionPushParams, -} from '@kbn/stack-connectors-plugin/server/connector_types/cases/cases_webhook/types'; -import { UserConfiguredActionConnector } from '../../../../types'; +} from '../../../../server/connector_types/cases/cases_webhook/types'; export interface CasesWebhookActionParams { subAction: string; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/validator.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/validator.ts similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/validator.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/validator.ts index 7f34f76807e55..d3d7f6dc8e612 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/validator.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/validator.ts @@ -11,9 +11,9 @@ import { ValidationFunc, } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { containsChars, isUrl } from '@kbn/es-ui-shared-plugin/static/validators/string'; +import { templateActionVariable } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; import { casesVars, commentVars, urlVars, urlVarsExt } from './action_variables'; -import { templateActionVariable } from '../../../lib'; const errorCode: ERROR_CODE = 'ERR_FIELD_MISSING'; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.test.tsx new file mode 100644 index 0000000000000..14e767915515a --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.test.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; + +const CONNECTOR_TYPE_ID = '.cases-webhook'; +let connectorTypeModel: ConnectorTypeModel; + +beforeAll(() => { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('logoWebhook'); + }); +}); + +describe('webhook action params validation', () => { + test('action params validation succeeds when action params is valid', async () => { + const actionParams = { + subActionParams: { incident: { title: 'some title {{test}}' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { 'subActionParams.incident.title': [] }, + }); + }); + + test('params validation fails when body is not valid', async () => { + const actionParams = { + subActionParams: { incident: { title: '' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + 'subActionParams.incident.title': ['Title is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.tsx similarity index 80% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.tsx index 5ac8d915e26d9..6e86df15c09c7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook.tsx @@ -7,10 +7,13 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; import { CasesWebhookActionParams, CasesWebhookConfig, CasesWebhookSecrets } from './types'; -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< CasesWebhookConfig, CasesWebhookSecrets, CasesWebhookActionParams @@ -19,14 +22,14 @@ export function getActionType(): ActionTypeModel< id: '.cases-webhook', iconClass: 'logoWebhook', selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.selectMessageText', + 'xpack.stackConnectors.components.casesWebhook.selectMessageText', { defaultMessage: 'Send a request to a Case Management web service.', } ), isExperimental: true, actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.actionTypeTitle', + 'xpack.stackConnectors.components.casesWebhookxpack.stackConnectors.components.casesWebhook.connectorTypeTitle', { defaultMessage: 'Webhook - Case Management data', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.test.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.test.tsx index ba0cf756530e7..fbe24f5e5d863 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.test.tsx @@ -7,15 +7,15 @@ import React from 'react'; import CasesWebhookActionConnectorFields from './webhook_connectors'; -import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../test_utils'; +import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../../lib/test_utils'; import { act, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { MockCodeEditor } from '../../../code_editor.mock'; +import { MockCodeEditor } from '@kbn/triggers-actions-ui-plugin/public/application/code_editor.mock'; import * as i18n from './translations'; -const kibanaReactPath = '../../../../../../../../src/plugins/kibana_react/public'; +const kibanaReactPath = '../../../../../../../src/plugins/kibana_react/public'; -jest.mock('../../../../common/lib/kibana', () => { - const originalModule = jest.requireActual('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public', () => { + const originalModule = jest.requireActual('@kbn/triggers-actions-ui-plugin/public'); return { ...originalModule, useKibana: () => ({ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.tsx index 29983935cf7f1..73e424901469a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_connectors.tsx @@ -17,8 +17,8 @@ import { EuiStepsHorizontal, EuiStepStatus, } from '@elastic/eui'; -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionConnectorFieldsProps } from '../../../../types'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; import { AuthStep, CreateStep, GetStep, UpdateStep } from './steps'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.test.tsx similarity index 93% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.test.tsx index 91adb9616c4ab..f931fd1eeddad 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.test.tsx @@ -8,10 +8,10 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import WebhookParamsFields from './webhook_params'; -import { MockCodeEditor } from '../../../code_editor.mock'; +import { MockCodeEditor } from '@kbn/triggers-actions-ui-plugin/public/application/code_editor.mock'; import { CasesWebhookActionConnector } from './types'; -const kibanaReactPath = '../../../../../../../../src/plugins/kibana_react/public'; +const kibanaReactPath = '../../../../../../../src/plugins/kibana_react/public'; jest.mock(kibanaReactPath, () => { const original = jest.requireActual(kibanaReactPath); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.tsx similarity index 84% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.tsx index 2d1f8b03bd08f..dab3f8cc95832 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/cases_webhook/webhook_params.tsx @@ -8,20 +8,22 @@ import React, { useCallback, useEffect, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiCallOut, EuiComboBox, EuiFormRow, EuiSpacer } from '@elastic/eui'; -import { ActionParamsProps } from '../../../../types'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, +} from '@kbn/triggers-actions-ui-plugin/public'; import { CasesWebhookActionConnector, CasesWebhookActionParams } from './types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; const CREATE_COMMENT_WARNING_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningTitle', + 'xpack.stackConnectors.components.casesWebhook.createCommentWarningTitle', { defaultMessage: 'Unable to share case comments', } ); const CREATE_COMMENT_WARNING_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningDesc', + 'xpack.stackConnectors.components.casesWebhook.createCommentWarningDesc', { defaultMessage: 'Configure the Create Comment URL and Create Comment Objects fields for the connector to share comments externally.', @@ -108,12 +110,9 @@ const WebhookParamsFields: React.FunctionComponent 0 && incident.title !== undefined } - label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.titleFieldLabel', - { - defaultMessage: 'Summary (required)', - } - )} + label={i18n.translate('xpack.stackConnectors.components.casesWebhook.titleFieldLabel', { + defaultMessage: 'Summary (required)', + })} > 0 ? comments[0].comment : undefined} label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.commentsTextAreaFieldLabel', + 'xpack.stackConnectors.components.casesWebhook.commentsTextAreaFieldLabel', { defaultMessage: 'Additional comments', } diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/index.ts new file mode 100644 index 0000000000000..22f32cf636036 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/index.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getCasesWebhookConnectorType } from './cases_webhook'; +export { getJiraConnectorType } from './jira'; +export { getResilientConnectorType } from './resilient'; +export { + getServiceNowITSMConnectorType, + getServiceNowSIRConnectorType, + getServiceNowITOMConnectorType, +} from './servicenow'; +export { getSwimlaneConnectorType } from './swimlane'; +export { getXmattersConnectorType } from './xmatters'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/api.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/api.test.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/api.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/api.test.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/api.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/api.ts similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/api.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/api.ts index f213bbc7bda40..e6db358b7988d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/api.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/api.ts @@ -6,9 +6,11 @@ */ import { HttpSetup } from '@kbn/core/public'; -import { ActionTypeExecutorResult } from '@kbn/actions-plugin/common'; -import { BASE_ACTION_API_PATH } from '../../../constants'; -import { ConnectorExecutorResult, rewriteResponseToCamelCase } from '../rewrite_response_body'; +import { ActionTypeExecutorResult, BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common'; +import { + ConnectorExecutorResult, + rewriteResponseToCamelCase, +} from '../../lib/rewrite_response_body'; import { Fields, Issue, IssueTypes } from './types'; export async function getIssueTypes({ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/index.ts similarity index 80% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/index.ts index a597a5ea6df4d..184109b17cc92 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { getActionType as getWebhookActionType } from './webhook'; +export { getConnectorType as getJiraConnectorType } from './jira'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.test.tsx similarity index 57% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.test.tsx index 07aa45cfe1925..2f8299ea010da 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.test.tsx @@ -5,26 +5,26 @@ * 2.0. */ -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; -const ACTION_TYPE_ID = '.jira'; -let actionTypeModel: ActionTypeModel; +const CONNECTOR_TYPE_ID = '.jira'; +let connectorTypeModel: ConnectorTypeModel; beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); if (getResult !== null) { - actionTypeModel = getResult; + connectorTypeModel = getResult; } }); -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); }); }); @@ -34,7 +34,7 @@ describe('jira action params validation', () => { subActionParams: { incident: { summary: 'some title {{test}}' }, comments: [] }, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.summary': [], 'subActionParams.incident.labels': [] }, }); }); @@ -44,7 +44,7 @@ describe('jira action params validation', () => { subActionParams: { incident: { summary: '' }, comments: [] }, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.summary': ['Summary is required.'], 'subActionParams.incident.labels': [], @@ -60,7 +60,7 @@ describe('jira action params validation', () => { }, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.summary': [], 'subActionParams.incident.labels': ['Labels cannot contain spaces.'], diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.tsx similarity index 80% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.tsx index 627429a39b5b3..92a98a3270cc3 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira.tsx @@ -7,24 +7,24 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { GenericValidationResult, ActionTypeModel } from '../../../../types'; +import type { + GenericValidationResult, + ActionTypeModel as ConnectorTypeModel, +} from '@kbn/triggers-actions-ui-plugin/public'; import { JiraConfig, JiraSecrets, JiraActionParams } from './types'; -export const JIRA_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.selectMessageText', - { - defaultMessage: 'Create an incident in Jira.', - } -); +export const JIRA_DESC = i18n.translate('xpack.stackConnectors.components.jira.selectMessageText', { + defaultMessage: 'Create an incident in Jira.', +}); export const JIRA_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.actionTypeTitle', + 'xpack.stackConnectors.components.jira.connectorTypeTitle', { defaultMessage: 'Jira', } ); -export function getActionType(): ActionTypeModel { +export function getConnectorType(): ConnectorTypeModel { return { id: '.jira', iconClass: lazy(() => import('./logo')), diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.test.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.test.tsx index 3afb0d16f8cbd..17166ae5c05c3 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.test.tsx @@ -8,11 +8,11 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import JiraConnectorFields from './jira_connectors'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import { act, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('JiraActionConnectorFields renders', () => { test('Jira connector fields are rendered', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.tsx similarity index 86% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.tsx index 5d056281cd38a..781b605696590 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_connectors.tsx @@ -6,15 +6,13 @@ */ import React from 'react'; - -import { ActionConnectorFieldsProps } from '../../../../types'; - -import * as i18n from './translations'; -import { +import type { + ActionConnectorFieldsProps, ConfigFieldSchema, - SimpleConnectorForm, SecretsFieldSchema, -} from '../../simple_connector_form'; +} from '@kbn/triggers-actions-ui-plugin/public'; +import { SimpleConnectorForm } from '@kbn/triggers-actions-ui-plugin/public'; +import * as i18n from './translations'; const configFormSchema: ConfigFieldSchema[] = [ { id: 'apiUrl', label: i18n.API_URL_LABEL, isUrlField: true }, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.test.tsx index 8a478c84b509e..3865da8ead3a7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.test.tsx @@ -11,11 +11,11 @@ import { useGetIssueTypes } from './use_get_issue_types'; import { useGetFieldsByIssueType } from './use_get_fields_by_issue_type'; import { useGetIssues } from './use_get_issues'; import { useGetSingleIssue } from './use_get_single_issue'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import { act, fireEvent, render, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); jest.mock('./use_get_issue_types'); jest.mock('./use_get_fields_by_issue_type'); jest.mock('./use_get_issues'); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.tsx similarity index 90% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.tsx index 5228fbcaf119f..f4aa607f7cf34 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/jira_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/jira_params.tsx @@ -18,15 +18,16 @@ import { EuiFlexItem, EuiSpacer, } from '@elastic/eui'; - -import { ActionParamsProps } from '../../../../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import { JiraActionParams } from './types'; import { useGetIssueTypes } from './use_get_issue_types'; import { useGetFieldsByIssueType } from './use_get_fields_by_issue_type'; import { SearchIssues } from './search_issues'; -import { useKibana } from '../../../../common/lib/kibana'; const JiraParamsFields: React.FunctionComponent> = ({ actionConnector, @@ -198,12 +199,9 @@ const JiraParamsFields: React.FunctionComponent 0 && incident.summary !== undefined } - label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.summaryFieldLabel', - { - defaultMessage: 'Summary (required)', - } - )} + label={i18n.translate('xpack.stackConnectors.components.jira.summaryFieldLabel', { + defaultMessage: 'Summary (required)', + })} > 0 ? comments[0].comment : undefined} label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.commentsTextAreaFieldLabel', + 'xpack.stackConnectors.components.jira.commentsTextAreaFieldLabel', { defaultMessage: 'Additional comments', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/logo.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/logo.tsx index f42b571408502..945dc955e4b20 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => ( - i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueMessage', - { - defaultMessage: 'Unable to get issue with id {id}', - values: { id }, - } - ); + i18n.translate('xpack.stackConnectors.components.jira.unableToGetIssueMessage', { + defaultMessage: 'Unable to get issue with id {id}', + values: { id }, + }); export const SEARCH_ISSUES_COMBO_BOX_ARIA_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxAriaLabel', + 'xpack.stackConnectors.components.jira.searchIssuesComboBoxAriaLabel', { defaultMessage: 'Type to search', } ); export const SEARCH_ISSUES_PLACEHOLDER = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxPlaceholder', + 'xpack.stackConnectors.components.jira.searchIssuesComboBoxPlaceholder', { defaultMessage: 'Type to search', } ); export const SEARCH_ISSUES_LOADING = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesLoading', + 'xpack.stackConnectors.components.jira.searchIssuesLoading', { defaultMessage: 'Loading...', } ); export const LABELS_WHITE_SPACES = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.jira.labelsSpacesErrorMessage', + 'xpack.stackConnectors.components.jira.labelsSpacesErrorMessage', { defaultMessage: 'Labels cannot contain spaces.', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/types.ts similarity index 81% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/types.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/types.ts index 85e7be1626b0c..e5796f44591ca 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/types.ts @@ -5,8 +5,8 @@ * 2.0. */ -import type { ExecutorSubActionPushParams } from '@kbn/stack-connectors-plugin/server/connector_types/cases/jira/types'; -import { UserConfiguredActionConnector } from '../../../../types'; +import { UserConfiguredActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; +import type { ExecutorSubActionPushParams } from '../../../../server/connector_types/cases/jira/types'; export type JiraActionConnector = UserConfiguredActionConnector; export interface JiraActionParams { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_fields_by_issue_type.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_fields_by_issue_type.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_fields_by_issue_type.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_fields_by_issue_type.tsx index 4f0e1e143291c..11b8c7fee8294 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_fields_by_issue_type.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_fields_by_issue_type.tsx @@ -7,7 +7,7 @@ import { useState, useEffect, useRef } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { Fields } from './types'; import { getFieldsByIssueType } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issue_types.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issue_types.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issue_types.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issue_types.tsx index 97db74630258c..ed5a0e0a48191 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issue_types.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issue_types.tsx @@ -8,7 +8,7 @@ import { useState, useEffect, useRef } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { IssueTypes } from './types'; import { getIssueTypes } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issues.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issues.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issues.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issues.tsx index 0dea608b78ac9..04153fdd5e4fc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_issues.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_issues.tsx @@ -8,7 +8,7 @@ import { isEmpty, debounce } from 'lodash/fp'; import { useState, useEffect, useRef } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { Issue } from './types'; import { getIssues } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_single_issue.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_single_issue.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_single_issue.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_single_issue.tsx index 3967ab25c889e..bacc57c971ad4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/use_get_single_issue.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/jira/use_get_single_issue.tsx @@ -7,7 +7,7 @@ import { useState, useEffect, useRef } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { Issue } from './types'; import { getIssue } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/api.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/api.test.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/api.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/api.test.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/api.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/api.ts similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/api.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/api.ts index b0378be04efd3..80341d45402e2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/api.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/api.ts @@ -6,8 +6,11 @@ */ import { HttpSetup } from '@kbn/core/public'; -import { BASE_ACTION_API_PATH } from '../../../constants'; -import { ConnectorExecutorResult, rewriteResponseToCamelCase } from '../rewrite_response_body'; +import { BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common'; +import { + ConnectorExecutorResult, + rewriteResponseToCamelCase, +} from '../../lib/rewrite_response_body'; export async function getIncidentTypes({ http, diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/index.ts new file mode 100644 index 0000000000000..0d6ca3e87e736 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getResilientConnectorType } from './resilient'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/logo.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/logo.tsx index 7b64a1330d401..7437984034bd5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => ( { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + }); +}); + +describe('resilient action params validation', () => { + test('action params validation succeeds when action params is valid', async () => { + const actionParams = { + subActionParams: { incident: { name: 'some title {{test}}' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { 'subActionParams.incident.name': [] }, + }); + }); + + test('params validation fails when body is not valid', async () => { + const actionParams = { + subActionParams: { incident: { name: '' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + 'subActionParams.incident.name': ['Name is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient.tsx similarity index 77% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient.tsx index 2297107e914cc..9ec583762b973 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient.tsx @@ -7,24 +7,24 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { GenericValidationResult, ActionTypeModel } from '../../../../types'; +import type { + GenericValidationResult, + ActionTypeModel as ConnectorTypeModel, +} from '@kbn/triggers-actions-ui-plugin/public'; import { ResilientConfig, ResilientSecrets, ResilientActionParams } from './types'; -export const DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.selectMessageText', - { - defaultMessage: 'Create an incident in IBM Resilient.', - } -); +export const DESC = i18n.translate('xpack.stackConnectors.components.resilient.selectMessageText', { + defaultMessage: 'Create an incident in IBM Resilient.', +}); export const TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.actionTypeTitle', + 'xpack.stackConnectors.components.resilient.connectorTypeTitle', { defaultMessage: 'Resilient', } ); -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< ResilientConfig, ResilientSecrets, ResilientActionParams diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.test.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.test.tsx index 0fbe63b28b166..8364e614a0335 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.test.tsx @@ -8,11 +8,11 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import ResilientConnectorFields from './resilient_connectors'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import { act, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('ResilientActionConnectorFields renders', () => { test('alerting Resilient connector fields are rendered', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.tsx similarity index 86% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.tsx index 6cc4d31f1b405..ddd219d4fc52b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_connectors.tsx @@ -6,14 +6,13 @@ */ import React from 'react'; - -import { ActionConnectorFieldsProps } from '../../../../types'; -import * as i18n from './translations'; -import { +import type { + ActionConnectorFieldsProps, ConfigFieldSchema, SecretsFieldSchema, - SimpleConnectorForm, -} from '../../simple_connector_form'; +} from '@kbn/triggers-actions-ui-plugin/public'; +import { SimpleConnectorForm } from '@kbn/triggers-actions-ui-plugin/public'; +import * as i18n from './translations'; const configFormSchema: ConfigFieldSchema[] = [ { id: 'apiUrl', label: i18n.API_URL_LABEL, isUrlField: true }, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.test.tsx index 09ae6fe002d41..c6417660720f7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.test.tsx @@ -14,7 +14,7 @@ import { EuiComboBoxOptionOption } from '@elastic/eui'; jest.mock('./use_get_incident_types'); jest.mock('./use_get_severity'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useGetIncidentTypesMock = useGetIncidentTypes as jest.Mock; const useGetSeverityMock = useGetSeverity as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.tsx similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.tsx index a50736b8c737b..04a0ba4f85ec4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/resilient_params.tsx @@ -16,15 +16,16 @@ import { EuiSelectOption, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; - -import { ActionParamsProps } from '../../../../types'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import { ResilientActionParams } from './types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; import { useGetIncidentTypes } from './use_get_incident_types'; import { useGetSeverity } from './use_get_severity'; -import { useKibana } from '../../../../common/lib/kibana'; const ResilientParamsFields: React.FunctionComponent> = ({ actionConnector, @@ -169,7 +170,7 @@ const ResilientParamsFields: React.FunctionComponent @@ -188,10 +189,9 @@ const ResilientParamsFields: React.FunctionComponent 0 && incident.name !== undefined } - label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.nameFieldLabel', - { defaultMessage: 'Name (required)' } - )} + label={i18n.translate('xpack.stackConnectors.components.resilient.nameFieldLabel', { + defaultMessage: 'Name (required)', + })} > @@ -245,7 +244,7 @@ const ResilientParamsFields: React.FunctionComponent 0 ? comments[0].comment : undefined} label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.commentsTextAreaFieldLabel', + 'xpack.stackConnectors.components.resilient.commentsTextAreaFieldLabel', { defaultMessage: 'Additional comments' } )} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/translations.ts similarity index 55% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/translations.ts index df4c15b0f322a..d049ba633e699 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/translations.ts @@ -8,49 +8,46 @@ import { i18n } from '@kbn/i18n'; export const API_URL_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiUrlTextFieldLabel', + 'xpack.stackConnectors.components.resilient.apiUrlTextFieldLabel', { defaultMessage: 'URL', } ); -export const ORG_ID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.orgId', - { - defaultMessage: 'Organization ID', - } -); +export const ORG_ID_LABEL = i18n.translate('xpack.stackConnectors.components.resilient.orgId', { + defaultMessage: 'Organization ID', +}); export const API_KEY_ID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeyId', + 'xpack.stackConnectors.components.resilient.apiKeyId', { defaultMessage: 'API Key ID', } ); export const API_KEY_SECRET_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeySecret', + 'xpack.stackConnectors.components.resilient.apiKeySecret', { defaultMessage: 'API Key Secret', } ); export const NAME_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredNameTextField', + 'xpack.stackConnectors.components.resilient.requiredNameTextField', { defaultMessage: 'Name is required.', } ); export const INCIDENT_TYPES_API_ERROR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetIncidentTypesMessage', + 'xpack.stackConnectors.components.resilient.unableToGetIncidentTypesMessage', { defaultMessage: 'Unable to get incident types', } ); export const SEVERITY_API_ERROR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetSeverityMessage', + 'xpack.stackConnectors.components.resilient.unableToGetSeverityMessage', { defaultMessage: 'Unable to get severity', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/types.ts similarity index 75% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/types.ts index 12c46d2900213..67006b967b5d6 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/types.ts @@ -5,8 +5,8 @@ * 2.0. */ -import type { ExecutorSubActionPushParams } from '@kbn/stack-connectors-plugin/server/connector_types/cases/resilient/types'; -import { UserConfiguredActionConnector } from '../../../../types'; +import { UserConfiguredActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; +import type { ExecutorSubActionPushParams } from '../../../../server/connector_types/cases/resilient/types'; export type ResilientActionConnector = UserConfiguredActionConnector< ResilientConfig, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_incident_types.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_incident_types.tsx index e398f1a8dd32c..577af149d77c0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_incident_types.tsx @@ -7,7 +7,7 @@ import { useState, useEffect, useRef } from 'react'; import { HttpSetup, ToastsApi } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { getIncidentTypes } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_severity.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_severity.tsx index 79e3b27d0a081..7f93e908dbb9a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/resilient/use_get_severity.tsx @@ -7,7 +7,7 @@ import { useState, useEffect, useRef } from 'react'; import { HttpSetup, ToastsApi } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { getSeverity } from './api'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/api.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/api.test.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/api.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/api.test.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/api.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/api.ts similarity index 92% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/api.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/api.ts index 95fac75cb9f5b..4cf46d57eb7f4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/api.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/api.ts @@ -10,12 +10,15 @@ import { HttpSetup } from '@kbn/core/public'; import { ActionTypeExecutorResult, INTERNAL_BASE_ACTION_API_PATH, + BASE_ACTION_API_PATH, } from '@kbn/actions-plugin/common'; -import { snExternalServiceConfig } from '@kbn/stack-connectors-plugin/common/servicenow_config'; -import { BASE_ACTION_API_PATH } from '../../../constants'; +import { snExternalServiceConfig } from '../../../../common/servicenow_config'; import { API_INFO_ERROR } from './translations'; import { AppInfo, RESTApiError, ServiceNowActionConnector } from './types'; -import { ConnectorExecutorResult, rewriteResponseToCamelCase } from '../rewrite_response_body'; +import { + ConnectorExecutorResult, + rewriteResponseToCamelCase, +} from '../../lib/rewrite_response_body'; import { Choice } from './types'; export async function getChoices({ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/application_required_callout.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/application_required_callout.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/application_required_callout.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/application_required_callout.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/application_required_callout.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/application_required_callout.tsx similarity index 81% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/application_required_callout.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/application_required_callout.tsx index 9aefd7a2259b2..2938685f1102c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/application_required_callout.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/application_required_callout.tsx @@ -11,14 +11,14 @@ import { i18n } from '@kbn/i18n'; import { SNStoreButton } from './sn_store_button'; const content = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.content', + 'xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.content', { defaultMessage: 'Please go to the ServiceNow app store and install the application', } ); const ERROR_MESSAGE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.errorMessage', + 'xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.errorMessage', { defaultMessage: 'Error message', } @@ -39,7 +39,7 @@ const ApplicationRequiredCalloutComponent: React.FC = ({ appId, message } data-test-subj="snApplicationCallout" color="danger" title={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout', + 'xpack.stackConnectors.components.serviceNow.applicationRequiredCallout', { defaultMessage: 'Elastic ServiceNow App not installed', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/credentials_auth.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/credentials_auth.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/credentials_auth.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/credentials_auth.tsx index b996d8feac8e2..46b509e22d6fc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/credentials_auth.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/credentials_auth.tsx @@ -9,7 +9,7 @@ import React, { memo } from 'react'; import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; -import { PasswordField } from '../../../password_field'; +import { PasswordField } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from '../translations'; interface Props { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/index.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/index.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/oauth.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/oauth.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/oauth.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/oauth.tsx index 4c51641ea0bf1..febcb6c498307 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/auth_types/oauth.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/auth_types/oauth.tsx @@ -9,8 +9,8 @@ import React, { memo } from 'react'; import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { TextAreaField, TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; +import { PasswordField } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from '../translations'; -import { PasswordField } from '../../../password_field'; interface Props { readOnly: boolean; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials.test.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials.test.tsx index d0b0b50b0ffc6..aab2ab0fb21c6 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials.test.tsx @@ -9,9 +9,9 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { Credentials } from './credentials'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('Credentials', () => { const connector = { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials_api_url.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials_api_url.tsx similarity index 92% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials_api_url.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials_api_url.tsx index 392b173080346..58130ee8d8a09 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/credentials_api_url.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/credentials_api_url.tsx @@ -12,7 +12,7 @@ import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; -import { useKibana } from '../../../../common/lib/kibana'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; interface Props { @@ -31,7 +31,7 @@ const CredentialsApiUrlComponent: React.FC = ({ isLoading, readOnly, path

    = ({ onMigrate }) => { data-test-subj="snDeprecatedCallout" color="warning" title={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutTitle', + 'xpack.stackConnectors.components.serviceNow.deprecatedCalloutTitle', { defaultMessage: 'This connector type is deprecated', } @@ -40,13 +40,13 @@ const DeprecatedCalloutComponent: React.FC = ({ onMigrate }) => { > {i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutCreate', + 'xpack.stackConnectors.components.serviceNow.deprecatedCalloutCreate', { defaultMessage: 'or create a new one.', } @@ -64,7 +64,7 @@ const DeprecatedCalloutComponent: React.FC = ({ onMigrate }) => { export const DeprecatedCallout = memo(DeprecatedCalloutComponent); const updateThisConnectorMessage = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutMigrate', + 'xpack.stackConnectors.components.serviceNow.deprecatedCalloutMigrate', { defaultMessage: 'Update this connector,', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.test.ts similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.test.ts index a02fca8f2dca4..7700014e58021 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.test.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.test.ts @@ -11,7 +11,7 @@ import { getConnectorDescriptiveTitle, getSelectedConnectorIcon, } from './helpers'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; const deprecatedConnector: ActionConnector = { secrets: {}, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.ts similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.ts index 3798a312083e1..def683edbdd33 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/helpers.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/helpers.ts @@ -7,9 +7,12 @@ import { lazy, ComponentType } from 'react'; import { EuiSelectOption } from '@elastic/eui'; +import { + ActionConnector, + deprecatedMessage, + IErrorObject, +} from '@kbn/triggers-actions-ui-plugin/public'; import { AppInfo, Choice, RESTApiError } from './types'; -import { ActionConnector, IErrorObject } from '../../../../types'; -import { deprecatedMessage } from '../../../../common/connectors_selection'; export const DEFAULT_CORRELATION_ID = '{{rule.id}}:{{alert.id}}'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/index.ts similarity index 73% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/index.ts index c313fd5d0edd6..553cf2edde846 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/index.ts @@ -6,7 +6,7 @@ */ export { - getServiceNowITSMActionType, - getServiceNowSIRActionType, - getServiceNowITOMActionType, + getServiceNowITSMConnectorType, + getServiceNowSIRConnectorType, + getServiceNowITOMConnectorType, } from './servicenow'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/installation_callout.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/installation_callout.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/installation_callout.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/installation_callout.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/installation_callout.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/installation_callout.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/installation_callout.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/installation_callout.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/logo.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/logo.tsx index e2c5546e31a72..f97b07247569d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; function Logo(props: LogoProps) { return ( diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.test.tsx new file mode 100644 index 0000000000000..9427623f0de8a --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; + +const SERVICENOW_ITSM_CONNECTOR_TYPE_ID = '.servicenow'; +const SERVICENOW_SIR_CONNECTOR_TYPE_ID = '.servicenow-sir'; +const SERVICENOW_ITOM_CONNECTOR_TYPE_ID = '.servicenow-itom'; +let connectorTypeRegistry: TypeRegistry; + +beforeAll(() => { + connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); +}); + +describe('connectorTypeRegistry.get() works', () => { + [ + SERVICENOW_ITSM_CONNECTOR_TYPE_ID, + SERVICENOW_SIR_CONNECTOR_TYPE_ID, + SERVICENOW_ITOM_CONNECTOR_TYPE_ID, + ].forEach((id) => { + test(`${id}: connector type static data is as expected`, () => { + const connectorTypeModel = connectorTypeRegistry.get(id); + expect(connectorTypeModel.id).toEqual(id); + }); + }); +}); + +describe('servicenow action params validation', () => { + [SERVICENOW_ITSM_CONNECTOR_TYPE_ID, SERVICENOW_SIR_CONNECTOR_TYPE_ID].forEach((id) => { + test(`${id}: action params validation succeeds when action params is valid`, async () => { + const connectorTypeModel = connectorTypeRegistry.get(id); + const actionParams = { + subActionParams: { incident: { short_description: 'some title {{test}}' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { ['subActionParams.incident.short_description']: [] }, + }); + }); + + test(`${id}: params validation fails when short_description is not valid`, async () => { + const connectorTypeModel = connectorTypeRegistry.get(id); + const actionParams = { + subActionParams: { incident: { short_description: '' }, comments: [] }, + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + ['subActionParams.incident.short_description']: ['Short description is required.'], + }, + }); + }); + }); + + test(`${SERVICENOW_ITOM_CONNECTOR_TYPE_ID}: action params validation succeeds when action params is valid`, async () => { + const connectorTypeModel = connectorTypeRegistry.get(SERVICENOW_ITOM_CONNECTOR_TYPE_ID); + const actionParams = { subActionParams: { severity: 'Critical' } }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { ['severity']: [] }, + }); + }); + + test(`${SERVICENOW_ITOM_CONNECTOR_TYPE_ID}: params validation fails when severity is not valid`, async () => { + const connectorTypeModel = connectorTypeRegistry.get(SERVICENOW_ITOM_CONNECTOR_TYPE_ID); + const actionParams = { subActionParams: { severity: null } }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { ['severity']: ['Severity is required.'] }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.tsx similarity index 84% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.tsx index 85b2aea862848..932d244e852f8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow.tsx @@ -7,7 +7,10 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; import { ServiceNowConfig, ServiceNowITOMActionParams, @@ -18,48 +21,48 @@ import { import { getConnectorDescriptiveTitle, getSelectedConnectorIcon } from './helpers'; export const SERVICENOW_ITOM_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.actionTypeTitle', + 'xpack.stackConnectors.components.serviceNowITOM.connectorTypeTitle', { defaultMessage: 'ServiceNow ITOM', } ); export const SERVICENOW_ITOM_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.selectMessageText', + 'xpack.stackConnectors.components.serviceNowITOM.selectMessageText', { defaultMessage: 'Create an event in ServiceNow ITOM.', } ); export const SERVICENOW_ITSM_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.selectMessageText', + 'xpack.stackConnectors.components.serviceNowITSM.selectMessageText', { defaultMessage: 'Create an incident in ServiceNow ITSM.', } ); export const SERVICENOW_SIR_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.selectMessageText', + 'xpack.stackConnectors.components.serviceNowSIR.selectMessageText', { defaultMessage: 'Create an incident in ServiceNow SecOps.', } ); export const SERVICENOW_ITSM_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.actionTypeTitle', + 'xpack.stackConnectors.components.serviceNowITSM.connectorTypeTitle', { defaultMessage: 'ServiceNow ITSM', } ); export const SERVICENOW_SIR_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.actionTypeTitle', + 'xpack.stackConnectors.components.serviceNowSIR.connectorTypeTitle', { defaultMessage: 'ServiceNow SecOps', } ); -export function getServiceNowITSMActionType(): ActionTypeModel< +export function getServiceNowITSMConnectorType(): ConnectorTypeModel< ServiceNowConfig, ServiceNowSecrets, ServiceNowITSMActionParams @@ -97,7 +100,7 @@ export function getServiceNowITSMActionType(): ActionTypeModel< }; } -export function getServiceNowSIRActionType(): ActionTypeModel< +export function getServiceNowSIRConnectorType(): ConnectorTypeModel< ServiceNowConfig, ServiceNowSecrets, ServiceNowSIRActionParams @@ -135,7 +138,7 @@ export function getServiceNowSIRActionType(): ActionTypeModel< }; } -export function getServiceNowITOMActionType(): ActionTypeModel< +export function getServiceNowITOMConnectorType(): ConnectorTypeModel< ServiceNowConfig, ServiceNowSecrets, ServiceNowITOMActionParams diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.test.tsx index f3ec5594144ec..6bf81f5aeae74 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.test.tsx @@ -10,17 +10,17 @@ import { act, within } from '@testing-library/react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import { render, act as reactAct } from '@testing-library/react'; -import { ConnectorValidationFunc } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; -import { updateActionConnector } from '../../../lib/action_connector_api'; +import { ConnectorValidationFunc } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; +import { updateActionConnector } from '@kbn/triggers-actions-ui-plugin/public/application/lib/action_connector_api'; import ServiceNowConnectorFields from './servicenow_connectors'; import { getAppInfo } from './api'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import { mount } from 'enzyme'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); -jest.mock('../../../lib/action_connector_api'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/application/lib/action_connector_api'); jest.mock('./api'); const useKibanaMock = useKibana as jest.Mocked; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.tsx similarity index 92% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.tsx index d9e462ae552de..b9aeca98b6cde 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors.tsx @@ -8,23 +8,24 @@ import React, { useCallback, useEffect, useState, useMemo } from 'react'; import { EuiSpacer } from '@elastic/eui'; -import { snExternalServiceConfig } from '@kbn/stack-connectors-plugin/common/servicenow_config'; import { useFormContext, useFormData } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; - -import { ActionConnectorFieldsProps } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + HiddenField, + updateActionConnector, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; +import type { ConnectorFormSchema } from '@kbn/triggers-actions-ui-plugin/public'; +import { snExternalServiceConfig } from '../../../../common/servicenow_config'; import { DeprecatedCallout } from './deprecated_callout'; import { useGetAppInfo } from './use_get_app_info'; import { ApplicationRequiredCallout } from './application_required_callout'; import { isRESTApiError } from './helpers'; import { InstallationCallout } from './installation_callout'; import { UpdateConnector, UpdateConnectorFormSchema } from './update_connector'; -import { updateActionConnector } from '../../../lib/action_connector_api'; import { Credentials } from './credentials'; import * as i18n from './translations'; import { ServiceNowActionConnector, ServiceNowConfig, ServiceNowSecrets } from './types'; -import { HiddenField } from '../../hidden_field'; -import { ConnectorFormSchema } from '../../../sections/action_connector_form/types'; // eslint-disable-next-line import/no-default-export export { ServiceNowConnectorFields as default }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.test.tsx index a0dda6edf76e0..e70005f8c7e1b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.test.tsx @@ -8,7 +8,11 @@ import { act } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; -import { AppMockRenderer, ConnectorFormTestProvider, createAppMockRenderer } from '../test_utils'; +import { + AppMockRenderer, + ConnectorFormTestProvider, + createAppMockRenderer, +} from '../../lib/test_utils'; import ServiceNowConnectorFieldsNoApp from './servicenow_connectors_no_app'; describe('ServiceNowActionConnectorFields renders', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.tsx similarity index 85% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.tsx index e4332f163151b..d1a2f3472acbb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors_no_app.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_connectors_no_app.tsx @@ -7,10 +7,9 @@ import React from 'react'; import { useFormData } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; - -import { ActionConnectorFieldsProps } from '../../../../types'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { ConnectorFormSchema } from '@kbn/triggers-actions-ui-plugin/public'; import { Credentials } from './credentials'; -import { ConnectorFormSchema } from '../../../sections/action_connector_form/types'; import { ServiceNowConfig, ServiceNowSecrets } from './types'; const ServiceNowConnectorFieldsNoApp: React.FC = ({ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.test.tsx index d17c77da1f820..60531c7a7104d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.test.tsx @@ -8,12 +8,12 @@ import React from 'react'; import { mount } from 'enzyme'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import { useChoices } from './use_choices'; import ServiceNowITOMParamsFields from './servicenow_itom_params'; jest.mock('./use_choices'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useChoicesMock = useChoices as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.tsx similarity index 94% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.tsx index 8ad32fc0bc86b..caa2f40bac2c1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itom_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itom_params.tsx @@ -7,10 +7,12 @@ import React, { useCallback, useEffect, useRef, useMemo } from 'react'; import { EuiFormRow, EuiSpacer, EuiTitle, EuiSelect } from '@elastic/eui'; -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionParamsProps } from '../../../../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; import { useChoices } from './use_choices'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.test.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.test.tsx index f8375a5aaeb6e..aa6cb6c71278d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.test.tsx @@ -9,14 +9,14 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import { act } from '@testing-library/react'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import { useGetChoices } from './use_get_choices'; import ServiceNowITSMParamsFields from './servicenow_itsm_params'; import { Choice } from './types'; import { merge } from 'lodash'; jest.mock('./use_get_choices'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useGetChoicesMock = useGetChoices as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.tsx index 3bae1c3b858d6..a585ee48864e8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_itsm_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_itsm_params.tsx @@ -16,12 +16,13 @@ import { EuiLink, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; - -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionParamsProps } from '../../../../types'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import { ServiceNowITSMActionParams, Choice, Fields } from './types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; import { useGetChoices } from './use_get_choices'; import { choicesToEuiOptions, DEFAULT_CORRELATION_ID } from './helpers'; @@ -252,7 +253,7 @@ const ServiceNowParamsFields: React.FunctionComponent< helpText={ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_selection_row.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_selection_row.tsx similarity index 81% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_selection_row.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_selection_row.tsx index 65068c6f56a07..f1fbb1a009ec7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_selection_row.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_selection_row.tsx @@ -8,8 +8,8 @@ import { EuiIconTip } from '@elastic/eui'; import React from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionConnector } from '../../../../types'; -import { connectorDeprecatedMessage } from '../../../../common/connectors_selection'; +import type { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; +import { connectorDeprecatedMessage } from '@kbn/triggers-actions-ui-plugin/public'; // eslint-disable-next-line import/no-default-export export { ServiceNowSelectableRowIcon as default }; @@ -32,7 +32,7 @@ export function ServiceNowSelectableRowIcon({ } const deprecatedTooltipTitle = i18n.translate( - 'xpack.triggersActionsUI.sections.actionForm.deprecatedTooltipTitle', + 'xpack.stackConnectors.components.serviceNow.deprecatedTooltipTitle', { defaultMessage: 'Deprecated connector', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.test.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.test.tsx index 9f15cb07f92e1..8739938891625 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.test.tsx @@ -9,14 +9,14 @@ import React from 'react'; import { act } from '@testing-library/react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import { useGetChoices } from './use_get_choices'; import ServiceNowSIRParamsFields from './servicenow_sir_params'; import { Choice } from './types'; import { merge } from 'lodash'; jest.mock('./use_get_choices'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useGetChoicesMock = useGetChoices as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.tsx index a341dca3f255a..e58d635f9ef2d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_sir_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/servicenow_sir_params.tsx @@ -16,11 +16,12 @@ import { EuiLink, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; - -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionParamsProps } from '../../../../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; import { useGetChoices } from './use_get_choices'; @@ -239,7 +240,7 @@ const ServiceNowSIRParamsFields: React.FunctionComponent< helpText={ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/sn_store_button.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/sn_store_button.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/sn_store_button.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/sn_store_button.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/sn_store_button.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/sn_store_button.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/sn_store_button.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/sn_store_button.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/translations.ts similarity index 50% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/translations.ts index 7c6fab2b18792..191fc001d7e80 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/translations.ts @@ -8,146 +8,143 @@ import { i18n } from '@kbn/i18n'; export const API_URL_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiUrlTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.apiUrlTextFieldLabel', { defaultMessage: 'ServiceNow instance URL', } ); export const API_URL_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.invalidApiUrlTextField', + 'xpack.stackConnectors.components.serviceNow.invalidApiUrlTextField', { defaultMessage: 'URL is invalid.', } ); export const AUTHENTICATION_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.authenticationLabel', + 'xpack.stackConnectors.components.serviceNow.authenticationLabel', { defaultMessage: 'Authentication', } ); export const USERNAME_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.usernameTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.usernameTextFieldLabel', { defaultMessage: 'Username', } ); export const USERNAME_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUsernameTextField', + 'xpack.stackConnectors.components.serviceNow.requiredUsernameTextField', { defaultMessage: 'Username is required.', } ); export const PASSWORD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.passwordTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.passwordTextFieldLabel', { defaultMessage: 'Password', } ); export const TITLE_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.common.requiredShortDescTextField', + 'xpack.stackConnectors.components.serviceNow.requiredShortDescTextField', { defaultMessage: 'Short description is required.', } ); -export const INCIDENT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.title', - { - defaultMessage: 'Incident', - } -); +export const INCIDENT = i18n.translate('xpack.stackConnectors.components.serviceNow.title', { + defaultMessage: 'Incident', +}); export const SECURITY_INCIDENT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenowSIR.title', + 'xpack.stackConnectors.components.serviceNowSIR.title', { defaultMessage: 'Security Incident', } ); export const SHORT_DESCRIPTION_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.titleFieldLabel', + 'xpack.stackConnectors.components.serviceNow.titleFieldLabel', { defaultMessage: 'Short description (required)', } ); export const DESCRIPTION_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.descriptionTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.descriptionTextAreaFieldLabel', { defaultMessage: 'Description', } ); export const COMMENTS_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.commentsTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.commentsTextAreaFieldLabel', { defaultMessage: 'Additional comments', } ); export const CHOICES_API_ERROR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unableToGetChoicesMessage', + 'xpack.stackConnectors.components.serviceNow.unableToGetChoicesMessage', { defaultMessage: 'Unable to get choices', } ); export const CATEGORY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.categoryTitle', + 'xpack.stackConnectors.components.serviceNow.categoryTitle', { defaultMessage: 'Category', } ); export const SUBCATEGORY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.subcategoryTitle', + 'xpack.stackConnectors.components.serviceNow.subcategoryTitle', { defaultMessage: 'Subcategory', } ); export const URGENCY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.urgencySelectFieldLabel', + 'xpack.stackConnectors.components.serviceNow.urgencySelectFieldLabel', { defaultMessage: 'Urgency', } ); export const SEVERITY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severitySelectFieldLabel', + 'xpack.stackConnectors.components.serviceNow.severitySelectFieldLabel', { defaultMessage: 'Severity', } ); export const IMPACT_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.impactSelectFieldLabel', + 'xpack.stackConnectors.components.serviceNow.impactSelectFieldLabel', { defaultMessage: 'Impact', } ); export const PRIORITY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.prioritySelectFieldLabel', + 'xpack.stackConnectors.components.serviceNow.prioritySelectFieldLabel', { defaultMessage: 'Priority', } ); export const API_INFO_ERROR = (status: number) => - i18n.translate('xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiInfoError', { + i18n.translate('xpack.stackConnectors.components.serviceNow.apiInfoError', { values: { status }, defaultMessage: 'Received status: {status} when attempting to get application information', }); export const FETCH_ERROR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.fetchErrorMsg', + 'xpack.stackConnectors.components.serviceNow.fetchErrorMsg', { defaultMessage: 'Failed to fetch. Check the URL or the CORS configuration of your ServiceNow instance.', @@ -155,7 +152,7 @@ export const FETCH_ERROR = i18n.translate( ); export const INSTALLATION_CALLOUT_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.installationCalloutTitle', + 'xpack.stackConnectors.components.serviceNow.installationCalloutTitle', { defaultMessage: 'To use this connector, first install the Elastic app from the ServiceNow app store.', @@ -163,218 +160,206 @@ export const INSTALLATION_CALLOUT_TITLE = i18n.translate( ); export const UPDATE_SUCCESS_TOAST_TITLE = (connectorName: string) => - i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateSuccessToastTitle', - { - defaultMessage: '{connectorName} connector updated', - values: { - connectorName, - }, - } - ); + i18n.translate('xpack.stackConnectors.components.serviceNow.updateSuccessToastTitle', { + defaultMessage: '{connectorName} connector updated', + values: { + connectorName, + }, + }); export const UPDATE_SUCCESS_TOAST_TEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateCalloutText', + 'xpack.stackConnectors.components.serviceNow.updateCalloutText', { defaultMessage: 'Connector has been updated.', } ); export const VISIT_SN_STORE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.visitSNStore', + 'xpack.stackConnectors.components.serviceNow.visitSNStore', { defaultMessage: 'Visit ServiceNow app store', } ); export const SETUP_DEV_INSTANCE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.setupDevInstance', + 'xpack.stackConnectors.components.serviceNow.setupDevInstance', { defaultMessage: 'setup a developer instance', } ); export const SN_INSTANCE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.snInstanceLabel', + 'xpack.stackConnectors.components.serviceNow.snInstanceLabel', { defaultMessage: 'ServiceNow instance', } ); -export const UNKNOWN = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unknown', - { - defaultMessage: 'UNKNOWN', - } -); +export const UNKNOWN = i18n.translate('xpack.stackConnectors.components.serviceNow.unknown', { + defaultMessage: 'UNKNOWN', +}); export const CORRELATION_ID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationID', + 'xpack.stackConnectors.components.serviceNow.correlationID', { defaultMessage: 'Correlation ID (optional)', } ); export const CORRELATION_DISPLAY = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationDisplay', + 'xpack.stackConnectors.components.serviceNow.correlationDisplay', { defaultMessage: 'Correlation display (optional)', } ); -export const EVENT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenowITOM.event', - { - defaultMessage: 'Event', - } -); +export const EVENT = i18n.translate('xpack.stackConnectors.components.serviceNowITOM.event', { + defaultMessage: 'Event', +}); /** * ITOM */ export const SOURCE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.sourceTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.sourceTextAreaFieldLabel', { defaultMessage: 'Source', } ); export const EVENT_CLASS = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.eventClassTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.eventClassTextAreaFieldLabel', { defaultMessage: 'Source instance', } ); export const RESOURCE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.resourceTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.resourceTextAreaFieldLabel', { defaultMessage: 'Resource', } ); export const NODE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.nodeTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.nodeTextAreaFieldLabel', { defaultMessage: 'Node', } ); export const METRIC_NAME = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.metricNameTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.metricNameTextAreaFieldLabel', { defaultMessage: 'Metric name', } ); export const TYPE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.typeTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.typeTextAreaFieldLabel', { defaultMessage: 'Type', } ); export const MESSAGE_KEY = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.messageKeyTextAreaFieldLabel', + 'xpack.stackConnectors.components.serviceNow.messageKeyTextAreaFieldLabel', { defaultMessage: 'Message key', } ); export const SEVERITY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredSeverityTextField', + 'xpack.stackConnectors.components.serviceNow.requiredSeverityTextField', { defaultMessage: 'Severity is required.', } ); export const SEVERITY_REQUIRED_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severityRequiredSelectFieldLabel', + 'xpack.stackConnectors.components.serviceNow.severityRequiredSelectFieldLabel', { defaultMessage: 'Severity (required)', } ); export const CLIENTID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientIdTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.clientIdTextFieldLabel', { defaultMessage: 'Client ID', } ); export const CLIENTSECRET_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientSecretTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.clientSecretTextFieldLabel', { defaultMessage: 'Client Secret', } ); export const KEY_ID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.keyIdTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.keyIdTextFieldLabel', { defaultMessage: 'JWT Verifier Key ID', } ); export const USER_IDENTIFIER_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.userEmailTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.userEmailTextFieldLabel', { defaultMessage: 'User Identifier', } ); export const PRIVATE_KEY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.privateKeyTextFieldLabel', { defaultMessage: 'Private Key', } ); export const PRIVATE_KEY_PASSWORD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassTextFieldLabel', + 'xpack.stackConnectors.components.serviceNow.privateKeyPassTextFieldLabel', { defaultMessage: 'Private Key Password', } ); export const PRIVATE_KEY_PASSWORD_HELPER_TEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassLabelHelpText', + 'xpack.stackConnectors.components.serviceNow.privateKeyPassLabelHelpText', { defaultMessage: 'This is only required if you have set a password on your private key', } ); export const CLIENTID_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredClientIdTextField', + 'xpack.stackConnectors.components.serviceNow.requiredClientIdTextField', { defaultMessage: 'Client ID is required.', } ); export const PRIVATE_KEY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredPrivateKeyTextField', + 'xpack.stackConnectors.components.serviceNow.requiredPrivateKeyTextField', { defaultMessage: 'Private Key is required.', } ); export const KEYID_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredKeyIdTextField', + 'xpack.stackConnectors.components.serviceNow.requiredKeyIdTextField', { defaultMessage: 'JWT Verifier Key ID is required.', } ); export const USER_IDENTIFIER_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUserIdentifierTextField', + 'xpack.stackConnectors.components.serviceNow.requiredUserIdentifierTextField', { defaultMessage: 'User Identifier is required.', } ); -export const IS_OAUTH = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.useOAuth', - { - defaultMessage: 'Use OAuth authentication', - } -); +export const IS_OAUTH = i18n.translate('xpack.stackConnectors.components.serviceNow.useOAuth', { + defaultMessage: 'Use OAuth authentication', +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/types.ts similarity index 92% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/types.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/types.ts index e6fbcf6e81939..f10de69252f9d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/types.ts @@ -5,12 +5,12 @@ * 2.0. */ +import { UserConfiguredActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import type { ExecutorSubActionPushParamsITSM, ExecutorSubActionPushParamsSIR, ExecutorSubActionAddEventParams, -} from '@kbn/stack-connectors-plugin/server/connector_types/cases/servicenow/types'; -import { UserConfiguredActionConnector } from '../../../../types'; +} from '../../../../server/connector_types/cases/servicenow/types'; export type ServiceNowActionConnector = UserConfiguredActionConnector< ServiceNowConfig, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.test.tsx index 219ba68114852..9a6d7c26e25f0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.test.tsx @@ -13,7 +13,7 @@ import { Props, UpdateConnector } from './update_connector'; import { act } from 'react-dom/test-utils'; import { render, act as reactAct } from '@testing-library/react'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const mountUpdateConnector = (props: Partial = {}, isOAuth: boolean = false) => { return mountWithIntl( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.tsx similarity index 86% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.tsx index 936e12a564b4a..84bfba31ca56b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/update_connector.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/update_connector.tsx @@ -21,58 +21,55 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { snExternalServiceConfig } from '@kbn/stack-connectors-plugin/common/servicenow_config'; import { useForm, Form } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; +import { snExternalServiceConfig } from '../../../../common/servicenow_config'; import { CredentialsApiUrl } from './credentials_api_url'; import { CredentialsAuth, OAuth } from './auth_types'; import { SNStoreLink } from './sn_store_button'; import { ApplicationRequiredCallout } from './application_required_callout'; import { ServiceNowConfig, ServiceNowSecrets } from './types'; -const title = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormTitle', - { - defaultMessage: 'Update ServiceNow connector', - } -); +const title = i18n.translate('xpack.stackConnectors.components.serviceNow.updateFormTitle', { + defaultMessage: 'Update ServiceNow connector', +}); const step1InstallTitle = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormInstallTitle', + 'xpack.stackConnectors.components.serviceNow.updateFormInstallTitle', { defaultMessage: 'Install the Elastic ServiceNow app', } ); const step2InstanceUrlTitle = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormUrlTitle', + 'xpack.stackConnectors.components.serviceNow.updateFormUrlTitle', { defaultMessage: 'Enter your ServiceNow instance URL', } ); const step3CredentialsTitle = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormCredentialsTitle', + 'xpack.stackConnectors.components.serviceNow.updateFormCredentialsTitle', { defaultMessage: 'Provide authentication credentials', } ); const cancelButtonText = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.cancelButtonText', + 'xpack.stackConnectors.components.serviceNow.cancelButtonText', { defaultMessage: 'Cancel', } ); const confirmButtonText = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.confirmButtonText', + 'xpack.stackConnectors.components.serviceNow.confirmButtonText', { defaultMessage: 'Update', } ); const warningMessage = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.warningMessage', + 'xpack.stackConnectors.components.serviceNow.warningMessage', { defaultMessage: 'This updates all instances of this connector and cannot be reversed.', } @@ -144,7 +141,7 @@ const UpdateConnectorComponent: React.FC = ({ title: step1InstallTitle, children: ( ; const getChoicesMock = getChoices as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_choices.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_choices.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_choices.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_choices.tsx index e3b10896e8707..9b1b0e453f4da 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_choices.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_choices.tsx @@ -8,7 +8,7 @@ import { useCallback, useMemo, useState } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { Choice, Fields } from './types'; import { useGetChoices } from './use_get_choices'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_app_info.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_app_info.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_app_info.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_app_info.test.tsx index f8e9a2c4bac1a..c8c061c9d07f1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_app_info.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_app_info.test.tsx @@ -13,7 +13,7 @@ import { ServiceNowActionConnector } from './types'; import { httpServiceMock } from '@kbn/core/public/mocks'; jest.mock('./api'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const getAppInfoMock = getAppInfo as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_app_info.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_app_info.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_app_info.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_app_info.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.test.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.test.tsx index 06956e6402300..b4d204c117b50 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.test.tsx @@ -7,13 +7,13 @@ import { renderHook } from '@testing-library/react-hooks'; -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionConnector } from '../../../../types'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import { useGetChoices, UseGetChoices, UseGetChoicesProps } from './use_get_choices'; import { getChoices } from './api'; jest.mock('./api'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useKibanaMock = useKibana as jest.Mocked; const getChoicesMock = getChoices as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.tsx index e81e0efe56a42..e2f0117e78ce4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/use_get_choices.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/servicenow/use_get_choices.tsx @@ -7,7 +7,7 @@ import { useState, useEffect, useRef, useCallback } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { ActionConnector } from '../../../../types'; +import { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { getChoices } from './api'; import { Choice } from './types'; import * as i18n from './translations'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/api.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/api.test.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/api.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/api.test.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/api.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/api.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/api.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/api.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/helpers.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/helpers.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/helpers.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/helpers.ts diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/index.ts new file mode 100644 index 0000000000000..0819c1b731ac6 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getSwimlaneConnectorType } from './swimlane'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/logo.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/logo.tsx index 572ff62d52f82..c86f97bf93a7c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => { return ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/mocks.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/mocks.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/mocks.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/mocks.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/index.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/index.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_connection.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_connection.tsx similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_connection.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_connection.tsx index 1dbb2f21a4fb8..2a32a7cace748 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_connection.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_connection.tsx @@ -11,8 +11,7 @@ import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { FormattedMessage } from '@kbn/i18n-react'; -import { PasswordField } from '../../../password_field'; -import { useKibana } from '../../../../../common/lib/kibana'; +import { PasswordField, useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from '../translations'; interface Props { @@ -73,7 +72,7 @@ const SwimlaneConnectionComponent: React.FunctionComponent = ({ readOnly target="_blank" > diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_fields.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_fields.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_fields.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_fields.tsx index 10afa07c65a16..4afb2eacc8918 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/steps/swimlane_fields.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/steps/swimlane_fields.tsx @@ -16,6 +16,7 @@ import { } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { ComboBoxField } from '@kbn/es-ui-shared-plugin/static/forms/components'; +import { ButtonGroupField } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from '../translations'; import { MappingConfigurationKeys, @@ -23,7 +24,6 @@ import { SwimlaneFieldMappingConfig, } from '../types'; import { isRequiredField, isValidFieldForConnector } from '../helpers'; -import { ButtonGroupField } from '../../../button_group_field'; const SINGLE_SELECTION = { asPlainText: true }; const EMPTY_COMBO_BOX_ARRAY: Array> | undefined = []; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.test.tsx similarity index 55% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.test.tsx index 479496b57ba83..13b68388573a7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.test.tsx @@ -5,26 +5,26 @@ * 2.0. */ -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; -const ACTION_TYPE_ID = '.swimlane'; -let actionTypeModel: ActionTypeModel; +const CONNECTOR_TYPE_ID = '.swimlane'; +let connectorTypeModel: ConnectorTypeModel; beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); if (getResult !== null) { - actionTypeModel = getResult; + connectorTypeModel = getResult; } }); -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); }); }); @@ -37,7 +37,7 @@ describe('swimlane action params validation', () => { }, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.ruleName': [], 'subActionParams.incident.alertId': [], @@ -50,7 +50,7 @@ describe('swimlane action params validation', () => { subActionParams: { incident: {} }, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.ruleName': ['Rule name is required.'], 'subActionParams.incident.alertId': ['Alert ID is required.'], @@ -63,7 +63,7 @@ describe('swimlane action params validation', () => { subActionParams: {}, }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { 'subActionParams.incident.ruleName': [], 'subActionParams.incident.alertId': [], diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.tsx similarity index 85% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.tsx index 5a072a54efb67..594c2e83c891f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane.tsx @@ -7,24 +7,27 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; import { SwimlaneConfig, SwimlaneSecrets, SwimlaneActionParams } from './types'; export const SW_SELECT_MESSAGE_TEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.selectMessageText', + 'xpack.stackConnectors.components.swimlane.selectMessageText', { defaultMessage: 'Create record in Swimlane', } ); export const SW_ACTION_TYPE_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.actionTypeTitle', + 'xpack.stackConnectors.components.swimlane.connectorTypeTitle', { defaultMessage: 'Create Swimlane Record', } ); -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< SwimlaneConfig, SwimlaneSecrets, SwimlaneActionParams diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.test.tsx index bbe86a4fe7fe1..c36b786863e3e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.test.tsx @@ -11,12 +11,12 @@ import { act } from 'react-dom/test-utils'; import SwimlaneActionConnectorFields from './swimlane_connectors'; import { useGetApplication } from './use_get_application'; import { applicationFields, mappings } from './mocks'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import { waitFor } from '@testing-library/dom'; import userEvent from '@testing-library/user-event'; import { render } from '@testing-library/react'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); jest.mock('./use_get_application'); const useGetApplicationMock = useGetApplication as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.tsx index af59b9517b91d..a7533f912ed46 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_connectors.tsx @@ -15,8 +15,8 @@ import { EuiStepStatus, } from '@elastic/eui'; import { useFormContext, useFormData } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; -import { useKibana } from '../../../../common/lib/kibana'; -import { ActionConnectorFieldsProps } from '../../../../types'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import { SwimlaneFieldMappingConfig } from './types'; import { SwimlaneConnection, SwimlaneFields } from './steps'; import { useGetApplication } from './use_get_application'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_params.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_params.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_params.tsx similarity index 95% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_params.tsx index 098e6490f3fe2..1faa8c8bbabf4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/swimlane_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/swimlane_params.tsx @@ -7,11 +7,13 @@ import React, { useCallback, useEffect, useRef, useMemo } from 'react'; import { EuiCallOut, EuiFormRow, EuiSpacer } from '@elastic/eui'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, +} from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; -import { ActionParamsProps } from '../../../../types'; import { SwimlaneActionConnector, SwimlaneActionParams, SwimlaneConnectorType } from './types'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; const SwimlaneParamsFields: React.FunctionComponent> = ({ actionParams, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/translations.ts similarity index 53% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/translations.ts index 631e69e8e7a66..08d4a9fd198d7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/translations.ts @@ -8,140 +8,137 @@ import { i18n } from '@kbn/i18n'; export const SW_REQUIRED_RULE_NAME = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredRuleName', + 'xpack.stackConnectors.components.swimlane.error.requiredRuleName', { defaultMessage: 'Rule name is required.', } ); export const SW_REQUIRED_APP_ID_TEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAppIdText', + 'xpack.stackConnectors.components.swimlane.error.requiredAppIdText', { defaultMessage: 'An App ID is required.', } ); export const SW_GET_APPLICATION_API_ERROR = (id: string | null) => - i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationMessage', - { - defaultMessage: 'Unable to get application with id {id}', - values: { id }, - } - ); + i18n.translate('xpack.stackConnectors.components.swimlane.unableToGetApplicationMessage', { + defaultMessage: 'Unable to get application with id {id}', + values: { id }, + }); export const SW_GET_APPLICATION_API_NO_FIELDS_ERROR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationFieldsMessage', + 'xpack.stackConnectors.components.swimlane.unableToGetApplicationFieldsMessage', { defaultMessage: 'Unable to get application fields', } ); export const SW_API_URL_TEXT_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiUrlTextFieldLabel', + 'xpack.stackConnectors.components.swimlane.apiUrlTextFieldLabel', { defaultMessage: 'API Url', } ); export const SW_API_URL_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.invalidApiUrlTextField', + 'xpack.stackConnectors.components.swimlane.invalidApiUrlTextField', { defaultMessage: 'URL is invalid.', } ); export const SW_APP_ID_TEXT_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.appIdTextFieldLabel', + 'xpack.stackConnectors.components.swimlane.appIdTextFieldLabel', { defaultMessage: 'Application ID', } ); export const SW_API_TOKEN_TEXT_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenTextFieldLabel', + 'xpack.stackConnectors.components.swimlane.apiTokenTextFieldLabel', { defaultMessage: 'API Token', } ); export const SW_MAPPING_TITLE_TEXT_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.mappingTitleTextFieldLabel', + 'xpack.stackConnectors.components.swimlane.mappingTitleTextFieldLabel', { defaultMessage: 'Configure Field Mappings', } ); export const SW_SEVERITY_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.severityFieldLabel', + 'xpack.stackConnectors.components.swimlane.severityFieldLabel', { defaultMessage: 'Severity', } ); export const SW_RULE_NAME_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.ruleNameFieldLabel', + 'xpack.stackConnectors.components.swimlane.ruleNameFieldLabel', { defaultMessage: 'Rule name', } ); export const SW_ALERT_ID_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.alertIdFieldLabel', + 'xpack.stackConnectors.components.swimlane.alertIdFieldLabel', { defaultMessage: 'Alert ID', } ); export const SW_CASE_ID_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseIdFieldLabel', + 'xpack.stackConnectors.components.swimlane.caseIdFieldLabel', { defaultMessage: 'Case ID', } ); export const SW_CASE_NAME_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseNameFieldLabel', + 'xpack.stackConnectors.components.swimlane.caseNameFieldLabel', { defaultMessage: 'Case name', } ); export const SW_COMMENTS_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.commentsFieldLabel', + 'xpack.stackConnectors.components.swimlane.commentsFieldLabel', { defaultMessage: 'Comments', } ); export const SW_DESCRIPTION_FIELD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.descriptionFieldLabel', + 'xpack.stackConnectors.components.swimlane.descriptionFieldLabel', { defaultMessage: 'Description', } ); export const SW_CONFIGURE_CONNECTION_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.configureConnectionLabel', + 'xpack.stackConnectors.components.swimlane.configureConnectionLabel', { defaultMessage: 'Configure API Connection' } ); export const SW_CONNECTOR_TYPE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.connectorType', + 'xpack.stackConnectors.components.swimlane.connectorType', { defaultMessage: 'Connector Type', } ); export const EMPTY_MAPPING_WARNING_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningTitle', + 'xpack.stackConnectors.components.swimlane.emptyMappingWarningTitle', { defaultMessage: 'This connector has missing field mappings', } ); export const EMPTY_MAPPING_WARNING_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningDesc', + 'xpack.stackConnectors.components.swimlane.emptyMappingWarningDesc', { defaultMessage: 'This connector cannot be selected because it is missing the required alert field mappings. You can edit this connector to add required field mappings or select a connector of type Alerts.', @@ -149,63 +146,57 @@ export const EMPTY_MAPPING_WARNING_DESC = i18n.translate( ); export const SW_REQUIRED_SEVERITY = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredSeverity', + 'xpack.stackConnectors.components.swimlane.error.requiredSeverity', { defaultMessage: 'Severity is required.', } ); export const SW_REQUIRED_CASE_NAME = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseName', + 'xpack.stackConnectors.components.swimlane.error.requiredCaseName', { defaultMessage: 'Case name is required.', } ); export const SW_REQUIRED_CASE_ID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseID', + 'xpack.stackConnectors.components.swimlane.error.requiredCaseID', { defaultMessage: 'Case ID is required.', } ); export const SW_REQUIRED_COMMENTS = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredComments', + 'xpack.stackConnectors.components.swimlane.error.requiredComments', { defaultMessage: 'Comments are required.', } ); export const SW_REQUIRED_DESCRIPTION = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredDescription', + 'xpack.stackConnectors.components.swimlane.error.requiredDescription', { defaultMessage: 'Description is required.', } ); export const SW_REQUIRED_ALERT_ID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAlertID', + 'xpack.stackConnectors.components.swimlane.error.requiredAlertID', { defaultMessage: 'Alert ID is required.', } ); -export const SW_BACK = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.prevStep', - { - defaultMessage: 'Back', - } -); +export const SW_BACK = i18n.translate('xpack.stackConnectors.components.swimlane.prevStep', { + defaultMessage: 'Back', +}); -export const SW_NEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStep', - { - defaultMessage: 'Next', - } -); +export const SW_NEXT = i18n.translate('xpack.stackConnectors.components.swimlane.nextStep', { + defaultMessage: 'Next', +}); export const SW_FIELDS_BUTTON_HELP_TEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStepHelpText', + 'xpack.stackConnectors.components.swimlane.nextStepHelpText', { defaultMessage: 'If field mappings are not configured, Swimlane connector type will be set to all.', diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/types.ts similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/types.ts rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/types.ts index cf77b094e5a12..398a63164f9e4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/types.ts @@ -5,11 +5,11 @@ * 2.0. */ +import { UserConfiguredActionConnector } from '@kbn/triggers-actions-ui-plugin/public/types'; import type { ExecutorSubActionPushParams, MappingConfigType, -} from '@kbn/stack-connectors-plugin/server/connector_types/cases/swimlane/types'; -import { UserConfiguredActionConnector } from '../../../../types'; +} from '../../../../server/connector_types/cases/swimlane/types'; export type SwimlaneActionConnector = UserConfiguredActionConnector< SwimlaneConfig, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/use_get_application.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/use_get_application.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/use_get_application.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/use_get_application.test.tsx index f852d40ebef2f..d56f0d0a1d7a5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/use_get_application.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/use_get_application.test.tsx @@ -7,12 +7,12 @@ import { renderHook, act } from '@testing-library/react-hooks'; -import { useKibana } from '../../../../common/lib/kibana'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'; import { getApplication } from './api'; import { useGetApplication, UseGetApplication } from './use_get_application'; jest.mock('./api'); -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useKibanaMock = useKibana as jest.Mocked; const getApplicationMock = getApplication as jest.Mock; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/use_get_application.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/use_get_application.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/use_get_application.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/swimlane/use_get_application.tsx diff --git a/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/index.ts new file mode 100644 index 0000000000000..0faa7732194c5 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getXmattersConnectorType } from './xmatters'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/logo.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/logo.tsx index dad43f666ad0a..438710f2516c7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => ( { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.actionTypeTitle).toEqual('xMatters data'); + }); +}); + +describe('xmatters action params validation', () => { + test('action params validation succeeds when action params is valid', async () => { + const actionParams = { + alertActionGroupName: 'Small t-shirt', + signalId: 'c9437cab-6a5b-45e8-bc8a-f4a8af440e97', + ruleName: 'Test xMatters', + date: '2022-01-18T19:01:08.818Z', + severity: 'high', + spaceId: 'default', + tags: 'test1, test2', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { alertActionGroupName: [], signalId: [] }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters.tsx similarity index 75% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters.tsx index 9f2955479d52e..2ad23f91b7c3f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters.tsx @@ -7,11 +7,14 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { XmattersActionParams, XmattersConfig, XmattersSecrets } from '../types'; -import { AlertProvidedActionVariables } from '../../../lib/action_variables'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { AlertProvidedActionVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { XmattersActionParams, XmattersConfig, XmattersSecrets } from '../../types'; -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< XmattersConfig, XmattersSecrets, XmattersActionParams @@ -19,14 +22,11 @@ export function getActionType(): ActionTypeModel< return { id: '.xmatters', iconClass: lazy(() => import('./logo')), - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.selectMessageText', - { - defaultMessage: 'Trigger an xMatters workflow.', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.xmatters.selectMessageText', { + defaultMessage: 'Trigger an xMatters workflow.', + }), actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.actionTypeTitle', + 'xpack.stackConnectors.components.xmatters.connectorTypeTitle', { defaultMessage: 'xMatters data', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.test.tsx index cef4c2c2bef81..be7a6dc0ebdb4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import XmattersActionConnectorFields from './xmatters_connectors'; -import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../test_utils'; +import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../../lib/test_utils'; import userEvent from '@testing-library/user-event'; import { act } from 'react-dom/test-utils'; import { render } from '@testing-library/react'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.tsx similarity index 89% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.tsx index 247a700876d14..881ea4c2164e2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_connectors.tsx @@ -16,12 +16,14 @@ import { useFormData, } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; -import { ActionConnectorFieldsProps } from '../../../../types'; -import { XmattersAuthenticationType } from '../types'; -import { ButtonGroupField } from '../../button_group_field'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + ButtonGroupField, + HiddenField, + PasswordField, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { XmattersAuthenticationType } from '../../types'; import * as i18n from './translations'; -import { PasswordField } from '../../password_field'; -import { HiddenField } from '../../hidden_field'; const { emptyField, urlField } = fieldValidators; @@ -53,7 +55,7 @@ const XmattersUrlField: React.FC<{ path: string; readOnly: boolean }> = ({ path, label: i18n.URL_LABEL, helpText: ( ), @@ -99,7 +101,7 @@ const XmattersActionConnectorFields: React.FunctionComponent

    @@ -133,7 +135,7 @@ const XmattersActionConnectorFields: React.FunctionComponent diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.test.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.test.tsx index 64c4b5ead81ae..500ee77efbd0d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; -import { XmattersSeverityOptions } from '../types'; +import { XmattersSeverityOptions } from '../../types'; import XmattersParamsFields from './xmatters_params'; describe('XmattersParamsFields renders', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.tsx similarity index 68% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.tsx index f66583ef32dd8..b97db2f349f8e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/cases/xmatters/xmatters_params.tsx @@ -9,15 +9,15 @@ import React, { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; import { isUndefined } from 'lodash'; -import { ActionParamsProps } from '../../../../types'; -import { XmattersActionParams } from '../types'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { TextFieldWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { XmattersActionParams } from '../../types'; const severityOptions = [ { value: 'critical', text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectCriticalOptionLabel', + 'xpack.stackConnectors.components.xmatters.severitySelectCriticalOptionLabel', { defaultMessage: 'Critical', } @@ -26,7 +26,7 @@ const severityOptions = [ { value: 'high', text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectHighOptionLabel', + 'xpack.stackConnectors.components.xmatters.severitySelectHighOptionLabel', { defaultMessage: 'High', } @@ -35,7 +35,7 @@ const severityOptions = [ { value: 'medium', text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMediumOptionLabel', + 'xpack.stackConnectors.components.xmatters.severitySelectMediumOptionLabel', { defaultMessage: 'Medium', } @@ -43,17 +43,14 @@ const severityOptions = [ }, { value: 'low', - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectLowOptionLabel', - { - defaultMessage: 'Low', - } - ), + text: i18n.translate('xpack.stackConnectors.components.xmatters.severitySelectLowOptionLabel', { + defaultMessage: 'Low', + }), }, { value: 'minimal', text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMinimalOptionLabel', + 'xpack.stackConnectors.components.xmatters.severitySelectMinimalOptionLabel', { defaultMessage: 'Minimal', } @@ -91,12 +88,9 @@ const XmattersParamsFields: React.FunctionComponent ValidatedEmail[]; +} + +export function registerConnectorTypes({ + connectorTypeRegistry, + services, +}: { + connectorTypeRegistry: TriggersAndActionsUIPublicPluginSetup['actionTypeRegistry']; + services: RegistrationServices; +}) { + connectorTypeRegistry.register(getServerLogConnectorType()); + connectorTypeRegistry.register(getSlackConnectorType()); + connectorTypeRegistry.register(getEmailConnectorType(services)); + connectorTypeRegistry.register(getIndexConnectorType()); + connectorTypeRegistry.register(getPagerDutyConnectorType()); + connectorTypeRegistry.register(getSwimlaneConnectorType()); + connectorTypeRegistry.register(getCasesWebhookConnectorType()); + connectorTypeRegistry.register(getWebhookConnectorType()); + connectorTypeRegistry.register(getXmattersConnectorType()); + connectorTypeRegistry.register(getServiceNowITSMConnectorType()); + connectorTypeRegistry.register(getServiceNowITOMConnectorType()); + connectorTypeRegistry.register(getServiceNowSIRConnectorType()); + connectorTypeRegistry.register(getJiraConnectorType()); + connectorTypeRegistry.register(getResilientConnectorType()); + connectorTypeRegistry.register(getTeamsConnectorType()); +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/extract_action_variable.ts b/x-pack/plugins/stack_connectors/public/connector_types/lib/extract_action_variable.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/extract_action_variable.ts rename to x-pack/plugins/stack_connectors/public/connector_types/lib/extract_action_variable.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/rewrite_response_body.ts b/x-pack/plugins/stack_connectors/public/connector_types/lib/rewrite_response_body.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/rewrite_response_body.ts rename to x-pack/plugins/stack_connectors/public/connector_types/lib/rewrite_response_body.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/test_utils.tsx b/x-pack/plugins/stack_connectors/public/connector_types/lib/test_utils.tsx similarity index 80% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/test_utils.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/lib/test_utils.tsx index c1c5eaefaa42c..59a6d3808ff81 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/test_utils.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/lib/test_utils.tsx @@ -6,7 +6,6 @@ */ import React, { useCallback } from 'react'; -import { ReactWrapper } from 'enzyme'; import { of } from 'rxjs'; import { I18nProvider } from '@kbn/i18n-react'; import { EuiButton } from '@elastic/eui'; @@ -16,12 +15,12 @@ import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { render as reactRender, RenderOptions, RenderResult } from '@testing-library/react'; import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; -import { ConnectorServices } from '../../../types'; -import { TriggersAndActionsUiServices } from '../../..'; -import { createStartServicesMock } from '../../../common/lib/kibana/kibana_react.mock'; -import { ConnectorFormSchema } from '../../sections/action_connector_form/types'; -import { ConnectorFormFieldsGlobal } from '../../sections/action_connector_form/connector_form_fields_global'; -import { ConnectorProvider } from '../../context/connector_context'; +import { ConnectorServices } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { TriggersAndActionsUiServices } from '@kbn/triggers-actions-ui-plugin/public'; +import { createStartServicesMock } from '@kbn/triggers-actions-ui-plugin/public/common/lib/kibana/kibana_react.mock'; +import { ConnectorFormSchema } from '@kbn/triggers-actions-ui-plugin/public/application/sections/action_connector_form/types'; +import { ConnectorFormFieldsGlobal } from '@kbn/triggers-actions-ui-plugin/public/application/sections/action_connector_form/connector_form_fields_global'; +import { ConnectorProvider } from '@kbn/triggers-actions-ui-plugin/public/application/context/connector_context'; interface FormTestProviderProps { children: React.ReactNode; @@ -81,16 +80,6 @@ const FormTestProviderComponent: React.FC = ({ ); }; -FormTestProviderComponent.displayName = 'FormTestProvider'; -export const FormTestProvider = React.memo(FormTestProviderComponent); - -export async function waitForComponentToPaint

    (wrapper: ReactWrapper

    , amount = 0) { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, amount)); - wrapper.update(); - }); -} - export const waitForComponentToUpdate = async () => await act(async () => { return Promise.resolve(); diff --git a/x-pack/plugins/stack_connectors/public/connector_types/security/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/security/index.ts new file mode 100644 index 0000000000000..1fec1c76430eb --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/security/index.ts @@ -0,0 +1,6 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/api.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/api.ts similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/api.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/api.ts index 913bda49fe53d..3323d3527428e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/api.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/api.ts @@ -6,8 +6,8 @@ */ import { HttpSetup } from '@kbn/core/public'; -import { INTERNAL_BASE_STACK_CONNECTORS_API_PATH } from '../../../constants'; -import { EmailConfig } from '../types'; +import { INTERNAL_BASE_STACK_CONNECTORS_API_PATH } from '../../../../common'; +import { EmailConfig } from '../../types'; export async function getServiceConfig({ http, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.test.tsx similarity index 74% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.test.tsx index 9e61d84f5fb31..4e67bdabef993 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.test.tsx @@ -5,9 +5,9 @@ * 2.0. */ -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; import { getEmailServices } from './email'; import { ValidatedEmail, @@ -16,8 +16,8 @@ import { MustacheInEmailRegExp, } from '@kbn/actions-plugin/common'; -const ACTION_TYPE_ID = '.email'; -let actionTypeModel: ActionTypeModel; +const CONNECTOR_TYPE_ID = '.email'; +let connectorTypeModel: ConnectorTypeModel; const RegistrationServices = { validateEmailAddresses: validateEmails, @@ -45,18 +45,18 @@ beforeEach(() => { }); beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: RegistrationServices }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: RegistrationServices }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); if (getResult !== null) { - actionTypeModel = getResult; + connectorTypeModel = getResult; } }); -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('email'); +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('email'); }); }); @@ -82,7 +82,7 @@ describe('action params validation', () => { subject: 'test', }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { to: [], cc: [], @@ -101,7 +101,7 @@ describe('action params validation', () => { subject: 'test', }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { to: ['Email address invalid.com is not valid.'], cc: ['Email address bob@notallowed.com is not allowed.'], diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.tsx similarity index 67% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.tsx index b44d13fb02ec1..73330de39be7e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email.tsx @@ -10,63 +10,48 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiSelectOption } from '@elastic/eui'; import { InvalidEmailReason } from '@kbn/actions-plugin/common'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { EmailActionParams, EmailConfig, EmailSecrets } from '../types'; -import { RegistrationServices } from '..'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public/types'; +import { EmailActionParams, EmailConfig, EmailSecrets } from '../../types'; +import { RegistrationServices } from '../..'; const emailServices: EuiSelectOption[] = [ { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.gmailServerTypeLabel', - { - defaultMessage: 'Gmail', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.gmailServerTypeLabel', { + defaultMessage: 'Gmail', + }), value: 'gmail', }, { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.outlookServerTypeLabel', - { - defaultMessage: 'Outlook', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.outlookServerTypeLabel', { + defaultMessage: 'Outlook', + }), value: 'outlook365', }, { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.amazonSesServerTypeLabel', - { - defaultMessage: 'Amazon SES', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.amazonSesServerTypeLabel', { + defaultMessage: 'Amazon SES', + }), value: 'ses', }, { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.elasticCloudServerTypeLabel', - { - defaultMessage: 'Elastic Cloud', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.elasticCloudServerTypeLabel', { + defaultMessage: 'Elastic Cloud', + }), value: 'elastic_cloud', }, { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.exchangeServerTypeLabel', - { - defaultMessage: 'MS Exchange Server', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.exchangeServerTypeLabel', { + defaultMessage: 'MS Exchange Server', + }), value: 'exchange_server', }, { - text: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.otherServerTypeLabel', - { - defaultMessage: 'Other', - } - ), + text: i18n.translate('xpack.stackConnectors.components.email.otherServerTypeLabel', { + defaultMessage: 'Other', + }), value: 'other', }, ]; @@ -77,24 +62,18 @@ export function getEmailServices(isCloudEnabled: boolean) { : emailServices.filter((service) => service.value !== 'elastic_cloud'); } -export function getActionType( +export function getConnectorType( services: RegistrationServices -): ActionTypeModel { +): ConnectorTypeModel { return { id: '.email', iconClass: 'email', - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.selectMessageText', - { - defaultMessage: 'Send email from your server.', - } - ), - actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.actionTypeTitle', - { - defaultMessage: 'Send to email', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.email.selectMessageText', { + defaultMessage: 'Send email from your server.', + }), + actionTypeTitle: i18n.translate('xpack.stackConnectors.components.email.connectorTypeTitle', { + defaultMessage: 'Send to email', + }), validateParams: async ( actionParams: EmailActionParams ): Promise> => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.test.tsx index b06340c7a180d..ac9ba471b2442 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.test.tsx @@ -9,7 +9,7 @@ import React, { Suspense } from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import { act } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { useKibana } from '../../../../common/lib/kibana'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import EmailActionConnectorFields from './email_connector'; import * as hooks from './use_email_config'; import { @@ -17,9 +17,9 @@ import { ConnectorFormTestProvider, createAppMockRenderer, waitForComponentToUpdate, -} from '../test_utils'; +} from '../../lib/test_utils'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); const useKibanaMock = useKibana as jest.Mocked; describe('EmailActionConnectorFields', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.tsx similarity index 94% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.tsx index 213d30ff4e5e4..502dc1d82dd1e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_connector.tsx @@ -11,7 +11,6 @@ import { EuiFlexItem, EuiFlexGroup, EuiTitle, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiLink } from '@elastic/eui'; import { InvalidEmailReason } from '@kbn/actions-plugin/common'; -import { AdditionalEmailServices } from '@kbn/stack-connectors-plugin/common'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { ActionsPublicPluginSetup } from '@kbn/actions-plugin/public'; import { @@ -26,13 +25,16 @@ import { TextField, ToggleField, } from '@kbn/es-ui-shared-plugin/static/forms/components'; -import { ActionConnectorFieldsProps } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + PasswordField, + useConnectorContext, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { AdditionalEmailServices } from '../../../../common'; import { getEmailServices } from './email'; import { useEmailConfig } from './use_email_config'; -import { PasswordField } from '../../password_field'; import * as i18n from './translations'; -import { useConnectorContext } from '../../../context/use_connector_context'; const { emptyField } = fieldValidators; @@ -50,7 +52,7 @@ const getEmailConfig = ( helpText: ( @@ -254,7 +256,7 @@ export const EmailActionConnectorFields: React.FunctionComponent

    diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_params.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_params.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_params.tsx similarity index 85% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_params.tsx index 0f894e011d3ea..9e5f1b06ad92b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/email_params.tsx @@ -9,10 +9,12 @@ import React, { useState, useEffect } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiComboBox, EuiButtonEmpty, EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { ActionParamsProps } from '../../../../types'; -import { EmailActionParams } from '../types'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { EmailActionParams } from '../../types'; export const EmailParamsFields = ({ actionParams, @@ -59,12 +61,9 @@ export const EmailParamsFields = ({ fullWidth error={errors.to} isInvalid={isToInvalid} - label={i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientTextFieldLabel', - { - defaultMessage: 'To', - } - )} + label={i18n.translate('xpack.stackConnectors.components.email.recipientTextFieldLabel', { + defaultMessage: 'To', + })} labelAppend={ <> @@ -72,7 +71,7 @@ export const EmailParamsFields = ({ setAddCC(true)}> ) : null} @@ -80,7 +79,7 @@ export const EmailParamsFields = ({ setAddBCC(true)}> ) : null} @@ -125,7 +124,7 @@ export const EmailParamsFields = ({ isInvalid={isCCInvalid} isDisabled={isDisabled} label={i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientCopyTextFieldLabel', + 'xpack.stackConnectors.components.email.recipientCopyTextFieldLabel', { defaultMessage: 'Cc', } @@ -167,7 +166,7 @@ export const EmailParamsFields = ({ error={errors.bcc} isInvalid={isBCCInvalid} label={i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientBccTextFieldLabel', + 'xpack.stackConnectors.components.email.recipientBccTextFieldLabel', { defaultMessage: 'Bcc', } @@ -209,12 +208,9 @@ export const EmailParamsFields = ({ fullWidth error={errors.subject} isInvalid={isSubjectInvalid} - label={i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.subjectTextFieldLabel', - { - defaultMessage: 'Subject', - } - )} + label={i18n.translate('xpack.stackConnectors.components.email.subjectTextFieldLabel', { + defaultMessage: 'Subject', + })} > { const actionConnector = { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/exchange_form.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/exchange_form.tsx similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/exchange_form.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/exchange_form.tsx index 41f82b3a32bfc..c38eebcf44fc1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/exchange_form.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/exchange_form.tsx @@ -11,9 +11,8 @@ import { FormattedMessage } from '@kbn/i18n-react'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; import { TextField } from '@kbn/es-ui-shared-plugin/static/forms/components'; -import { useKibana } from '../../../../common/lib/kibana'; +import { PasswordField, useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; -import { PasswordField } from '../../password_field'; const { emptyField } = fieldValidators; @@ -36,7 +35,7 @@ const ExchangeFormFields: React.FC = ({ readOnly }) => helpText: ( @@ -63,7 +62,7 @@ const ExchangeFormFields: React.FC = ({ readOnly }) => helpText: ( @@ -94,7 +93,7 @@ const ExchangeFormFields: React.FC = ({ readOnly }) => target="_blank" > diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/index.ts similarity index 78% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/index.ts index 419fb069aa8c7..42fa6d59fefd3 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { getActionType as getIndexActionType } from './es_index'; +export { getConnectorType as getEmailConnectorType } from './email'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/translations.ts similarity index 54% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/translations.ts index 65fc2bdb542e8..c21418f349096 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/translations.ts @@ -8,171 +8,168 @@ import { i18n } from '@kbn/i18n'; export const USERNAME_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.userTextFieldLabel', + 'xpack.stackConnectors.components.email.userTextFieldLabel', { defaultMessage: 'Username', } ); export const PASSWORD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.passwordFieldLabel', + 'xpack.stackConnectors.components.email.passwordFieldLabel', { defaultMessage: 'Password', } ); export const FROM_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.fromTextFieldLabel', + 'xpack.stackConnectors.components.email.fromTextFieldLabel', { defaultMessage: 'Sender', } ); export const SERVICE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.serviceTextFieldLabel', + 'xpack.stackConnectors.components.email.serviceTextFieldLabel', { defaultMessage: 'Service', } ); export const TENANT_ID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.tenantIdFieldLabel', + 'xpack.stackConnectors.components.email.tenantIdFieldLabel', { defaultMessage: 'Tenant ID', } ); export const CLIENT_ID_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientIdFieldLabel', + 'xpack.stackConnectors.components.email.clientIdFieldLabel', { defaultMessage: 'Client ID', } ); export const CLIENT_SECRET_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientSecretTextFieldLabel', + 'xpack.stackConnectors.components.email.clientSecretTextFieldLabel', { defaultMessage: 'Client Secret', } ); export const HOST_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hostTextFieldLabel', + 'xpack.stackConnectors.components.email.hostTextFieldLabel', { defaultMessage: 'Host', } ); export const PORT_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.portTextFieldLabel', + 'xpack.stackConnectors.components.email.portTextFieldLabel', { defaultMessage: 'Port', } ); export const SECURE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.secureSwitchLabel', + 'xpack.stackConnectors.components.email.secureSwitchLabel', { defaultMessage: 'Secure', } ); export const HAS_AUTH_LABEL = i18n.translate( - 'xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hasAuthSwitchLabel', + 'xpack.stackConnectors.components.email.hasAuthSwitchLabel', { defaultMessage: 'Require authentication for this server', } ); export const SENDER_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredFromText', + 'xpack.stackConnectors.components.email.error.requiredFromText', { defaultMessage: 'Sender is required.', } ); export const CLIENT_ID_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredClientIdText', + 'xpack.stackConnectors.components.email.error.requiredClientIdText', { defaultMessage: 'Client ID is required.', } ); export const TENANT_ID_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredTenantIdText', + 'xpack.stackConnectors.components.email.error.requiredTenantIdText', { defaultMessage: 'Tenant ID is required.', } ); export const PORT_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredPortText', + 'xpack.stackConnectors.components.email.error.requiredPortText', { defaultMessage: 'Port is required.', } ); export const PORT_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.invalidPortText', + 'xpack.stackConnectors.components.email.error.invalidPortText', { defaultMessage: 'Port is invalid.', } ); export const SERVICE_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServiceText', + 'xpack.stackConnectors.components.email.error.requiredServiceText', { defaultMessage: 'Service is required.', } ); export const HOST_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredHostText', + 'xpack.stackConnectors.components.email.error.requiredHostText', { defaultMessage: 'Host is required.', } ); export const USERNAME_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredAuthUserNameText', + 'xpack.stackConnectors.components.email.error.requiredAuthUserNameText', { defaultMessage: 'Username is required.', } ); export const TO_CC_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredEntryText', + 'xpack.stackConnectors.components.email.error.requiredEntryText', { defaultMessage: 'No To, Cc, or Bcc entry. At least one entry is required.', } ); export const MESSAGE_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredMessageText', + 'xpack.stackConnectors.components.email.error.requiredMessageText', { defaultMessage: 'Message is required.', } ); export const SUBJECT_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSubjectText', + 'xpack.stackConnectors.components.email.error.requiredSubjectText', { defaultMessage: 'Subject is required.', } ); export function getInvalidEmailAddress(email: string) { - return i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.invalidEmail', - { - defaultMessage: 'Email address {email} is not valid.', - values: { email }, - } - ); + return i18n.translate('xpack.stackConnectors.components.email.error.invalidEmail', { + defaultMessage: 'Email address {email} is not valid.', + values: { email }, + }); } export function getNotAllowedEmailAddress(email: string) { - return i18n.translate('xpack.triggersActionsUI.components.builtinActionTypes.error.notAllowed', { + return i18n.translate('xpack.stackConnectors.components.email.error.notAllowed', { defaultMessage: 'Email address {email} is not allowed.', values: { email }, }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/use_email_config.test.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/use_email_config.test.ts similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/use_email_config.test.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/use_email_config.test.ts diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/use_email_config.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/use_email_config.ts similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/use_email_config.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/email/use_email_config.ts index fc0221227783d..c93715e34ef84 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/use_email_config.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/email/use_email_config.ts @@ -8,9 +8,9 @@ import { isEmpty } from 'lodash'; import { useCallback, useEffect, useRef, useState } from 'react'; import { HttpSetup, IToasts } from '@kbn/core/public'; -import { AdditionalEmailServices } from '@kbn/stack-connectors-plugin/common'; import { i18n } from '@kbn/i18n'; -import { EmailConfig } from '../types'; +import { AdditionalEmailServices } from '../../../../common'; +import { EmailConfig } from '../../types'; import { getServiceConfig } from './api'; interface Props { @@ -73,7 +73,7 @@ export function useEmailConfig({ http, toasts }: Props): UseEmailConfigReturnVal toasts.addDanger( error.body?.message ?? i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.updateErrorNotificationText', + 'xpack.stackConnectors.components.email.updateErrorNotificationText', { defaultMessage: 'Cannot get service configuration' } ) ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.test.tsx similarity index 61% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.test.tsx index ccf90cb91d837..f2e927fa42f33 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.test.tsx @@ -5,34 +5,34 @@ * 2.0. */ -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; -const ACTION_TYPE_ID = '.index'; -let actionTypeModel: ActionTypeModel; +const CONNECTOR_TYPE_ID = '.index'; +let connectorTypeModel: ConnectorTypeModel; beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); if (getResult !== null) { - actionTypeModel = getResult; + connectorTypeModel = getResult; } }); -describe('actionTypeRegistry.get() works', () => { - test('action type .index is registered', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('indexOpen'); +describe('connectorTypeRegistry.get() works', () => { + test('connector type .index is registered', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('indexOpen'); }); }); describe('action params validation', () => { test('action params validation succeeds when action params are valid', async () => { expect( - await actionTypeModel.validateParams({ + await connectorTypeModel.validateParams({ documents: [{ test: 1234 }], }) ).toEqual({ @@ -43,7 +43,7 @@ describe('action params validation', () => { }); expect( - await actionTypeModel.validateParams({ + await connectorTypeModel.validateParams({ documents: [{ test: 1234 }], indexOverride: 'kibana-alert-history-anything', }) @@ -56,7 +56,7 @@ describe('action params validation', () => { }); test('action params validation fails when action params are invalid', async () => { - expect(await actionTypeModel.validateParams({})).toEqual({ + expect(await connectorTypeModel.validateParams({})).toEqual({ errors: { documents: ['Document is required and should be a valid JSON object.'], indexOverride: [], @@ -64,7 +64,7 @@ describe('action params validation', () => { }); expect( - await actionTypeModel.validateParams({ + await connectorTypeModel.validateParams({ documents: [{}], }) ).toEqual({ @@ -75,7 +75,7 @@ describe('action params validation', () => { }); expect( - await actionTypeModel.validateParams({ + await connectorTypeModel.validateParams({ documents: [{}], indexOverride: 'kibana-alert-history-', }) @@ -87,7 +87,7 @@ describe('action params validation', () => { }); expect( - await actionTypeModel.validateParams({ + await connectorTypeModel.validateParams({ documents: [{}], indexOverride: 'this.is-a_string', }) diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.tsx similarity index 59% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.tsx index 75666c1282da3..8265af8a74efb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index.tsx @@ -7,25 +7,23 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult, ALERT_HISTORY_PREFIX } from '../../../../types'; -import { EsIndexConfig, IndexActionParams } from '../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { ALERT_HISTORY_PREFIX } from '@kbn/triggers-actions-ui-plugin/public'; +import { EsIndexConfig, IndexActionParams } from '../../types'; -export function getActionType(): ActionTypeModel { +export function getConnectorType(): ConnectorTypeModel { return { id: '.index', iconClass: 'indexOpen', - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.selectMessageText', - { - defaultMessage: 'Index data into Elasticsearch.', - } - ), - actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.actionTypeTitle', - { - defaultMessage: 'Index data', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.index.selectMessageText', { + defaultMessage: 'Index data into Elasticsearch.', + }), + actionTypeTitle: i18n.translate('xpack.stackConnectors.components.index.connectorTypeTitle', { + defaultMessage: 'Index data', + }), actionConnectorFields: lazy(() => import('./es_index_connector')), actionParamsFields: lazy(() => import('./es_index_params')), validateParams: async ( @@ -43,13 +41,10 @@ export function getActionType(): ActionTypeModel { const module = jest.requireActual('lodash'); @@ -24,7 +28,7 @@ jest.mock('lodash', () => { }; }); -jest.mock('../../../../common/index_controls', () => ({ +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/index_controls', () => ({ firstFieldOption: { text: 'Select a field', value: '', @@ -33,7 +37,9 @@ jest.mock('../../../../common/index_controls', () => ({ getIndexOptions: jest.fn(), })); -const { getIndexOptions } = jest.requireMock('../../../../common/index_controls'); +const { getIndexOptions } = jest.requireMock( + '@kbn/triggers-actions-ui-plugin/public/common/index_controls' +); getIndexOptions.mockResolvedValueOnce([ { @@ -45,7 +51,9 @@ getIndexOptions.mockResolvedValueOnce([ }, ]); -const { getFields } = jest.requireMock('../../../../common/index_controls'); +const { getFields } = jest.requireMock( + '@kbn/triggers-actions-ui-plugin/public/common/index_controls' +); async function setup(actionConnector: any) { const wrapper = mountWithIntl( 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/stack_connectors/public/connector_types/stack/es_index/es_index_connector.tsx similarity index 87% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index_connector.tsx index 12fb79bd2845a..ec090c3c004d1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index_connector.tsx @@ -29,10 +29,14 @@ import { ToggleField, SelectField } from '@kbn/es-ui-shared-plugin/static/forms/ import { DocLinksStart } from '@kbn/core/public'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; -import { ActionConnectorFieldsProps } from '../../../../types'; -import { getTimeFieldOptions } from '../../../../common/lib/get_time_options'; -import { firstFieldOption, getFields, getIndexOptions } from '../../../../common/index_controls'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { + firstFieldOption, + getFields, + getIndexOptions, + getTimeFieldOptions, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; import * as translations from './translations'; interface TimeFieldOptions { @@ -47,13 +51,13 @@ const getIndexConfig = (docLinks: DocLinksStart): FieldConfig => ({ helpText: ( <> @@ -123,7 +127,7 @@ const IndexActionConnectorFields: React.FunctionComponent @@ -159,7 +163,7 @@ const IndexActionConnectorFields: React.FunctionComponent } @@ -168,13 +172,13 @@ const IndexActionConnectorFields: React.FunctionComponent @@ -221,7 +225,7 @@ const IndexActionConnectorFields: React.FunctionComponent {' '} { const original = jest.requireActual(kibanaReactPath); 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/stack_connectors/public/connector_types/stack/es_index/es_index_params.tsx similarity index 84% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index_params.tsx index 0601d0a9b1284..7c6e5bc97cfb1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/es_index_params.tsx @@ -17,16 +17,16 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; import { - ActionParamsProps, AlertHistoryEsIndexConnectorId, AlertHistoryDocumentTemplate, AlertHistoryDefaultIndexName, ALERT_HISTORY_PREFIX, -} from '../../../../types'; -import { IndexActionParams } from '../types'; -import { JsonEditorWithMessageVariables } from '../../json_editor_with_message_variables'; -import { useKibana } from '../../../../common/lib/kibana'; + JsonEditorWithMessageVariables, + useKibana, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { IndexActionParams } from '../../types'; export const IndexParamsFields = ({ actionParams, @@ -90,7 +90,7 @@ export const IndexParamsFields = ({ }; const documentsFieldLabel = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel', + 'xpack.stackConnectors.components.index.documentsFieldLabel', { defaultMessage: 'Document to index', } @@ -108,7 +108,7 @@ export const IndexParamsFields = ({ > @@ -127,17 +127,14 @@ export const IndexParamsFields = ({ (errors.indexOverride as string[]) && errors.indexOverride.length > 0 } - label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndex', - { - defaultMessage: 'Elasticsearch index', - } - )} + label={i18n.translate('xpack.stackConnectors.components.index.preconfiguredIndex', { + defaultMessage: 'Elasticsearch index', + })} labelAppend={resetDefaultIndex} helpText={ <> @@ -146,7 +143,7 @@ export const IndexParamsFields = ({ target="_blank" > @@ -189,18 +186,15 @@ export const IndexParamsFields = ({ : documentToIndex } label={documentsFieldLabel} - aria-label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel', - { - defaultMessage: 'Code editor', - } - )} + aria-label={i18n.translate('xpack.stackConnectors.components.index.jsonDocAriaLabel', { + defaultMessage: 'Code editor', + })} errors={errors.documents as string[]} onDocumentsChange={onDocumentsChange} helpText={ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/index.ts similarity index 77% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/index.ts index 63e1475a115fd..f3c7daa86fbf6 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { getActionType as getCasesWebhookActionType } from './webhook'; +export { getConnectorType as getIndexConnectorType } from './es_index'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/translations.ts similarity index 64% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/translations.ts index d86824fd1813f..3153d84182040 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/es_index/translations.ts @@ -8,49 +8,49 @@ import { i18n } from '@kbn/i18n'; export const INDEX_IS_NOT_VALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.error.notValidIndexText', + 'xpack.stackConnectors.components.index.error.notValidIndexText', { defaultMessage: 'Index is not valid.', } ); export const DOCUMENT_NOT_VALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredDocumentJson', + 'xpack.stackConnectors.components.index.error.requiredDocumentJson', { defaultMessage: 'Document is required and should be a valid JSON object.', } ); export const HISTORY_NOT_VALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideSuffix', + 'xpack.stackConnectors.components.index.error.badIndexOverrideSuffix', { defaultMessage: 'Alert history index must contain valid suffix.', } ); export const EXECUTION_TIME_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.executionTimeFieldLabel', + 'xpack.stackConnectors.components.index.executionTimeFieldLabel', { defaultMessage: 'Time field', } ); export const SHOW_TIME_FIELD_TOGGLE_TOOLTIP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.definedateFieldTooltip', + 'xpack.stackConnectors.components.index.definedateFieldTooltip', { defaultMessage: `Set this time field to the time the document was indexed.`, } ); export const REFRESH_FIELD_TOGGLE_TOOLTIP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshTooltip', + 'xpack.stackConnectors.components.index.refreshTooltip', { defaultMessage: 'Refresh the affected shards to make this operation visible to search.', } ); export const INDEX_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesToQueryLabel', + 'xpack.stackConnectors.components.index.indicesToQueryLabel', { defaultMessage: 'Index', } diff --git a/x-pack/plugins/stack_connectors/public/connector_types/stack/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/index.ts new file mode 100644 index 0000000000000..93d444d20204d --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getEmailConnectorType } from './email'; +export { getIndexConnectorType } from './es_index'; +export { getPagerDutyConnectorType } from './pagerduty'; +export { getServerLogConnectorType } from './server_log'; +export { getSlackConnectorType } from './slack'; +export { getTeamsConnectorType } from './teams'; +export { getWebhookConnectorType } from './webhook'; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/index.ts new file mode 100644 index 0000000000000..48ee4b5288ec8 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getPagerDutyConnectorType } from './pagerduty'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/logo.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/logo.tsx index ab991651a8a52..9383a4cf5d59f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => ( { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); if (getResult !== null) { - actionTypeModel = getResult; + connectorTypeModel = getResult; } }); -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.actionTypeTitle).toEqual('Send to PagerDuty'); +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.actionTypeTitle).toEqual('Send to PagerDuty'); }); }); @@ -43,7 +43,7 @@ describe('pagerduty action params validation', () => { class: 'test class', }; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { dedupKey: [], summary: [], @@ -67,7 +67,7 @@ describe('pagerduty action params validation', () => { const expected = [expect.stringMatching(/^Timestamp must be a valid date/)]; - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ errors: { dedupKey: [], summary: [], diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty.tsx similarity index 71% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty.tsx index 8c3961e6d7116..edb1e9b71b848 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty.tsx @@ -8,17 +8,22 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; import moment from 'moment'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public'; +import { + AlertProvidedActionVariables, + hasMustacheTokens, +} from '@kbn/triggers-actions-ui-plugin/public'; import { PagerDutyConfig, PagerDutySecrets, PagerDutyActionParams, EventActionOptions, -} from '../types'; -import { hasMustacheTokens } from '../../../lib/has_mustache_tokens'; -import { AlertProvidedActionVariables } from '../../../lib/action_variables'; +} from '../../types'; -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< PagerDutyConfig, PagerDutySecrets, PagerDutyActionParams @@ -26,14 +31,11 @@ export function getActionType(): ActionTypeModel< return { id: '.pagerduty', iconClass: lazy(() => import('./logo')), - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.selectMessageText', - { - defaultMessage: 'Send an event in PagerDuty.', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.pagerDuty.selectMessageText', { + defaultMessage: 'Send an event in PagerDuty.', + }), actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.actionTypeTitle', + 'xpack.stackConnectors.components.pagerDuty.connectorTypeTitle', { defaultMessage: 'Send to PagerDuty', } @@ -66,17 +68,14 @@ export function getActionType(): ActionTypeModel< if (!moment(actionParams.timestamp).isValid()) { const { nowShortFormat, nowLongFormat } = getValidTimestampExamples(); errors.timestamp.push( - i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.invalidTimestamp', - { - defaultMessage: - 'Timestamp must be a valid date, such as {nowShortFormat} or {nowLongFormat}.', - values: { - nowShortFormat, - nowLongFormat, - }, - } - ) + i18n.translate('xpack.stackConnectors.components.pagerDuty.error.invalidTimestamp', { + defaultMessage: + 'Timestamp must be a valid date, such as {nowShortFormat} or {nowLongFormat}.', + values: { + nowShortFormat, + nowLongFormat, + }, + }) ); } } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.test.tsx similarity index 97% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.test.tsx index 1ccd7fba702f6..184ae124cbc04 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.test.tsx @@ -9,11 +9,11 @@ import React from 'react'; import { mountWithIntl, nextTick } from '@kbn/test-jest-helpers'; import { act } from 'react-dom/test-utils'; import PagerDutyActionConnectorFields from './pagerduty_connectors'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('PagerDutyActionConnectorFields renders', () => { test('all connector fields is rendered', async () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.tsx similarity index 91% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.tsx index 21f7443b6b545..13139306ea781 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_connectors.tsx @@ -13,8 +13,8 @@ import { FieldConfig, UseField } from '@kbn/es-ui-shared-plugin/static/forms/hoo import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { DocLinksStart } from '@kbn/core/public'; -import { ActionConnectorFieldsProps } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; const { emptyField, urlField } = fieldValidators; @@ -44,7 +44,7 @@ const getRoutingKeyConfig = (docLinks: DocLinksStart): FieldConfig => ({ helpText: ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.test.tsx similarity index 98% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.test.tsx index 19f47166b2726..7f2933587ebca 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; -import { EventActionOptions, SeverityActionOptions } from '../types'; +import { EventActionOptions, SeverityActionOptions } from '../../types'; import PagerDutyParamsFields from './pagerduty_params'; describe('PagerDutyParamsFields renders', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.tsx similarity index 76% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.tsx index 738f1ca74b1a6..f9f9921d84ceb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/pagerduty/pagerduty_params.tsx @@ -9,9 +9,9 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isUndefined } from 'lodash'; -import { ActionParamsProps } from '../../../../types'; -import { PagerDutyActionParams } from '../types'; -import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { TextFieldWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { PagerDutyActionParams } from '../../types'; const PagerDutyParamsFields: React.FunctionComponent> = ({ actionParams, @@ -26,7 +26,7 @@ const PagerDutyParamsFields: React.FunctionComponent { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('logsApp'); + }); +}); + +describe('action params validation', () => { + test('action params validation succeeds when action params is valid', async () => { + const actionParams = { + message: 'test message', + level: 'trace', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { message: [] }, + }); + }); + + test('params validation fails when message is not valid', async () => { + const actionParams = { + message: '', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + message: ['Message is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log.tsx similarity index 63% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log.tsx index 4fe024f8861f0..b1dadf0bf2ddc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log.tsx @@ -7,21 +7,21 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { ServerLogActionParams } from '../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public/types'; +import { ServerLogActionParams } from '../../types'; -export function getActionType(): ActionTypeModel { +export function getConnectorType(): ConnectorTypeModel { return { id: '.server-log', iconClass: 'logsApp', - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.selectMessageText', - { - defaultMessage: 'Add a message to a Kibana log.', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.serverLog.selectMessageText', { + defaultMessage: 'Add a message to a Kibana log.', + }), actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.actionTypeTitle', + 'xpack.stackConnectors.components.serverLog.connectorTypeTitle', { defaultMessage: 'Send to Server log', } @@ -36,7 +36,7 @@ export function getActionType(): ActionTypeModel { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log_params.tsx similarity index 79% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log_params.tsx index b8f5b84eb471e..d923e1165c3f1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/server_log/server_log_params.tsx @@ -8,9 +8,9 @@ import React, { useEffect, useState } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiSelect, EuiFormRow } from '@elastic/eui'; -import { ActionParamsProps } from '../../../../types'; -import { ServerLogActionParams } from '../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { TextAreaWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { ServerLogActionParams } from '../../types'; export const ServerLogParamsFields: React.FunctionComponent< ActionParamsProps @@ -52,12 +52,9 @@ export const ServerLogParamsFields: React.FunctionComponent< diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/index.ts similarity index 78% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/index.ts index ee207a6d8e8a0..05d27afff76fb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/jira/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { getActionType as getJiraActionType } from './jira'; +export { getConnectorType as getSlackConnectorType } from './slack'; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.test.tsx new file mode 100644 index 0000000000000..dc1f27ec3998b --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.test.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; + +const CONNECTOR_TYPE_ID = '.slack'; +let connectorTypeModel: ConnectorTypeModel; + +beforeAll(async () => { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('logoSlack'); + }); +}); + +describe('slack action params validation', () => { + test('if action params validation succeeds when action params is valid', async () => { + const actionParams = { + message: 'message {test}', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { message: [] }, + }); + }); + + test('params validation fails when message is not valid', async () => { + const actionParams = { + message: '', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + message: ['Message is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.tsx similarity index 59% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.tsx index 2252677084ba6..a3a800b2036a8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack.tsx @@ -7,25 +7,22 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { SlackActionParams, SlackSecrets } from '../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public/types'; +import { SlackActionParams, SlackSecrets } from '../../types'; -export function getActionType(): ActionTypeModel { +export function getConnectorType(): ConnectorTypeModel { return { id: '.slack', iconClass: 'logoSlack', - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.slackAction.selectMessageText', - { - defaultMessage: 'Send a message to a Slack channel or user.', - } - ), - actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.slackAction.actionTypeTitle', - { - defaultMessage: 'Send to Slack', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.slack.selectMessageText', { + defaultMessage: 'Send a message to a Slack channel or user.', + }), + actionTypeTitle: i18n.translate('xpack.stackConnectors.components.slack.connectorTypeTitle', { + defaultMessage: 'Send to Slack', + }), validateParams: async ( actionParams: SlackActionParams ): Promise> => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.test.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.test.tsx index 640bef0c22685..ac381ba07e3b0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.test.tsx @@ -9,10 +9,10 @@ import React from 'react'; import { mountWithIntl, nextTick } from '@kbn/test-jest-helpers'; import { act, render } from '@testing-library/react'; import SlackActionFields from './slack_connectors'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('SlackActionFields renders', () => { test('all connector fields is rendered', async () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.tsx similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.tsx index 0725096c5a719..188b8912fc390 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_connectors.tsx @@ -12,9 +12,8 @@ import { FieldConfig, UseField } from '@kbn/es-ui-shared-plugin/static/forms/hoo import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { DocLinksStart } from '@kbn/core/public'; - -import { ActionConnectorFieldsProps } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; const { urlField } = fieldValidators; @@ -24,7 +23,7 @@ const getWebhookUrlConfig = (docLinks: DocLinksStart): FieldConfig => ({ helpText: ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_params.test.tsx similarity index 100% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_params.test.tsx diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_params.tsx similarity index 79% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_params.tsx index 59e10277cfe08..d5cd699caaae5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/slack_params.tsx @@ -7,9 +7,9 @@ import React, { useEffect, useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionParamsProps } from '../../../../types'; -import { SlackActionParams } from '../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { TextAreaWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { SlackActionParams } from '../../types'; const SlackParamsFields: React.FunctionComponent> = ({ actionParams, @@ -43,12 +43,9 @@ const SlackParamsFields: React.FunctionComponent ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/translations.ts similarity index 67% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/slack/translations.ts index e7d37082b53ff..7caed9ca07237 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/slack/translations.ts @@ -8,21 +8,21 @@ import { i18n } from '@kbn/i18n'; export const WEBHOOK_URL_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.slackAction.error.invalidWebhookUrlText', + 'xpack.stackConnectors.components.slack.error.invalidWebhookUrlText', { defaultMessage: 'Webhook URL is invalid.', } ); export const MESSAGE_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSlackMessageText', + 'xpack.stackConnectors.components.slack..error.requiredSlackMessageText', { defaultMessage: 'Message is required.', } ); export const WEBHOOK_URL_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlTextFieldLabel', + 'xpack.stackConnectors.components.slack.webhookUrlTextFieldLabel', { defaultMessage: 'Webhook URL', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/index.ts similarity index 78% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/index.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/index.ts index 2990773856ac4..a64d07770b4dd 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/index.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { getActionType as getSlackActionType } from './slack'; +export { getConnectorType as getTeamsConnectorType } from './teams'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/logo.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/logo.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/logo.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/logo.tsx index 666cb8d854032..a7740ece4323f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/logo.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/logo.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { LogoProps } from '../types'; +import { LogoProps } from '../../types'; const Logo = (props: LogoProps) => ( { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + }); +}); + +describe('teams action params validation', () => { + test('if action params validation succeeds when action params is valid', async () => { + const actionParams = { + message: 'message {test}', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { message: [] }, + }); + }); + + test('params validation fails when message is not valid', async () => { + const actionParams = { + message: '', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + message: ['Message is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams.tsx similarity index 59% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams.tsx index e9c286cdc1b56..560d647253a5f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams.tsx @@ -7,25 +7,22 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { TeamsActionParams, TeamsSecrets } from '../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public/types'; +import { TeamsActionParams, TeamsSecrets } from '../../types'; -export function getActionType(): ActionTypeModel { +export function getConnectorType(): ConnectorTypeModel { return { id: '.teams', iconClass: lazy(() => import('./logo')), - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.selectMessageText', - { - defaultMessage: 'Send a message to a Microsoft Teams channel.', - } - ), - actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.actionTypeTitle', - { - defaultMessage: 'Send a message to a Microsoft Teams channel.', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.teams.selectMessageText', { + defaultMessage: 'Send a message to a Microsoft Teams channel.', + }), + actionTypeTitle: i18n.translate('xpack.stackConnectors.components.teams.connectorTypeTitle', { + defaultMessage: 'Send a message to a Microsoft Teams channel.', + }), validateParams: async ( actionParams: TeamsActionParams ): Promise> => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.test.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.test.tsx index a0a082d36a864..37078d7efd115 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.test.tsx @@ -9,9 +9,9 @@ import React from 'react'; import { mountWithIntl, nextTick } from '@kbn/test-jest-helpers'; import { act, render } from '@testing-library/react'; import TeamsActionFields from './teams_connectors'; -import { ConnectorFormTestProvider } from '../test_utils'; +import { ConnectorFormTestProvider } from '../../lib/test_utils'; import userEvent from '@testing-library/user-event'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('TeamsActionFields renders', () => { test('all connector fields are rendered', async () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.tsx similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.tsx index 34e2e02a0611c..7d989b9b04c6e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_connectors.tsx @@ -12,8 +12,8 @@ import { FieldConfig, UseField } from '@kbn/es-ui-shared-plugin/static/forms/hoo import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { DocLinksStart } from '@kbn/core/public'; -import { ActionConnectorFieldsProps } from '../../../../types'; -import { useKibana } from '../../../../common/lib/kibana'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; const { urlField } = fieldValidators; @@ -23,7 +23,7 @@ const getWebhookUrlConfig = (docLinks: DocLinksStart): FieldConfig => ({ helpText: ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.test.tsx similarity index 93% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.test.tsx index cf0bfe9db0e97..ac1228ac5fda4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import TeamsParamsFields from './teams_params'; -jest.mock('../../../../common/lib/kibana'); +jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); describe('TeamsParamsFields renders', () => { test('all params fields is rendered', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.tsx similarity index 74% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.tsx index 0aea576c10b31..5a4c9e85f583b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/teams_params.tsx @@ -7,9 +7,9 @@ import React, { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionParamsProps } from '../../../../types'; -import { TeamsActionParams } from '../types'; -import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { TextAreaWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { TeamsActionParams } from '../../types'; const TeamsParamsFields: React.FunctionComponent> = ({ actionParams, @@ -34,12 +34,9 @@ const TeamsParamsFields: React.FunctionComponent ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/translations.ts similarity index 67% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/teams/translations.ts index 2bf4cae881f7b..539e0867dc97c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/teams/translations.ts @@ -8,21 +8,21 @@ import { i18n } from '@kbn/i18n'; export const WEBHOOK_URL_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.webhookUrlTextLabel', + 'xpack.stackConnectors.components.teams.error.webhookUrlTextLabel', { defaultMessage: 'Webhook URL', } ); export const WEBHOOK_URL_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.invalidWebhookUrlText', + 'xpack.stackConnectors.components.teams.error.invalidWebhookUrlText', { defaultMessage: 'Webhook URL is invalid.', } ); export const MESSAGE_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.requiredMessageText', + 'xpack.stackConnectors.components.teams.error.requiredMessageText', { defaultMessage: 'Message is required.', } diff --git a/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/index.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/index.ts new file mode 100644 index 0000000000000..dd5934986c846 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { getConnectorType as getWebhookConnectorType } from './webhook'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/translations.ts b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/translations.ts similarity index 55% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/translations.ts rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/translations.ts index 27a7d08b8c767..7095c91729f91 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/translations.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/translations.ts @@ -8,98 +8,98 @@ import { i18n } from '@kbn/i18n'; export const METHOD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.methodTextFieldLabel', + 'xpack.stackConnectors.components.webhook.methodTextFieldLabel', { defaultMessage: 'Method', } ); export const HAS_AUTH_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.hasAuthSwitchLabel', + 'xpack.stackConnectors.components.webhook.hasAuthSwitchLabel', { defaultMessage: 'Require authentication for this webhook', } ); export const URL_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.urlTextFieldLabel', + 'xpack.stackConnectors.components.webhook.urlTextFieldLabel', { defaultMessage: 'URL', } ); export const USERNAME_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.userTextFieldLabel', + 'xpack.stackConnectors.components.webhook.userTextFieldLabel', { defaultMessage: 'Username', } ); export const PASSWORD_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.passwordTextFieldLabel', + 'xpack.stackConnectors.components.webhook.passwordTextFieldLabel', { defaultMessage: 'Password', } ); export const ADD_HEADERS_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.viewHeadersSwitch', + 'xpack.stackConnectors.components.webhook.viewHeadersSwitch', { defaultMessage: 'Add HTTP header', } ); export const HEADER_KEY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerKeyTextFieldLabel', + 'xpack.stackConnectors.components.webhook.headerKeyTextFieldLabel', { defaultMessage: 'Key', } ); export const REMOVE_ITEM_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.removeHeaderIconLabel', + 'xpack.stackConnectors.components.webhook.removeHeaderIconLabel', { defaultMessage: 'Key', } ); export const ADD_HEADER_BTN = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.addHeaderButtonLabel', + 'xpack.stackConnectors.components.webhook.addHeaderButtonLabel', { defaultMessage: 'Add header', } ); export const HEADER_VALUE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerValueTextFieldLabel', + 'xpack.stackConnectors.components.webhook.headerValueTextFieldLabel', { defaultMessage: 'Value', } ); export const URL_INVALID = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.error.invalidUrlTextField', + 'xpack.stackConnectors.components.webhook.error.invalidUrlTextField', { defaultMessage: 'URL is invalid.', } ); export const METHOD_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredMethodText', + 'xpack.stackConnectors.components.webhook.error.requiredMethodText', { defaultMessage: 'Method is required.', } ); export const USERNAME_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredAuthUserNameText', + 'xpack.stackConnectors.components.webhook.error.requiredAuthUserNameText', { defaultMessage: 'Username is required.', } ); export const BODY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookBodyText', + 'xpack.stackConnectors.components.webhook.error.requiredWebhookBodyText', { defaultMessage: 'Body is required.', } diff --git a/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.test.tsx new file mode 100644 index 0000000000000..d24e1e865e17f --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.test.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { TypeRegistry } from '@kbn/triggers-actions-ui-plugin/public/application/type_registry'; +import { registerConnectorTypes } from '../..'; +import type { ActionTypeModel as ConnectorTypeModel } from '@kbn/triggers-actions-ui-plugin/public/types'; +import { registrationServicesMock } from '../../../mocks'; + +const CONNECTOR_TYPE_ID = '.webhook'; +let connectorTypeModel: ConnectorTypeModel; + +beforeAll(() => { + const connectorTypeRegistry = new TypeRegistry(); + registerConnectorTypes({ connectorTypeRegistry, services: registrationServicesMock }); + const getResult = connectorTypeRegistry.get(CONNECTOR_TYPE_ID); + if (getResult !== null) { + connectorTypeModel = getResult; + } +}); + +describe('connectorTypeRegistry.get() works', () => { + test('connector type static data is as expected', () => { + expect(connectorTypeModel.id).toEqual(CONNECTOR_TYPE_ID); + expect(connectorTypeModel.iconClass).toEqual('logoWebhook'); + }); +}); + +describe('webhook action params validation', () => { + test('action params validation succeeds when action params is valid', async () => { + const actionParams = { + body: 'message {test}', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { body: [] }, + }); + }); + + test('params validation fails when body is not valid', async () => { + const actionParams = { + body: '', + }; + + expect(await connectorTypeModel.validateParams(actionParams)).toEqual({ + errors: { + body: ['Body is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.tsx similarity index 67% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.tsx index 5ee08cc027003..9740038f85a66 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook.tsx @@ -7,10 +7,13 @@ import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionTypeModel, GenericValidationResult } from '../../../../types'; -import { WebhookActionParams, WebhookConfig, WebhookSecrets } from '../types'; +import type { + ActionTypeModel as ConnectorTypeModel, + GenericValidationResult, +} from '@kbn/triggers-actions-ui-plugin/public/types'; +import { WebhookActionParams, WebhookConfig, WebhookSecrets } from '../../types'; -export function getActionType(): ActionTypeModel< +export function getConnectorType(): ConnectorTypeModel< WebhookConfig, WebhookSecrets, WebhookActionParams @@ -18,18 +21,12 @@ export function getActionType(): ActionTypeModel< return { id: '.webhook', iconClass: 'logoWebhook', - selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.selectMessageText', - { - defaultMessage: 'Send a request to a web service.', - } - ), - actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.actionTypeTitle', - { - defaultMessage: 'Webhook data', - } - ), + selectMessage: i18n.translate('xpack.stackConnectors.components.webhook.selectMessageText', { + defaultMessage: 'Send a request to a web service.', + }), + actionTypeTitle: i18n.translate('xpack.stackConnectors.components.webhook.connectorTypeTitle', { + defaultMessage: 'Webhook data', + }), validateParams: async ( actionParams: WebhookActionParams ): Promise> => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.test.tsx similarity index 99% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.test.tsx index d3b933e9e2dc4..8744f126e1541 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import WebhookActionConnectorFields from './webhook_connectors'; -import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../test_utils'; +import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../../lib/test_utils'; import { act, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.tsx similarity index 96% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.tsx index 7981f8fa4fa78..233d2eea4b117 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_connectors.tsx @@ -29,9 +29,9 @@ import { ToggleField, } from '@kbn/es-ui-shared-plugin/static/forms/components'; import { fieldValidators } from '@kbn/es-ui-shared-plugin/static/forms/helpers'; -import { ActionConnectorFieldsProps } from '../../../../types'; +import type { ActionConnectorFieldsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { PasswordField } from '@kbn/triggers-actions-ui-plugin/public'; import * as i18n from './translations'; -import { PasswordField } from '../../password_field'; const HTTP_VERBS = ['post', 'put']; const { emptyField, urlField } = fieldValidators; @@ -99,7 +99,7 @@ const WebhookActionConnectorFields: React.FunctionComponent

    diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.test.tsx similarity index 88% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.test.tsx index 064d21b50e463..6cf29adfe89bf 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.test.tsx @@ -8,9 +8,9 @@ import React from 'react'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import WebhookParamsFields from './webhook_params'; -import { MockCodeEditor } from '../../../code_editor.mock'; +import { MockCodeEditor } from '@kbn/triggers-actions-ui-plugin/public/application/code_editor.mock'; -const kibanaReactPath = '../../../../../../../../src/plugins/kibana_react/public'; +const kibanaReactPath = '../../../../../../../src/plugins/kibana_react/public'; jest.mock(kibanaReactPath, () => { const original = jest.requireActual(kibanaReactPath); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.tsx similarity index 69% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.tsx rename to x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.tsx index 2eab79b14f53a..4a48027e8153a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/stack/webhook/webhook_params.tsx @@ -7,9 +7,9 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionParamsProps } from '../../../../types'; -import { WebhookActionParams } from '../types'; -import { JsonEditorWithMessageVariables } from '../../json_editor_with_message_variables'; +import type { ActionParamsProps } from '@kbn/triggers-actions-ui-plugin/public'; +import { JsonEditorWithMessageVariables } from '@kbn/triggers-actions-ui-plugin/public'; +import { WebhookActionParams } from '../../types'; const WebhookParamsFields: React.FunctionComponent> = ({ actionParams, @@ -24,14 +24,11 @@ const WebhookParamsFields: React.FunctionComponent new StackConnectorsPublicPlugin(); diff --git a/x-pack/plugins/stack_connectors/public/mocks.ts b/x-pack/plugins/stack_connectors/public/mocks.ts new file mode 100644 index 0000000000000..9e087c3cee6eb --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/mocks.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ValidatedEmail } from '@kbn/actions-plugin/common'; +import { RegistrationServices } from './connector_types'; + +function validateEmailAddresses(addresses: string[]): ValidatedEmail[] { + return addresses.map((address) => ({ address, valid: true })); +} + +export const registrationServicesMock: RegistrationServices = { validateEmailAddresses }; diff --git a/x-pack/plugins/stack_connectors/public/plugin.ts b/x-pack/plugins/stack_connectors/public/plugin.ts new file mode 100644 index 0000000000000..bc9d855a14303 --- /dev/null +++ b/x-pack/plugins/stack_connectors/public/plugin.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { CoreSetup, Plugin } from '@kbn/core/public'; +import { TriggersAndActionsUIPublicPluginSetup } from '@kbn/triggers-actions-ui-plugin/public'; +import { ActionsPublicPluginSetup } from '@kbn/actions-plugin/public'; +import { registerConnectorTypes } from './connector_types'; + +export type Setup = void; +export type Start = void; + +export interface StackConnectorsPublicSetupDeps { + triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; + actions: ActionsPublicPluginSetup; +} + +export class StackConnectorsPublicPlugin + implements Plugin +{ + public setup(core: CoreSetup, { triggersActionsUi, actions }: StackConnectorsPublicSetupDeps) { + registerConnectorTypes({ + connectorTypeRegistry: triggersActionsUi.actionTypeRegistry, + services: { + validateEmailAddresses: actions.validateEmailAddresses, + }, + }); + } + + public start() {} + public stop() {} +} diff --git a/x-pack/plugins/stack_connectors/tsconfig.json b/x-pack/plugins/stack_connectors/tsconfig.json index 395dc5a65be86..1cf8281670d0a 100644 --- a/x-pack/plugins/stack_connectors/tsconfig.json +++ b/x-pack/plugins/stack_connectors/tsconfig.json @@ -10,10 +10,12 @@ "server/**/*", // have to declare *.json explicitly due to https://github.com/microsoft/TypeScript/issues/25636 "server/**/*.json", - "common/**/*" + "common/**/*", + "public/**/*" ], "references": [ { "path": "../../../src/core/tsconfig.json" }, - { "path": "../actions/tsconfig.json" } + { "path": "../actions/tsconfig.json" }, + { "path": "../triggers_actions_ui/tsconfig.json" } ] } diff --git a/x-pack/plugins/synthetics/common/runtime_types/monitor_management/monitor_types_project.ts b/x-pack/plugins/synthetics/common/runtime_types/monitor_management/monitor_types_project.ts index 6abcf4b832135..cba2f506189e6 100644 --- a/x-pack/plugins/synthetics/common/runtime_types/monitor_management/monitor_types_project.ts +++ b/x-pack/plugins/synthetics/common/runtime_types/monitor_management/monitor_types_project.ts @@ -30,7 +30,6 @@ export const ProjectMonitorCodec = t.intersection([ screenshot: ScreenshotOptionCodec, tags: t.union([t.string, t.array(t.string)]), ignoreHTTPSErrors: t.boolean, - apmServiceName: t.string, playwrightOptions: t.record(t.string, t.unknown), filter: t.interface({ match: t.string, diff --git a/x-pack/plugins/synthetics/e2e/journeys/data_view_permissions.ts b/x-pack/plugins/synthetics/e2e/journeys/data_view_permissions.ts index aa29b92b7ea25..e5714234de690 100644 --- a/x-pack/plugins/synthetics/e2e/journeys/data_view_permissions.ts +++ b/x-pack/plugins/synthetics/e2e/journeys/data_view_permissions.ts @@ -6,7 +6,7 @@ */ import { journey, step, expect, before } from '@elastic/synthetics'; -import { callKibana } from '@kbn/apm-plugin/scripts/create_apm_users/helpers/call_kibana'; +import { callKibana } from '@kbn/apm-plugin/server/test_helpers/create_apm_users/helpers/call_kibana'; import { byTestId, waitForLoadingToFinish } from '@kbn/observability-plugin/e2e/utils'; import { loginPageProvider } from '../page_objects/login'; diff --git a/x-pack/plugins/synthetics/e2e/journeys/monitor_management.journey.ts b/x-pack/plugins/synthetics/e2e/journeys/monitor_management.journey.ts index 2b0aeca66f068..c3b325183b05a 100644 --- a/x-pack/plugins/synthetics/e2e/journeys/monitor_management.journey.ts +++ b/x-pack/plugins/synthetics/e2e/journeys/monitor_management.journey.ts @@ -225,3 +225,72 @@ journey('Monitor Management breadcrumbs', async ({ page, params }: { page: Page; expect(isSuccessful).toBeTruthy(); }); }); + +journey( + 'MonitorManagement-case-insensitive sort', + async ({ page, params }: { page: Page; params: any }) => { + const uptime = monitorManagementPageProvider({ page, kibanaUrl: params.kibanaUrl }); + + const sortedMonitors = [ + Object.assign({}, configuration[DataStream.ICMP].monitorConfig, { + name: `A ${uuid.v4()}`, + }), + Object.assign({}, configuration[DataStream.ICMP].monitorConfig, { + name: `B ${uuid.v4()}`, + }), + Object.assign({}, configuration[DataStream.ICMP].monitorConfig, { + name: `aa ${uuid.v4()}`, + }), + ]; + + before(async () => { + await uptime.waitForLoadingToFinish(); + }); + + after(async () => { + await uptime.navigateToMonitorManagement(); + await uptime.deleteMonitors(); + await uptime.enableMonitorManagement(false); + }); + + step('Go to monitor-management', async () => { + await uptime.navigateToMonitorManagement(); + }); + + step('login to Kibana', async () => { + await uptime.loginToKibana(); + const invalid = await page.locator( + `text=Username or password is incorrect. Please try again.` + ); + expect(await invalid.isVisible()).toBeFalsy(); + }); + + for (const monitorConfig of sortedMonitors) { + step(`create monitor ${monitorConfig.name}`, async () => { + await uptime.enableMonitorManagement(); + await uptime.clickAddMonitor(); + await uptime.createMonitor({ monitorConfig, monitorType: DataStream.ICMP }); + const isSuccessful = await uptime.confirmAndSave(); + expect(isSuccessful).toBeTruthy(); + }); + } + + step(`list monitors in Monitor Management UI`, async () => { + await uptime.navigateToMonitorManagement(); + await Promise.all( + sortedMonitors.map((monitor) => + page.waitForSelector(`text=${monitor.name}`, { timeout: 160 * 1000 }) + ) + ); + + // Get first cell value from monitor table -> monitor name + const rows = page.locator('tbody tr td:first-child div.euiTableCellContent'); + expect(await rows.count()).toEqual(sortedMonitors.length); + + const expectedSort = sortedMonitors + .map((mn) => mn.name) + .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); + expect(await rows.allTextContents()).toEqual(expectedSort); + }); + } +); diff --git a/x-pack/plugins/synthetics/server/legacy_uptime/lib/saved_objects/synthetics_monitor.ts b/x-pack/plugins/synthetics/server/legacy_uptime/lib/saved_objects/synthetics_monitor.ts index 61d0694d7cfa6..52be898373ef2 100644 --- a/x-pack/plugins/synthetics/server/legacy_uptime/lib/saved_objects/synthetics_monitor.ts +++ b/x-pack/plugins/synthetics/server/legacy_uptime/lib/saved_objects/synthetics_monitor.ts @@ -23,6 +23,7 @@ export const syntheticsMonitor: SavedObjectsType = { keyword: { type: 'keyword', ignore_above: 256, + normalizer: 'lowercase', }, }, }, diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.test.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.test.ts index ed02f1037e32b..9b32b61a59b35 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.test.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.test.ts @@ -67,9 +67,7 @@ describe('browser normalizers', () => { locations: ['us_central'], tags: ['tag1', 'tag2'], ignoreHTTPSErrors: true, - apmServiceName: 'cart-service', - type: DataStream.BROWSER, - }, + } as ProjectMonitor, // test that normalizers defaults to browser when type is omitted { id: 'test-id-2', screenshot: ScreenshotOption.ON, @@ -86,7 +84,6 @@ describe('browser normalizers', () => { locations: ['us_central', 'us_east'], tags: ['tag3', 'tag4'], ignoreHTTPSErrors: false, - apmServiceName: 'bean-service', type: DataStream.BROWSER, }, { @@ -106,7 +103,6 @@ describe('browser normalizers', () => { privateLocations: ['Germany'], tags: ['tag3', 'tag4'], ignoreHTTPSErrors: false, - apmServiceName: 'bean-service', type: DataStream.BROWSER, }, ]; @@ -118,6 +114,7 @@ describe('browser normalizers', () => { monitors, projectId, namespace: 'test-space', + version: '8.5.0', }); expect(actual).toEqual([ { @@ -145,7 +142,7 @@ describe('browser normalizers', () => { unit: 'm', }, screenshots: 'off', - 'service.name': 'cart-service', + 'service.name': '', 'source.project.content': 'test content 1', tags: ['tag1', 'tag2'], 'throttling.config': '5d/10u/20l', @@ -162,6 +159,7 @@ describe('browser normalizers', () => { timeout: null, }, unsupportedKeys: [], + errors: [], }, { normalizedFields: { @@ -201,7 +199,7 @@ describe('browser normalizers', () => { unit: 'm', }, screenshots: 'on', - 'service.name': 'bean-service', + 'service.name': '', 'source.project.content': 'test content 2', tags: ['tag3', 'tag4'], 'throttling.config': '10d/15u/18l', @@ -217,6 +215,7 @@ describe('browser normalizers', () => { timeout: null, }, unsupportedKeys: [], + errors: [], }, { normalizedFields: { @@ -263,7 +262,7 @@ describe('browser normalizers', () => { unit: 'm', }, screenshots: 'on', - 'service.name': 'bean-service', + 'service.name': '', 'source.project.content': 'test content 3', tags: ['tag3', 'tag4'], 'throttling.config': '10d/15u/18l', @@ -279,6 +278,7 @@ describe('browser normalizers', () => { timeout: null, }, unsupportedKeys: [], + errors: [], }, ]); }); diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.ts index aae7031435c74..8eba2cd2651db 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/browser_monitor.ts @@ -10,20 +10,14 @@ import { ConfigKey, DataStream, FormMonitorType, - Locations, - PrivateLocation, - ProjectMonitor, } from '../../../../common/runtime_types'; -import { getNormalizeCommonFields, getValueInSeconds } from './common_fields'; import { DEFAULT_FIELDS } from '../../../../common/constants/monitor_defaults'; - -export interface NormalizedProjectProps { - locations: Locations; - privateLocations: PrivateLocation[]; - monitor: ProjectMonitor; - projectId: string; - namespace: string; -} +import { + NormalizedProjectProps, + NormalizerResult, + getNormalizeCommonFields, + getValueInSeconds, +} from './common_fields'; export const getNormalizeBrowserFields = ({ locations = [], @@ -31,7 +25,8 @@ export const getNormalizeBrowserFields = ({ monitor, projectId, namespace, -}: NormalizedProjectProps): { normalizedFields: BrowserFields; unsupportedKeys: string[] } => { + version, +}: NormalizedProjectProps): NormalizerResult => { const defaultFields = DEFAULT_FIELDS[DataStream.BROWSER]; const commonFields = getNormalizeCommonFields({ @@ -40,6 +35,7 @@ export const getNormalizeBrowserFields = ({ monitor, projectId, namespace, + version, }); const normalizedFields = { @@ -81,5 +77,6 @@ export const getNormalizeBrowserFields = ({ ...normalizedFields, }, unsupportedKeys: [], + errors: [], }; }; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.test.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.test.ts new file mode 100644 index 0000000000000..fee6f0ca2637c --- /dev/null +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.test.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { flattenAndFormatObject } from './common_fields'; + +describe('normalizeYamlConfig', () => { + it('does not continue flattening when encountering an array', () => { + const array = ['value1', 'value2']; + const supportedKeys: string[] = []; + const nestedObject = { + a: { + nested: { + key: array, + }, + }, + }; + expect(flattenAndFormatObject(nestedObject, '', supportedKeys)).toEqual({ + 'a.nested.key': array, + }); + }); + + it('does not continue flattening when encountering a supported key', () => { + const supportedKeys: string[] = ['a.supported.key']; + const object = { + with: { + further: { + nesting: '', + }, + }, + }; + const nestedObject = { + a: { + supported: { + key: object, + }, + }, + }; + expect(flattenAndFormatObject(nestedObject, '', supportedKeys)).toEqual({ + 'a.supported.key': object, + }); + }); + + it('flattens objects', () => { + const supportedKeys: string[] = []; + const nestedObject = { + a: { + nested: { + key: 'value1', + }, + }, + b: { + nested: { + key: 'value2', + }, + }, + }; + expect(flattenAndFormatObject(nestedObject, '', supportedKeys)).toEqual({ + 'a.nested.key': 'value1', + 'b.nested.key': 'value2', + }); + }); +}); diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.ts index 31aebd0e8586e..56045712606a1 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/common_fields.ts @@ -20,7 +20,27 @@ import { } from '../../../../common/runtime_types'; import { DEFAULT_FIELDS } from '../../../../common/constants/monitor_defaults'; import { DEFAULT_COMMON_FIELDS } from '../../../../common/constants/monitor_defaults'; -import { NormalizedProjectProps } from '.'; + +export interface NormalizedProjectProps { + locations: Locations; + privateLocations: PrivateLocation[]; + monitor: ProjectMonitor; + projectId: string; + namespace: string; + version: string; +} + +export interface Error { + id: string; + reason: string; + details: string; +} + +export interface NormalizerResult { + normalizedFields: MonitorTypeFields; + unsupportedKeys: string[]; + errors: Error[]; +} export const getNormalizeCommonFields = ({ locations = [], @@ -28,7 +48,7 @@ export const getNormalizeCommonFields = ({ monitor, projectId, namespace, -}: NormalizedProjectProps): CommonFields => { +}: NormalizedProjectProps): Partial => { const defaultFields = DEFAULT_COMMON_FIELDS; const normalizedFields = { @@ -45,18 +65,16 @@ export const getNormalizeCommonFields = ({ privateLocations, publicLocations: locations, }), - [ConfigKey.APM_SERVICE_NAME]: - monitor.apmServiceName || defaultFields[ConfigKey.APM_SERVICE_NAME], [ConfigKey.TAGS]: getOptionalListField(monitor.tags) || defaultFields[ConfigKey.TAGS], [ConfigKey.NAMESPACE]: formatKibanaNamespace(namespace) || defaultFields[ConfigKey.NAMESPACE], [ConfigKey.ORIGINAL_SPACE]: namespace || defaultFields[ConfigKey.NAMESPACE], [ConfigKey.CUSTOM_HEARTBEAT_ID]: getCustomHeartbeatId(monitor, projectId, namespace), [ConfigKey.ENABLED]: monitor.enabled ?? defaultFields[ConfigKey.ENABLED], + [ConfigKey.TIMEOUT]: monitor.timeout + ? getValueInSeconds(monitor.timeout) + : defaultFields[ConfigKey.TIMEOUT], }; - return { - ...defaultFields, - ...normalizedFields, - }; + return normalizedFields; }; export const getCustomHeartbeatId = ( @@ -94,6 +112,35 @@ export const getMonitorLocations = ({ ) as BrowserFields[ConfigKey.LOCATIONS]; }; +export const getUnsupportedKeysError = ( + monitor: ProjectMonitor, + unsupportedKeys: string[], + version: string +) => ({ + id: monitor.id, + reason: 'Unsupported Heartbeat option', + details: `The following Heartbeat options are not supported for ${ + monitor.type + } project monitors in ${version}: ${unsupportedKeys.join( + '|' + )}. You monitor was not created or updated.`, +}); + +export const getMultipleUrlsOrHostsError = ( + monitor: ProjectMonitor, + key: 'hosts' | 'urls', + version: string +) => ({ + id: monitor.id, + reason: 'Unsupported Heartbeat option', + details: `Multiple ${key} are not supported for ${ + monitor.type + } project monitors in ${version}. Please set only 1 ${key.slice( + 0, + -1 + )} per monitor. You monitor was not created or updated.`, +}); + export const getValueInSeconds = (value: string) => { const keyMap = { h: 60 * 60, @@ -136,7 +183,7 @@ export const getOptionalArrayField = (value: string[] | string = '') => { * @param {Object} [monitor] * @returns {Object} Returns an object containing synthetics-compatible configuration keys */ -const flattenAndFormatObject = (obj: Record, prefix = '', keys: string[]) => +export const flattenAndFormatObject = (obj: Record, prefix = '', keys: string[]) => Object.keys(obj).reduce>((acc, k) => { const pre = prefix.length ? prefix + '.' : ''; const key = pre + k; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.test.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.test.ts new file mode 100644 index 0000000000000..922c5ca6dab05 --- /dev/null +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.test.ts @@ -0,0 +1,242 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Locations, LocationStatus, PrivateLocation } from '../../../../common/runtime_types'; +import { normalizeProjectMonitors } from '.'; + +describe('http normalizers', () => { + describe('normalize push monitors', () => { + const projectId = 'test-project-id'; + const locations: Locations = [ + { + id: 'us_central', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + { + id: 'us_east', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + ]; + const privateLocations: PrivateLocation[] = [ + { + id: 'germany', + label: 'Germany', + isServiceManaged: false, + concurrentMonitors: 1, + agentPolicyId: 'germany', + }, + ]; + const monitors = [ + { + locations: ['localhost'], + type: 'http', + enabled: false, + id: 'my-monitor-2', + name: 'My Monitor 2', + urls: ['http://localhost:9200', 'http://anotherurl:9200'], + schedule: 60, + timeout: '80s', + 'check.request': { + method: 'POST', + body: { + json: 'body', + }, + headers: { + 'a-header': 'a-header-value', + }, + }, + response: { + include_body: 'always', + }, + 'response.include_headers': false, + 'check.response': { + status: [200], + body: ['Saved', 'saved'], + }, + unsupportedKey: { + nestedUnsupportedKey: 'unsupportedValue', + }, + service: { + name: 'test service', + }, + ssl: { + supported_protocols: ['TLSv1.2', 'TLSv1.3'], + }, + }, + { + locations: ['localhost'], + type: 'http', + enabled: false, + id: 'my-monitor-3', + name: 'My Monitor 3', + urls: ['http://localhost:9200'], + schedule: 60, + timeout: '80s', + 'check.request': { + method: 'POST', + body: 'sometextbody', + headers: { + 'a-header': 'a-header-value', + }, + }, + response: { + include_body: 'always', + }, + tags: 'tag2,tag2', + 'response.include_headers': false, + 'check.response': { + status: [200], + body: { + positive: ['Saved', 'saved'], + }, + }, + 'service.name': 'test service', + 'ssl.supported_protocols': 'TLSv1.2,TLSv1.3', + }, + ]; + + it('properly normalizes http monitors', () => { + const actual = normalizeProjectMonitors({ + locations, + privateLocations, + monitors, + projectId, + namespace: 'test-space', + version: '8.5.0', + }); + expect(actual).toEqual([ + { + errors: [ + { + details: + 'Multiple urls are not supported for http project monitors in 8.5.0. Please set only 1 url per monitor. You monitor was not created or updated.', + id: 'my-monitor-2', + reason: 'Unsupported Heartbeat option', + }, + { + details: + 'The following Heartbeat options are not supported for http project monitors in 8.5.0: check.response.body|unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.', + id: 'my-monitor-2', + reason: 'Unsupported Heartbeat option', + }, + ], + normalizedFields: { + __ui: { + is_tls_enabled: false, + }, + 'check.request.body': { + type: 'json', + value: '{"json":"body"}', + }, + 'check.request.headers': { + 'a-header': 'a-header-value', + }, + 'check.request.method': 'POST', + 'check.response.body.negative': [], + 'check.response.body.positive': [], + 'check.response.headers': {}, + 'check.response.status': ['200'], + config_id: '', + custom_heartbeat_id: 'my-monitor-2-test-project-id-test-space', + enabled: false, + form_monitor_type: 'http', + journey_id: 'my-monitor-2', + locations: [], + max_redirects: '0', + name: 'My Monitor 2', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + password: '', + project_id: 'test-project-id', + proxy_url: '', + 'response.include_body': 'always', + 'response.include_headers': false, + schedule: { + number: '60', + unit: 'm', + }, + 'service.name': 'test service', + 'ssl.certificate': '', + 'ssl.certificate_authorities': '', + 'ssl.key': '', + 'ssl.key_passphrase': '', + 'ssl.supported_protocols': ['TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + tags: [], + timeout: '80', + type: 'http', + urls: 'http://localhost:9200', + username: '', + }, + unsupportedKeys: ['check.response.body', 'unsupportedKey.nestedUnsupportedKey'], + }, + { + errors: [], + normalizedFields: { + __ui: { + is_tls_enabled: false, + }, + 'check.request.body': { + type: 'text', + value: 'sometextbody', + }, + 'check.request.headers': { + 'a-header': 'a-header-value', + }, + 'check.request.method': 'POST', + 'check.response.body.negative': [], + 'check.response.body.positive': ['Saved', 'saved'], + 'check.response.headers': {}, + 'check.response.status': ['200'], + config_id: '', + custom_heartbeat_id: 'my-monitor-3-test-project-id-test-space', + enabled: false, + form_monitor_type: 'http', + journey_id: 'my-monitor-3', + locations: [], + max_redirects: '0', + name: 'My Monitor 3', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + password: '', + project_id: 'test-project-id', + proxy_url: '', + 'response.include_body': 'always', + 'response.include_headers': false, + schedule: { + number: '60', + unit: 'm', + }, + 'service.name': 'test service', + 'ssl.certificate': '', + 'ssl.certificate_authorities': '', + 'ssl.key': '', + 'ssl.key_passphrase': '', + 'ssl.supported_protocols': ['TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + tags: ['tag2', 'tag2'], + timeout: '80', + type: 'http', + urls: 'http://localhost:9200', + username: '', + }, + unsupportedKeys: [], + }, + ]); + }); + }); +}); diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.ts index 6f637d818667a..d994e61517822 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/http_monitor.ts @@ -4,16 +4,26 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { getNormalizeCommonFields } from './common_fields'; -import { NormalizedProjectProps } from './browser_monitor'; +import { get } from 'lodash'; import { DEFAULT_FIELDS } from '../../../../common/constants/monitor_defaults'; import { ConfigKey, DataStream, FormMonitorType, HTTPFields, + Mode, + TLSVersion, } from '../../../../common/runtime_types/monitor_management'; -import { normalizeYamlConfig, getValueInSeconds, getOptionalArrayField } from './common_fields'; +import { + NormalizedProjectProps, + NormalizerResult, + getNormalizeCommonFields, + normalizeYamlConfig, + getOptionalListField, + getOptionalArrayField, + getUnsupportedKeysError, + getMultipleUrlsOrHostsError, +} from './common_fields'; export const getNormalizeHTTPFields = ({ locations = [], @@ -21,18 +31,30 @@ export const getNormalizeHTTPFields = ({ monitor, projectId, namespace, -}: NormalizedProjectProps): { normalizedFields: HTTPFields; unsupportedKeys: string[] } => { + version, +}: NormalizedProjectProps): NormalizerResult => { const defaultFields = DEFAULT_FIELDS[DataStream.HTTP]; + const errors = []; const { yamlConfig, unsupportedKeys } = normalizeYamlConfig(monitor); - const commonFields = getNormalizeCommonFields({ locations, privateLocations, monitor, projectId, namespace, + version, }); + /* Check if monitor has multiple urls */ + const urls = getOptionalListField(monitor.urls); + if (urls.length > 1) { + errors.push(getMultipleUrlsOrHostsError(monitor, 'urls', version)); + } + + if (unsupportedKeys.length) { + errors.push(getUnsupportedKeysError(monitor, unsupportedKeys, version)); + } + const normalizedFields = { ...yamlConfig, ...commonFields, @@ -41,9 +63,13 @@ export const getNormalizeHTTPFields = ({ [ConfigKey.URLS]: getOptionalArrayField(monitor.urls) || defaultFields[ConfigKey.URLS], [ConfigKey.MAX_REDIRECTS]: monitor[ConfigKey.MAX_REDIRECTS] || defaultFields[ConfigKey.MAX_REDIRECTS], - [ConfigKey.TIMEOUT]: monitor.timeout - ? getValueInSeconds(monitor.timeout) - : defaultFields[ConfigKey.TIMEOUT], + [ConfigKey.REQUEST_BODY_CHECK]: getRequestBodyField( + (yamlConfig as Record)[ConfigKey.REQUEST_BODY_CHECK] as string, + defaultFields[ConfigKey.REQUEST_BODY_CHECK] + ), + [ConfigKey.TLS_VERSION]: get(monitor, ConfigKey.TLS_VERSION) + ? (getOptionalListField(get(monitor, ConfigKey.TLS_VERSION)) as TLSVersion[]) + : defaultFields[ConfigKey.TLS_VERSION], }; return { normalizedFields: { @@ -51,5 +77,26 @@ export const getNormalizeHTTPFields = ({ ...normalizedFields, }, unsupportedKeys, + errors, + }; +}; + +export const getRequestBodyField = ( + value: string, + defaultValue: HTTPFields[ConfigKey.REQUEST_BODY_CHECK] +): HTTPFields[ConfigKey.REQUEST_BODY_CHECK] => { + let parsedValue: string; + let type: Mode; + + if (typeof value === 'object') { + parsedValue = JSON.stringify(value); + type = Mode.JSON; + } else { + parsedValue = value; + type = Mode.PLAINTEXT; + } + return { + type, + value: parsedValue || defaultValue.value, }; }; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.test.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.test.ts new file mode 100644 index 0000000000000..e32ddf4f328a1 --- /dev/null +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.test.ts @@ -0,0 +1,227 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Locations, LocationStatus, PrivateLocation } from '../../../../common/runtime_types'; +import { normalizeProjectMonitors } from '.'; + +describe('http normalizers', () => { + describe('normalize push monitors', () => { + const projectId = 'test-project-id'; + const locations: Locations = [ + { + id: 'us_central', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + { + id: 'us_east', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + ]; + const privateLocations: PrivateLocation[] = [ + { + id: 'germany', + label: 'Germany', + isServiceManaged: false, + concurrentMonitors: 1, + agentPolicyId: 'germany', + }, + ]; + const monitors = [ + { + locations: ['us_central'], + type: 'icmp', + id: 'Cloudflare-DNS', + name: 'Cloudflare DNS', + hosts: ['1.1.1.1'], + schedule: 1, + tags: ['service:smtp', 'org:google'], + privateLocations: ['Test private location 0'], + timeout: '1m', + wait: '30s', + 'service.name': 'test service', + }, + { + locations: ['us_central'], + type: 'icmp', + id: 'Cloudflare-DNS-2', + name: 'Cloudflare DNS 2', + hosts: '1.1.1.1', + schedule: 1, + tags: 'tag1,tag2', + privateLocations: ['Test private location 0'], + wait: '1m', + service: { + name: 'test service', + }, + }, + { + locations: ['us_central'], + type: 'icmp', + id: 'Cloudflare-DNS-3', + name: 'Cloudflare DNS 3', + hosts: '1.1.1.1,2.2.2.2', + schedule: 1, + tags: 'tag1,tag2', + privateLocations: ['Test private location 0'], + unsupportedKey: { + nestedUnsupportedKey: 'unnsuportedValue', + }, + }, + ]; + + it('properly normalizes http monitors', () => { + const actual = normalizeProjectMonitors({ + locations, + privateLocations, + monitors, + projectId, + namespace: 'test-space', + version: '8.5.0', + }); + expect(actual).toEqual([ + { + errors: [], + normalizedFields: { + config_id: '', + custom_heartbeat_id: 'Cloudflare-DNS-test-project-id-test-space', + enabled: true, + form_monitor_type: 'icmp', + hosts: '1.1.1.1', + journey_id: 'Cloudflare-DNS', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'Cloudflare DNS', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': 'test service', + tags: ['service:smtp', 'org:google'], + timeout: '60', + type: 'icmp', + wait: '30', + }, + unsupportedKeys: [], + }, + { + errors: [], + normalizedFields: { + config_id: '', + custom_heartbeat_id: 'Cloudflare-DNS-2-test-project-id-test-space', + enabled: true, + form_monitor_type: 'icmp', + hosts: '1.1.1.1', + journey_id: 'Cloudflare-DNS-2', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'Cloudflare DNS 2', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': 'test service', + tags: ['tag1', 'tag2'], + timeout: '16', + type: 'icmp', + wait: '60', + }, + unsupportedKeys: [], + }, + { + errors: [ + { + details: + 'Multiple hosts are not supported for icmp project monitors in 8.5.0. Please set only 1 host per monitor. You monitor was not created or updated.', + id: 'Cloudflare-DNS-3', + reason: 'Unsupported Heartbeat option', + }, + { + details: + 'The following Heartbeat options are not supported for icmp project monitors in 8.5.0: unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.', + id: 'Cloudflare-DNS-3', + reason: 'Unsupported Heartbeat option', + }, + ], + normalizedFields: { + config_id: '', + custom_heartbeat_id: 'Cloudflare-DNS-3-test-project-id-test-space', + enabled: true, + form_monitor_type: 'icmp', + hosts: '1.1.1.1', + journey_id: 'Cloudflare-DNS-3', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'Cloudflare DNS 3', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': '', + tags: ['tag1', 'tag2'], + timeout: '16', + type: 'icmp', + wait: '1', + }, + unsupportedKeys: ['unsupportedKey.nestedUnsupportedKey'], + }, + ]); + }); + }); +}); diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.ts index 282475f94d7cd..ea4eb7dbdba84 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/icmp_monitor.ts @@ -5,8 +5,6 @@ * 2.0. */ -import { getNormalizeCommonFields } from './common_fields'; -import { NormalizedProjectProps } from './browser_monitor'; import { DEFAULT_FIELDS } from '../../../../common/constants/monitor_defaults'; import { ConfigKey, @@ -14,7 +12,17 @@ import { FormMonitorType, ICMPFields, } from '../../../../common/runtime_types/monitor_management'; -import { normalizeYamlConfig, getValueInSeconds, getOptionalArrayField } from './common_fields'; +import { + NormalizerResult, + NormalizedProjectProps, + normalizeYamlConfig, + getNormalizeCommonFields, + getValueInSeconds, + getOptionalArrayField, + getOptionalListField, + getMultipleUrlsOrHostsError, + getUnsupportedKeysError, +} from './common_fields'; export const getNormalizeICMPFields = ({ locations = [], @@ -22,8 +30,10 @@ export const getNormalizeICMPFields = ({ monitor, projectId, namespace, -}: NormalizedProjectProps): { normalizedFields: ICMPFields; unsupportedKeys: string[] } => { + version, +}: NormalizedProjectProps): NormalizerResult => { const defaultFields = DEFAULT_FIELDS[DataStream.ICMP]; + const errors = []; const { yamlConfig, unsupportedKeys } = normalizeYamlConfig(monitor); const commonFields = getNormalizeCommonFields({ @@ -32,8 +42,19 @@ export const getNormalizeICMPFields = ({ monitor, projectId, namespace, + version, }); + /* Check if monitor has multiple hosts */ + const hosts = getOptionalListField(monitor.hosts); + if (hosts.length > 1) { + errors.push(getMultipleUrlsOrHostsError(monitor, 'hosts', version)); + } + + if (unsupportedKeys.length) { + errors.push(getUnsupportedKeysError(monitor, unsupportedKeys, version)); + } + const normalizedFields = { ...yamlConfig, ...commonFields, @@ -41,9 +62,6 @@ export const getNormalizeICMPFields = ({ [ConfigKey.FORM_MONITOR_TYPE]: FormMonitorType.ICMP, [ConfigKey.HOSTS]: getOptionalArrayField(monitor[ConfigKey.HOSTS]) || defaultFields[ConfigKey.HOSTS], - [ConfigKey.TIMEOUT]: monitor.timeout - ? getValueInSeconds(monitor.timeout) - : defaultFields[ConfigKey.TIMEOUT], [ConfigKey.WAIT]: monitor.wait ? getValueInSeconds(monitor.wait) || defaultFields[ConfigKey.WAIT] : defaultFields[ConfigKey.WAIT], @@ -54,5 +72,6 @@ export const getNormalizeICMPFields = ({ ...normalizedFields, }, unsupportedKeys, + errors, }; }; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/index.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/index.ts index 82b2acfacbf5b..6bac17c0fb542 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/index.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/index.ts @@ -14,14 +14,7 @@ import { getNormalizeBrowserFields } from './browser_monitor'; import { getNormalizeICMPFields } from './icmp_monitor'; import { getNormalizeTCPFields } from './tcp_monitor'; import { getNormalizeHTTPFields } from './http_monitor'; - -export interface NormalizedProjectProps { - locations: Locations; - privateLocations: PrivateLocation[]; - monitor: ProjectMonitor; - projectId: string; - namespace: string; -} +import { NormalizedProjectProps } from './common_fields'; export const normalizeProjectMonitor = (props: NormalizedProjectProps) => { const { monitor } = props; @@ -50,14 +43,23 @@ export const normalizeProjectMonitors = ({ monitors = [], projectId, namespace, + version, }: { locations: Locations; privateLocations: PrivateLocation[]; monitors: ProjectMonitor[]; projectId: string; namespace: string; + version: string; }) => { return monitors.map((monitor) => { - return normalizeProjectMonitor({ monitor, locations, privateLocations, projectId, namespace }); + return normalizeProjectMonitor({ + monitor, + locations, + privateLocations, + projectId, + namespace, + version, + }); }); }; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.test.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.test.ts new file mode 100644 index 0000000000000..094bf018ba127 --- /dev/null +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.test.ts @@ -0,0 +1,265 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Locations, LocationStatus, PrivateLocation } from '../../../../common/runtime_types'; +import { normalizeProjectMonitors } from '.'; + +describe('http normalizers', () => { + describe('normalize push monitors', () => { + const projectId = 'test-project-id'; + const locations: Locations = [ + { + id: 'us_central', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + { + id: 'us_east', + label: 'Test Location', + geo: { lat: 33.333, lon: 73.333 }, + url: 'test-url', + isServiceManaged: true, + status: LocationStatus.GA, + }, + ]; + const privateLocations: PrivateLocation[] = [ + { + id: 'germany', + label: 'Germany', + isServiceManaged: false, + concurrentMonitors: 1, + agentPolicyId: 'germany', + }, + ]; + const monitors = [ + { + locations: ['us_central'], + type: 'tcp', + id: 'gmail-smtp', + name: 'GMail SMTP', + hosts: ['smtp.gmail.com:587'], + schedule: 1, + tags: ['service:smtp', 'org:google'], + privateLocations: ['BEEP'], + 'service.name': 'test service', + 'ssl.supported_protocols': ['TLSv1.2', 'TLSv1.3'], + }, + { + locations: ['us_central'], + type: 'tcp', + id: 'always-down', + name: 'Always Down', + hosts: 'localhost:18278', + schedule: 1, + tags: 'tag1,tag2', + privateLocations: ['BEEP'], + service: { + name: 'test service', + }, + ssl: { + supported_protocols: 'TLSv1.2,TLSv1.3', + }, + }, + { + locations: ['us_central'], + type: 'tcp', + id: 'always-down', + name: 'Always Down', + hosts: ['localhost', 'anotherhost'], + ports: ['5698'], + schedule: 1, + tags: 'tag1,tag2', + privateLocations: ['BEEP'], + unsupportedKey: { + nestedUnsupportedKey: 'unnsuportedValue', + }, + }, + ]; + + it('properly normalizes http monitors', () => { + const actual = normalizeProjectMonitors({ + locations, + privateLocations, + monitors, + projectId, + namespace: 'test-space', + version: '8.5.0', + }); + expect(actual).toEqual([ + { + errors: [], + normalizedFields: { + __ui: { + is_tls_enabled: false, + }, + 'check.receive': '', + 'check.send': '', + config_id: '', + custom_heartbeat_id: 'gmail-smtp-test-project-id-test-space', + enabled: true, + form_monitor_type: 'tcp', + hosts: 'smtp.gmail.com:587', + journey_id: 'gmail-smtp', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'GMail SMTP', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + proxy_url: '', + proxy_use_local_resolver: false, + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': 'test service', + 'ssl.certificate': '', + 'ssl.certificate_authorities': '', + 'ssl.key': '', + 'ssl.key_passphrase': '', + 'ssl.supported_protocols': ['TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + tags: ['service:smtp', 'org:google'], + timeout: '16', + type: 'tcp', + }, + unsupportedKeys: [], + }, + { + errors: [], + normalizedFields: { + __ui: { + is_tls_enabled: false, + }, + 'check.receive': '', + 'check.send': '', + config_id: '', + custom_heartbeat_id: 'always-down-test-project-id-test-space', + enabled: true, + form_monitor_type: 'tcp', + hosts: 'localhost:18278', + journey_id: 'always-down', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'Always Down', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + proxy_url: '', + proxy_use_local_resolver: false, + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': 'test service', + 'ssl.certificate': '', + 'ssl.certificate_authorities': '', + 'ssl.key': '', + 'ssl.key_passphrase': '', + 'ssl.supported_protocols': ['TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + tags: ['tag1', 'tag2'], + timeout: '16', + type: 'tcp', + }, + unsupportedKeys: [], + }, + { + errors: [ + { + details: + 'Multiple hosts are not supported for tcp project monitors in 8.5.0. Please set only 1 host per monitor. You monitor was not created or updated.', + id: 'always-down', + reason: 'Unsupported Heartbeat option', + }, + { + details: + 'The following Heartbeat options are not supported for tcp project monitors in 8.5.0: ports|unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.', + id: 'always-down', + reason: 'Unsupported Heartbeat option', + }, + ], + normalizedFields: { + __ui: { + is_tls_enabled: false, + }, + 'check.receive': '', + 'check.send': '', + config_id: '', + custom_heartbeat_id: 'always-down-test-project-id-test-space', + enabled: true, + form_monitor_type: 'tcp', + hosts: 'localhost', + journey_id: 'always-down', + locations: [ + { + geo: { + lat: 33.333, + lon: 73.333, + }, + id: 'us_central', + isServiceManaged: true, + label: 'Test Location', + status: 'ga', + url: 'test-url', + }, + ], + name: 'Always Down', + namespace: 'test_space', + origin: 'project', + original_space: 'test-space', + project_id: 'test-project-id', + proxy_url: '', + proxy_use_local_resolver: false, + schedule: { + number: '1', + unit: 'm', + }, + 'service.name': '', + 'ssl.certificate': '', + 'ssl.certificate_authorities': '', + 'ssl.key': '', + 'ssl.key_passphrase': '', + 'ssl.supported_protocols': ['TLSv1.1', 'TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + tags: ['tag1', 'tag2'], + timeout: '16', + type: 'tcp', + }, + unsupportedKeys: ['ports', 'unsupportedKey.nestedUnsupportedKey'], + }, + ]); + }); + }); +}); diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.ts index 8a85b2959d804..1045bc5ebff72 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/normalizers/tcp_monitor.ts @@ -4,18 +4,25 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - -import { NormalizedProjectProps } from './browser_monitor'; +import { get } from 'lodash'; import { DEFAULT_FIELDS } from '../../../../common/constants/monitor_defaults'; -import { normalizeYamlConfig, getValueInSeconds } from './common_fields'; - import { ConfigKey, DataStream, FormMonitorType, TCPFields, + TLSVersion, } from '../../../../common/runtime_types/monitor_management'; -import { getNormalizeCommonFields, getOptionalArrayField } from './common_fields'; +import { + NormalizedProjectProps, + NormalizerResult, + normalizeYamlConfig, + getNormalizeCommonFields, + getOptionalArrayField, + getOptionalListField, + getMultipleUrlsOrHostsError, + getUnsupportedKeysError, +} from './common_fields'; export const getNormalizeTCPFields = ({ locations = [], @@ -23,8 +30,10 @@ export const getNormalizeTCPFields = ({ monitor, projectId, namespace, -}: NormalizedProjectProps): { normalizedFields: TCPFields; unsupportedKeys: string[] } => { + version, +}: NormalizedProjectProps): NormalizerResult => { const defaultFields = DEFAULT_FIELDS[DataStream.TCP]; + const errors = []; const { yamlConfig, unsupportedKeys } = normalizeYamlConfig(monitor); const commonFields = getNormalizeCommonFields({ @@ -33,8 +42,19 @@ export const getNormalizeTCPFields = ({ monitor, projectId, namespace, + version, }); + /* Check if monitor has multiple hosts */ + const hosts = getOptionalListField(monitor.hosts); + if (hosts.length > 1) { + errors.push(getMultipleUrlsOrHostsError(monitor, 'hosts', version)); + } + + if (unsupportedKeys.length) { + errors.push(getUnsupportedKeysError(monitor, unsupportedKeys, version)); + } + const normalizedFields = { ...yamlConfig, ...commonFields, @@ -42,9 +62,9 @@ export const getNormalizeTCPFields = ({ [ConfigKey.FORM_MONITOR_TYPE]: FormMonitorType.TCP, [ConfigKey.HOSTS]: getOptionalArrayField(monitor[ConfigKey.HOSTS]) || defaultFields[ConfigKey.HOSTS], - [ConfigKey.TIMEOUT]: monitor.timeout - ? getValueInSeconds(monitor.timeout) - : defaultFields[ConfigKey.TIMEOUT], + [ConfigKey.TLS_VERSION]: get(monitor, ConfigKey.TLS_VERSION) + ? (getOptionalListField(get(monitor, ConfigKey.TLS_VERSION)) as TLSVersion[]) + : defaultFields[ConfigKey.TLS_VERSION], }; return { normalizedFields: { @@ -52,5 +72,6 @@ export const getNormalizeTCPFields = ({ ...normalizedFields, }, unsupportedKeys, + errors, }; }; diff --git a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts index 6b337734df5f8..16cbf3f33a8aa 100644 --- a/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts +++ b/x-pack/plugins/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts @@ -196,22 +196,17 @@ export class ProjectMonitorFormatter { try { await this.validatePermissions({ monitor }); - const { normalizedFields: normalizedMonitor, unsupportedKeys } = normalizeProjectMonitor({ + const { normalizedFields: normalizedMonitor, errors } = normalizeProjectMonitor({ monitor, locations: this.locations, privateLocations: this.privateLocations, projectId: this.projectId, namespace: this.spaceId, + version: this.server.kibanaVersion, }); - if (unsupportedKeys.length) { - this.failedMonitors.push({ - id: monitor.id, - reason: 'Unsupported Heartbeat option', - details: `The following Heartbeat options are not supported for ${ - monitor.type - } project monitors in ${this.server.kibanaVersion}: ${unsupportedKeys.join('|')}`, - }); + if (errors.length) { + this.failedMonitors.push(...errors); this.handleStreamingMessage({ message: `${monitor.id}: failed to create or update monitor`, }); 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 0c389000f6c80..9a47ad9de093e 100644 --- a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json +++ b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json @@ -4644,6 +4644,18 @@ "properties": { "all": { "properties": { + "total": { + "type": "long" + }, + "monthly": { + "type": "long" + }, + "weekly": { + "type": "long" + }, + "daily": { + "type": "long" + }, "assignees": { "properties": { "total": { @@ -4657,18 +4669,6 @@ } } }, - "total": { - "type": "long" - }, - "monthly": { - "type": "long" - }, - "weekly": { - "type": "long" - }, - "daily": { - "type": "long" - }, "status": { "properties": { "open": { @@ -4720,6 +4720,18 @@ }, "sec": { "properties": { + "total": { + "type": "long" + }, + "monthly": { + "type": "long" + }, + "weekly": { + "type": "long" + }, + "daily": { + "type": "long" + }, "assignees": { "properties": { "total": { @@ -4732,7 +4744,11 @@ "type": "long" } } - }, + } + } + }, + "obs": { + "properties": { "total": { "type": "long" }, @@ -4744,11 +4760,7 @@ }, "daily": { "type": "long" - } - } - }, - "obs": { - "properties": { + }, "assignees": { "properties": { "total": { @@ -4761,7 +4773,11 @@ "type": "long" } } - }, + } + } + }, + "main": { + "properties": { "total": { "type": "long" }, @@ -4773,11 +4789,7 @@ }, "daily": { "type": "long" - } - } - }, - "main": { - "properties": { + }, "assignees": { "properties": { "total": { @@ -4790,18 +4802,6 @@ "type": "long" } } - }, - "total": { - "type": "long" - }, - "monthly": { - "type": "long" - }, - "weekly": { - "type": "long" - }, - "daily": { - "type": "long" } } } @@ -10029,6 +10029,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10161,6 +10183,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10293,6 +10337,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10425,6 +10491,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10557,6 +10645,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10689,6 +10799,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10847,6 +10979,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -10979,6 +11133,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11111,6 +11287,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11243,6 +11441,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11375,6 +11595,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11507,6 +11749,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11665,6 +11929,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11797,6 +12083,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -11929,6 +12237,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -12061,6 +12391,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -12193,6 +12545,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { @@ -12325,6 +12699,28 @@ } } }, + "enrichment_duration": { + "properties": { + "max": { + "type": "float", + "_meta": { + "description": "The max duration" + } + }, + "avg": { + "type": "float", + "_meta": { + "description": "The avg duration" + } + }, + "min": { + "type": "float", + "_meta": { + "description": "The min duration" + } + } + } + }, "gap_duration": { "properties": { "max": { diff --git a/x-pack/plugins/threat_intelligence/FAQ.md b/x-pack/plugins/threat_intelligence/FAQ.md deleted file mode 100644 index d3f1287713840..0000000000000 --- a/x-pack/plugins/threat_intelligence/FAQ.md +++ /dev/null @@ -1,15 +0,0 @@ -# FAQ - -### Where can I find the UI for the Threat Intelligence plugin? - -Kibana recommends working on a fork of the [elastic/kibana repository](https://github.com/elastic/kibana) (see [here](https://docs.github.com/en/get-started/quickstart/fork-a-repo) to learn about forks). - -### How is the Threat Intelligence code loaded in Kibana? - -The Threat Intelligence plugin is loaded within the [security_solution](https://github.com/elastic/kibana/tree/main/x-pack/plugins/security_solution) plugin. - -### I'm not seeing any data in the Indicators' table - -See this [documentation here](https://github.com/elastic/security-team/blob/main/docs/protections-team/threat-intelligence-services/protections-experience/development-setup.mdx) to get Threat Intelligence feed in Kibana. - -Once you have the feed running, go to `Management > Advanced Settings > Threat indices` and add `filebeat-*` to the list (comma separated). \ No newline at end of file diff --git a/x-pack/plugins/threat_intelligence/README.md b/x-pack/plugins/threat_intelligence/README.md index 945ab9b85a4f1..7395ca0df8a70 100755 --- a/x-pack/plugins/threat_intelligence/README.md +++ b/x-pack/plugins/threat_intelligence/README.md @@ -6,28 +6,55 @@ Elastic Threat Intelligence makes it easy to analyze and investigate potential s The Threat Intelligence UI is displayed in Kibana Security, under the Explore section. -## Quick Start +## Development setup -See the [kibana contributing guide](https://github.com/elastic/kibana/blob/main/CONTRIBUTING.md) for instructions setting up your development environment. +### Kibana development in general -Verify your node version [here](https://github.com/elastic/kibana/blob/main/.node-version). +Best source - [internal Kibana docs](https://docs.elastic.dev/kibana-dev-docs/getting-started/welcome). If you have any issues with setting up your Kibana dev environment [#kibana](https://elastic.slack.com/archives/C0D8P2XK5) Slack channel is a good way to get help. -**Run ES:** +### Essential `kibana.yml` settings -`yarn es snapshot --license trial` +You can make a copy of `kibana.yml` file into `kibana.dev.yml` and make adjustments to the settings. External documentation on the flags available is [here](https://www.elastic.co/guide/en/kibana/current/settings.html) -**Run Kibana:** +It is recommended to set `server.basePath: "/kbn"` to make you local instance persist the base Kibana path. If you don't do it, the base path will be a random string every time you start Kibana. Any other value than `/kbn` will also work. -> **Important:** -> -> See here to get your `kibana.yaml` to enable the Threat Intelligence plugin. +### Getting Threat Intelligence feeds data into Kibana -``` -yarn kbn reset && yarn kbn bootstrap -yarn start --no-base-path -``` +There are many ways to get data for you local development. We first focus on getting Threat Intelligence data specifically. + +### Setting up filebeat threatintel integrations locally + +1. install [mage](https://github.com/magefile/mage). It is a Go build tool used to build `beats`. Installation from the sources requires Go lang set up. A simpler option might be to install it from a package manager available in your system (eg. `brew` on MacOs) or use their [binary distribution](https://github.com/magefile/mage/releases) +1. start Elasticsearch and Kibana +1. clone [beats](https://github.com/elastic/beats) repository +1. inside beats repository, update `x-pack/filebeat/filebeat.yml` with your local Elasticsearch and Kibana connection configs + + ``` + output.elasticsearch: + hosts: ["localhost:9200"] + username: "elastic" + password: "changeme" + + setup.kibana: + host: "localhost:5601" // make sure to run Kibana with --no-base-path option or specify server.basePath in Kibana config and use it here as a path, eg. localhost:5601/kbn + ``` + +1. go into `x-pack/filebeat` (that's where security related modules live) +1. build filebeat `mage build` +1. enable `threatintel` module by running `./filebeat modules enable threatintel` +1. enable specific Threat Intelligence integrations by updating `modules.d/threatintel.yml`. Update `enable` to `true` in every integration you want to enable and configs specific for these integrations. The bare minimum is to enable Abuse.CH feeds `abuseurl`, `abusemalware` and `malwarebazaar`. +1. run `./filebeat setup -E setup.dashboards.directory=build/kibana` to set up predefined dashboards +1. run `./filebeat -e` to start filebeat +1. to validate that the set up works, wait for some Threat Intel data to be ingested and then go in Analytics > Discover in your local Kibana to search `event.category : threat and event.type : indicator`. You should see some documents returned by this search. Abuse.CH feeds are up to date so you should see the results from the last 7 days. + +### More ways to get data -### Performance +There are many more tools available for getting the data for testing or local development, depending on the data type and usecase. + +- Kibana development docs > [Add data](https://docs.elastic.dev/kibana-dev-docs/getting-started/sample-data) +- [Dev/Design/Testing Environments and Frameworks](https://docs.google.com/document/d/1DGCcLMnVKQ_STlkbS4E0m4kbPivNtR8iMlg_IoCuCEw/edit#) gathered by Security Engineering Productivity team + +### Generate fixtures for local testing You can generate large volumes of threat indicators on demand with the following script: @@ -37,17 +64,29 @@ node scripts/generate_indicators.js see the file in order to adjust the amount of indicators generated. The default is one million. -### Useful hints +## Data for E2E tests -Export local instance data to es_archives (will be loaded in cypress tests). +Use es_archives to export data for e2e testing purposes, like so: ``` TEST_ES_PORT=9200 node scripts/es_archiver save x-pack/test/threat_intelligence_cypress/es_archives/threat_intelligence "logs-ti*" ``` +These can be loaded at will with `x-pack/plugins/threat_intelligence/cypress/tasks/es_archiver.ts` task. + +You can use this approach to load separate data dumps for every test case, to cover all critical scenarios. + ## FAQ -See [FAQ.md](https://github.com/elastic/kibana/blob/main/x-pack/plugins/threat_intelligence/FAQ.md) for questions you may have. +### How is the Threat Intelligence code loaded in Kibana? + +The Threat Intelligence plugin is loaded lazily within the [security_solution](https://github.com/elastic/kibana/tree/main/x-pack/plugins/security_solution) plugin, +from `x-pack/plugins/security_solution/public/threat_intelligence` owned by the Protections Experience Team. + +## QA and demo for implemented features + +One way to QA and demo the feature merged into `main` branch is to run the latest `main` locally. +Another option is to deploy a Staging instance. For Staging environment snapshots are being build every night with the latest state of the `main` branch. More documentation can be found [here](https://cloud.elastic.dev/environments/Staging/#automatic-termination-of-staging-deployments) ## Contributing diff --git a/x-pack/plugins/threat_intelligence/public/common/mocks/mock_indicators_filters_context.tsx b/x-pack/plugins/threat_intelligence/public/common/mocks/mock_indicators_filters_context.tsx index 6e9c0b373a0fe..4b7832631fd16 100644 --- a/x-pack/plugins/threat_intelligence/public/common/mocks/mock_indicators_filters_context.tsx +++ b/x-pack/plugins/threat_intelligence/public/common/mocks/mock_indicators_filters_context.tsx @@ -6,11 +6,19 @@ */ import { FilterManager } from '@kbn/data-plugin/public'; -import { IndicatorsFiltersContextValue } from '../../modules/indicators/context'; +import { IndicatorsFiltersContextValue } from '../../modules/indicators/containers/indicators_filters/context'; export const mockIndicatorsFiltersContext: IndicatorsFiltersContextValue = { filterManager: { getFilters: () => [], setFilters: () => {}, } as unknown as FilterManager, + filters: [], + filterQuery: { + language: 'kuery', + query: '', + }, + handleSavedQuery: () => {}, + handleSubmitQuery: () => {}, + handleSubmitTimeRange: () => {}, }; diff --git a/x-pack/plugins/threat_intelligence/public/common/mocks/story_providers.tsx b/x-pack/plugins/threat_intelligence/public/common/mocks/story_providers.tsx index 78c064f72b449..7cea653c45e5f 100644 --- a/x-pack/plugins/threat_intelligence/public/common/mocks/story_providers.tsx +++ b/x-pack/plugins/threat_intelligence/public/common/mocks/story_providers.tsx @@ -11,15 +11,18 @@ import { DataPublicPluginStart } from '@kbn/data-plugin/public'; import { CoreStart, IUiSettingsClient } from '@kbn/core/public'; import { TimelinesUIStart } from '@kbn/timelines-plugin/public'; import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { mockIndicatorsFiltersContext } from './mock_indicators_filters_context'; import { SecuritySolutionContext } from '../../containers/security_solution_context'; import { getSecuritySolutionContextMock } from './mock_security_context'; -import { IndicatorsFiltersContext } from '../../modules/indicators/context'; +import { IndicatorsFiltersContext } from '../../modules/indicators/containers/indicators_filters/context'; import { FieldTypesContext } from '../../containers/field_types_provider'; import { generateFieldTypeMap } from './mock_field_type_map'; import { mockUiSettingsService } from './mock_kibana_ui_settings_service'; import { mockKibanaTimelinesService } from './mock_kibana_timelines_service'; import { mockTriggersActionsUiService } from './mock_kibana_triggers_actions_ui_service'; +import { InspectorContext } from '../../containers/inspector'; export interface KibanaContextMock { /** @@ -81,13 +84,17 @@ export const StoryProvidersComponent: VFC = ({ return ( - - - - {children} - - - + + + + + + {children} + + + + + ); }; diff --git a/x-pack/plugins/threat_intelligence/public/common/mocks/test_providers.tsx b/x-pack/plugins/threat_intelligence/public/common/mocks/test_providers.tsx index 7e046e214b547..c41f8972fd605 100644 --- a/x-pack/plugins/threat_intelligence/public/common/mocks/test_providers.tsx +++ b/x-pack/plugins/threat_intelligence/public/common/mocks/test_providers.tsx @@ -17,12 +17,14 @@ import { unifiedSearchPluginMock } from '@kbn/unified-search-plugin/public/mocks import { createTGridMocks } from '@kbn/timelines-plugin/public/mock'; import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; import { RequestAdapter } from '@kbn/inspector-plugin/common'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router-dom'; import { KibanaContext } from '../../hooks/use_kibana'; import { SecuritySolutionPluginContext } from '../../types'; import { getSecuritySolutionContextMock } from './mock_security_context'; import { mockUiSetting } from './mock_kibana_ui_settings_service'; import { SecuritySolutionContext } from '../../containers/security_solution_context'; -import { IndicatorsFiltersContext } from '../../modules/indicators/context'; +import { IndicatorsFiltersContext } from '../../modules/indicators/containers/indicators_filters/context'; import { mockIndicatorsFiltersContext } from './mock_indicators_filters_context'; import { FieldTypesContext } from '../../containers/field_types_provider'; import { generateFieldTypeMap } from './mock_field_type_map'; @@ -127,28 +129,34 @@ export const mockedServices = { }; export const TestProvidersComponent: FC = ({ children }) => ( - - - - - - - - {children} - - - - - - - + + + + + + + + + + {children} + + + + + + + + + ); export type MockedSearch = jest.Mocked; export type MockedTimefilter = jest.Mocked; export type MockedTriggersActionsUi = jest.Mocked; +export type MockedQueryService = jest.Mocked; export const mockedSearchService = mockedServices.data.search as MockedSearch; +export const mockedQueryService = mockedServices.data.query as MockedQueryService; export const mockedTimefilterService = mockedServices.data.query.timefilter as MockedTimefilter; export const mockedTriggersActionsUiService = mockedServices.triggersActionsUi as MockedTriggersActionsUi; diff --git a/x-pack/plugins/threat_intelligence/public/common/utils/barchart.test.ts b/x-pack/plugins/threat_intelligence/public/common/utils/barchart.test.ts index 1acf8d0213341..004071059a739 100644 --- a/x-pack/plugins/threat_intelligence/public/common/utils/barchart.test.ts +++ b/x-pack/plugins/threat_intelligence/public/common/utils/barchart.test.ts @@ -5,8 +5,8 @@ * 2.0. */ +import type { Aggregation } from '../../modules/indicators/services/fetch_aggregated_indicators'; import { convertAggregationToChartSeries } from './barchart'; -import { Aggregation } from '../../modules/indicators/hooks/use_aggregated_indicators'; const aggregation1: Aggregation = { events: { diff --git a/x-pack/plugins/threat_intelligence/public/common/utils/barchart.ts b/x-pack/plugins/threat_intelligence/public/common/utils/barchart.ts index 93f6b4ce6fd62..c994e7e9f3a3f 100644 --- a/x-pack/plugins/threat_intelligence/public/common/utils/barchart.ts +++ b/x-pack/plugins/threat_intelligence/public/common/utils/barchart.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { +import type { Aggregation, AggregationValue, ChartSeries, -} from '../../modules/indicators/hooks/use_aggregated_indicators'; +} from '../../modules/indicators/services/fetch_aggregated_indicators'; /** * Converts data received from an Elastic search with date_histogram aggregation enabled to something usable in the "@elastic/chart" BarChart component diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.stories.tsx similarity index 78% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.stories.tsx index 56d66781d187d..3f30e6c223cda 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.stories.tsx @@ -7,8 +7,8 @@ import React from 'react'; import { Story } from '@storybook/react'; -import { StoryProvidersComponent } from '../../../../../../common/mocks/story_providers'; -import { IndicatorEmptyPrompt } from './indicator_empty_prompt'; +import { StoryProvidersComponent } from '../../../../../common/mocks/story_providers'; +import { IndicatorEmptyPrompt } from '.'; export default { component: IndicatorEmptyPrompt, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.tsx similarity index 94% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.tsx index 0edf3e67f3c03..7242989ad86a4 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/indicator_empty_prompt.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/empty_prompt.tsx @@ -7,8 +7,7 @@ import { EuiEmptyPrompt } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import React from 'react'; -import { VFC } from 'react'; +import React, { VFC } from 'react'; export const EMPTY_PROMPT_TEST_ID = 'indicatorEmptyPrompt'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/index.ts similarity index 87% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/index.ts index 9e055caf749a6..3c3d20d367b82 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/index.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/empty_prompt/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export * from './indicators_flyout'; +export * from './empty_prompt'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.stories.tsx similarity index 65% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.stories.tsx index c867eda97389f..eb0ed8fb045ed 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.stories.tsx @@ -6,11 +6,11 @@ */ import React from 'react'; -import { mockIndicatorsFiltersContext } from '../../../../../../common/mocks/mock_indicators_filters_context'; -import { IndicatorFieldsTable } from './indicator_fields_table'; -import { generateMockIndicator } from '../../../../../../../common/types/indicator'; -import { StoryProvidersComponent } from '../../../../../../common/mocks/story_providers'; -import { IndicatorsFiltersContext } from '../../../../context'; +import { mockIndicatorsFiltersContext } from '../../../../../common/mocks/mock_indicators_filters_context'; +import { IndicatorFieldsTable } from '.'; +import { generateMockIndicator } from '../../../../../../common/types/indicator'; +import { StoryProvidersComponent } from '../../../../../common/mocks/story_providers'; +import { IndicatorsFiltersContext } from '../../../containers/indicators_filters'; export default { component: IndicatorFieldsTable, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.tsx similarity index 89% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.tsx index 13bb919009bae..e670d6b90e02a 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_fields_table/indicator_fields_table.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/fields_table.tsx @@ -8,9 +8,9 @@ import { EuiBasicTableColumn, EuiInMemoryTable, EuiInMemoryTableProps } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import React, { useMemo, VFC } from 'react'; -import { Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorFieldValue } from '../../../indicator_field_value'; -import { IndicatorValueActions } from '../../../indicator_value_actions'; +import { Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorFieldValue } from '../../indicator_field_value'; +import { IndicatorValueActions } from '../indicator_value_actions'; export interface IndicatorFieldsTableProps { fields: string[]; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/index.ts similarity index 85% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/index.ts index 7e927ef8fab0c..aea9d041e18b8 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/index.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/fields_table/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export * from './indicators_flyout_json'; +export * from './fields_table'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.stories.tsx similarity index 94% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.stories.tsx index ec87259c90a58..69236e778178b 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.stories.tsx @@ -13,8 +13,8 @@ import { mockIndicatorsFiltersContext } from '../../../../common/mocks/mock_indi import { mockUiSettingsService } from '../../../../common/mocks/mock_kibana_ui_settings_service'; import { mockKibanaTimelinesService } from '../../../../common/mocks/mock_kibana_timelines_service'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; -import { IndicatorsFlyout } from './indicators_flyout'; -import { IndicatorsFiltersContext } from '../../context'; +import { IndicatorsFlyout } from '.'; +import { IndicatorsFiltersContext } from '../../containers/indicators_filters'; export default { component: IndicatorsFlyout, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.test.tsx similarity index 98% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.test.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.test.tsx index 08add53bafcb1..a50cf08b3f2b5 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { cleanup, render, screen } from '@testing-library/react'; -import { IndicatorsFlyout, SUBTITLE_TEST_ID, TITLE_TEST_ID } from './indicators_flyout'; +import { IndicatorsFlyout, SUBTITLE_TEST_ID, TITLE_TEST_ID } from '.'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; import { TestProvidersComponent } from '../../../../common/mocks/test_providers'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.tsx similarity index 93% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.tsx index 303059c61fc69..24fe1cc0082ec 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/indicators_flyout.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/flyout.tsx @@ -24,10 +24,10 @@ import { FormattedMessage } from '@kbn/i18n-react'; import { InvestigateInTimelineButton } from '../../../timeline/components/investigate_in_timeline_button'; import { DateFormatter } from '../../../../components/date_formatter/date_formatter'; import { Indicator, RawIndicatorFieldId } from '../../../../../common/types/indicator'; -import { IndicatorsFlyoutJson } from './tabs/indicators_flyout_json/indicators_flyout_json'; -import { IndicatorsFlyoutTable } from './tabs/indicators_flyout_table/indicators_flyout_table'; -import { unwrapValue } from '../../lib/unwrap_value'; -import { IndicatorsFlyoutOverview } from './tabs/indicators_flyout_overview'; +import { IndicatorsFlyoutJson } from './json_tab'; +import { IndicatorsFlyoutTable } from './table_tab'; +import { unwrapValue } from '../../utils/unwrap_value'; +import { IndicatorsFlyoutOverview } from './overview_tab'; export const TITLE_TEST_ID = 'tiIndicatorFlyoutTitle'; export const SUBTITLE_TEST_ID = 'tiIndicatorFlyoutSubtitle'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/index.ts similarity index 85% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/index.ts index a2b896781739c..6a2c75f0054a7 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/components/indicator_empty_prompt/index.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export * from './indicator_empty_prompt'; +export * from './flyout'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_value_actions/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/indicator_value_actions/index.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_value_actions/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/indicator_value_actions/index.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_value_actions/indicator_value_actions.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/indicator_value_actions/indicator_value_actions.tsx similarity index 86% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_value_actions/indicator_value_actions.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/indicator_value_actions/indicator_value_actions.tsx index f3c5fd7c2e7d8..919b39da28c31 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_value_actions/indicator_value_actions.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/indicator_value_actions/indicator_value_actions.tsx @@ -6,13 +6,13 @@ */ import type { EuiButtonEmpty, EuiButtonIcon } from '@elastic/eui'; -import React, { VFC } from 'react'; import { EuiFlexGroup } from '@elastic/eui'; -import { Indicator } from '../../../../../common/types/indicator'; -import { FilterIn } from '../../../query_bar/components/filter_in'; -import { FilterOut } from '../../../query_bar/components/filter_out'; -import { AddToTimeline } from '../../../timeline/components/add_to_timeline'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../lib/field_value'; +import React, { VFC } from 'react'; +import { Indicator } from '../../../../../../common/types/indicator'; +import { FilterIn } from '../../../../query_bar/components/filter_in'; +import { FilterOut } from '../../../../query_bar/components/filter_out'; +import { AddToTimeline } from '../../../../timeline/components/add_to_timeline'; +import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../../utils/field_value'; export const TIMELINE_BUTTON_TEST_ID = 'TimelineButton'; export const FILTER_IN_BUTTON_TEST_ID = 'FilterInButton'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/index.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/index.ts new file mode 100644 index 0000000000000..2d4825141142d --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './json_tab'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.stories.tsx similarity index 88% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.stories.tsx index 1e40c23a26d4d..8d2eead239f4e 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.stories.tsx @@ -7,8 +7,8 @@ import React from 'react'; import { Story } from '@storybook/react'; -import { generateMockIndicator, Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorsFlyoutJson } from './indicators_flyout_json'; +import { generateMockIndicator, Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorsFlyoutJson } from '.'; export default { component: IndicatorsFlyoutJson, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.test.tsx similarity index 82% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.test.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.test.tsx index a468db60a023e..d56b328c61597 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.test.tsx @@ -7,13 +7,13 @@ import React from 'react'; import { render } from '@testing-library/react'; -import { TestProvidersComponent } from '../../../../../../common/mocks/test_providers'; -import { generateMockIndicator, Indicator } from '../../../../../../../common/types/indicator'; -import { CODE_BLOCK_TEST_ID, IndicatorsFlyoutJson } from './indicators_flyout_json'; +import { TestProvidersComponent } from '../../../../../common/mocks/test_providers'; +import { generateMockIndicator, Indicator } from '../../../../../../common/types/indicator'; +import { CODE_BLOCK_TEST_ID, IndicatorsFlyoutJson } from '.'; +import { EMPTY_PROMPT_TEST_ID } from '../empty_prompt'; const mockIndicator: Indicator = generateMockIndicator(); -import { EMPTY_PROMPT_TEST_ID } from '../../components/indicator_empty_prompt'; describe('', () => { it('should render code block component on valid indicator', () => { const { getByTestId } = render( diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.tsx similarity index 86% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.tsx index 99c4bcfb0d50f..f7dc6ad59de00 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_json/indicators_flyout_json.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/json_tab/json_tab.tsx @@ -7,8 +7,8 @@ import React, { VFC } from 'react'; import { EuiCodeBlock } from '@elastic/eui'; -import { Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorEmptyPrompt } from '../../components/indicator_empty_prompt'; +import { Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorEmptyPrompt } from '../empty_prompt'; export const CODE_BLOCK_TEST_ID = 'tiFlyoutJsonCodeBlock'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.stories.tsx similarity index 70% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.stories.tsx index 32966e72c2eec..e30d352c2644f 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.stories.tsx @@ -6,10 +6,10 @@ */ import React from 'react'; -import { IndicatorsFiltersContext } from '../../../../../../context'; -import { StoryProvidersComponent } from '../../../../../../../../common/mocks/story_providers'; -import { generateMockIndicator } from '../../../../../../../../../common/types/indicator'; -import { IndicatorBlock } from './indicator_block'; +import { IndicatorsFiltersContext } from '../../../../containers/indicators_filters'; +import { StoryProvidersComponent } from '../../../../../../common/mocks/story_providers'; +import { generateMockIndicator } from '../../../../../../../common/types/indicator'; +import { IndicatorBlock } from '.'; export default { component: IndicatorBlock, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.tsx similarity index 82% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.tsx index 9537131a574a3..dd8d4335feca1 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/indicator_block.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/block.tsx @@ -7,11 +7,11 @@ import { EuiPanel, EuiSpacer, EuiText } from '@elastic/eui'; import React, { VFC } from 'react'; -import { euiStyled, css } from '@kbn/kibana-react-plugin/common'; -import { Indicator } from '../../../../../../../../../common/types/indicator'; -import { IndicatorFieldValue } from '../../../../../indicator_field_value'; -import { IndicatorFieldLabel } from '../../../../../indicator_field_label'; -import { IndicatorValueActions } from '../../../../../indicator_value_actions'; +import { css, euiStyled } from '@kbn/kibana-react-plugin/common'; +import { Indicator } from '../../../../../../../common/types/indicator'; +import { IndicatorFieldValue } from '../../../indicator_field_value'; +import { IndicatorFieldLabel } from '../../../indicator_field_label'; +import { IndicatorValueActions } from '../../indicator_value_actions'; /** * Show actions wrapper on hover. This is a helper component, limited only to Block diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/index.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/index.ts new file mode 100644 index 0000000000000..e8b564b29af94 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/block/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './block'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/highlighted_values_table/highlighted_values_table.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/highlighted_values_table/highlighted_values_table.tsx similarity index 88% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/highlighted_values_table/highlighted_values_table.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/highlighted_values_table/highlighted_values_table.tsx index d7cf25dca3239..6ce9c332d6323 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/highlighted_values_table/highlighted_values_table.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/highlighted_values_table/highlighted_values_table.tsx @@ -6,9 +6,9 @@ */ import React, { useMemo, VFC } from 'react'; -import { Indicator, RawIndicatorFieldId } from '../../../../../../../../../common/types/indicator'; -import { unwrapValue } from '../../../../../../lib/unwrap_value'; -import { IndicatorFieldsTable } from '../../../../components/indicator_fields_table'; +import { Indicator, RawIndicatorFieldId } from '../../../../../../../common/types/indicator'; +import { unwrapValue } from '../../../../utils/unwrap_value'; +import { IndicatorFieldsTable } from '../../fields_table'; /** * Pick indicator fields starting with the indicator type diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/highlighted_values_table/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/highlighted_values_table/index.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/highlighted_values_table/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/highlighted_values_table/index.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/index.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/index.ts new file mode 100644 index 0000000000000..4f58be52f6ba6 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './overview_tab'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.stories.tsx similarity index 79% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.stories.tsx index 72b20f769575b..005edd9c4201d 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.stories.tsx @@ -7,10 +7,10 @@ import React from 'react'; import { Story } from '@storybook/react'; -import { StoryProvidersComponent } from '../../../../../../common/mocks/story_providers'; -import { generateMockIndicator, Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorsFlyoutOverview } from './indicators_flyout_overview'; -import { IndicatorsFiltersContext } from '../../../../context'; +import { StoryProvidersComponent } from '../../../../../common/mocks/story_providers'; +import { generateMockIndicator, Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorsFlyoutOverview } from '.'; +import { IndicatorsFiltersContext } from '../../../containers/indicators_filters'; export default { component: IndicatorsFlyoutOverview, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.test.tsx similarity index 86% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.test.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.test.tsx index 580534e5668c2..df4201761a98e 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.test.tsx @@ -5,16 +5,16 @@ * 2.0. */ -import { TestProvidersComponent } from '../../../../../../common/mocks/test_providers'; +import { TestProvidersComponent } from '../../../../../common/mocks/test_providers'; import { render, screen } from '@testing-library/react'; import React from 'react'; -import { generateMockIndicator, Indicator } from '../../../../../../../common/types/indicator'; +import { generateMockIndicator, Indicator } from '../../../../../../common/types/indicator'; import { IndicatorsFlyoutOverview, TI_FLYOUT_OVERVIEW_HIGH_LEVEL_BLOCKS, TI_FLYOUT_OVERVIEW_TABLE, -} from './indicators_flyout_overview'; -import { EMPTY_PROMPT_TEST_ID } from '../../components/indicator_empty_prompt'; +} from '.'; +import { EMPTY_PROMPT_TEST_ID } from '../empty_prompt'; describe('', () => { describe('invalid indicator', () => { diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.tsx similarity index 87% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.tsx index c1a0468822269..7abbc1508fb58 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/indicators_flyout_overview.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/overview_tab/overview_tab.tsx @@ -15,14 +15,13 @@ import { EuiTitle, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import React, { useMemo } from 'react'; -import { VFC } from 'react'; -import { EMPTY_VALUE } from '../../../../../../../common/constants'; -import { Indicator, RawIndicatorFieldId } from '../../../../../../../common/types/indicator'; -import { unwrapValue } from '../../../../lib/unwrap_value'; -import { IndicatorEmptyPrompt } from '../../components/indicator_empty_prompt'; -import { IndicatorBlock } from './components/block'; -import { HighlightedValuesTable } from './components/highlighted_values_table'; +import React, { useMemo, VFC } from 'react'; +import { EMPTY_VALUE } from '../../../../../../common/constants'; +import { Indicator, RawIndicatorFieldId } from '../../../../../../common/types/indicator'; +import { unwrapValue } from '../../../utils/unwrap_value'; +import { IndicatorEmptyPrompt } from '../empty_prompt'; +import { IndicatorBlock } from './block'; +import { HighlightedValuesTable } from './highlighted_values_table'; const highLevelFields = [ RawIndicatorFieldId.Feed, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/index.tsx similarity index 87% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/index.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/index.tsx index dbad4c02ee5dc..73571446eeef7 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/components/block/index.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/index.tsx @@ -5,4 +5,4 @@ * 2.0. */ -export * from './indicator_block'; +export * from './table_tab'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.stories.tsx similarity index 72% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.stories.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.stories.tsx index 3a3aa1fa788ee..60808a46356a8 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.stories.tsx @@ -9,12 +9,12 @@ import React from 'react'; import { Story } from '@storybook/react'; import { CoreStart } from '@kbn/core/public'; import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public'; -import { mockIndicatorsFiltersContext } from '../../../../../../common/mocks/mock_indicators_filters_context'; -import { mockUiSettingsService } from '../../../../../../common/mocks/mock_kibana_ui_settings_service'; -import { mockKibanaTimelinesService } from '../../../../../../common/mocks/mock_kibana_timelines_service'; -import { generateMockIndicator, Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorsFlyoutTable } from './indicators_flyout_table'; -import { IndicatorsFiltersContext } from '../../../../context'; +import { mockIndicatorsFiltersContext } from '../../../../../common/mocks/mock_indicators_filters_context'; +import { mockUiSettingsService } from '../../../../../common/mocks/mock_kibana_ui_settings_service'; +import { mockKibanaTimelinesService } from '../../../../../common/mocks/mock_kibana_timelines_service'; +import { generateMockIndicator, Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorsFlyoutTable } from '.'; +import { IndicatorsFiltersContext } from '../../../containers/indicators_filters'; export default { component: IndicatorsFlyoutTable, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.test.tsx similarity index 82% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.test.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.test.tsx index c91ce0e6aa89c..8503bcdace2cc 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.test.tsx @@ -7,15 +7,15 @@ import React from 'react'; import { render } from '@testing-library/react'; -import { TestProvidersComponent } from '../../../../../../common/mocks/test_providers'; +import { TestProvidersComponent } from '../../../../../common/mocks/test_providers'; import { generateMockIndicator, Indicator, RawIndicatorFieldId, -} from '../../../../../../../common/types/indicator'; -import { IndicatorsFlyoutTable, TABLE_TEST_ID } from './indicators_flyout_table'; -import { unwrapValue } from '../../../../lib/unwrap_value'; -import { EMPTY_PROMPT_TEST_ID } from '../../components/indicator_empty_prompt'; +} from '../../../../../../common/types/indicator'; +import { IndicatorsFlyoutTable, TABLE_TEST_ID } from '.'; +import { unwrapValue } from '../../../utils/unwrap_value'; +import { EMPTY_PROMPT_TEST_ID } from '../empty_prompt'; const mockIndicator: Indicator = generateMockIndicator(); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.tsx similarity index 82% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.tsx rename to x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.tsx index 8bb7956afc170..0f0a699733ccb 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/indicators_flyout_table.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/flyout/table_tab/table_tab.tsx @@ -6,9 +6,9 @@ */ import React, { VFC } from 'react'; -import { Indicator } from '../../../../../../../common/types/indicator'; -import { IndicatorEmptyPrompt } from '../../components/indicator_empty_prompt'; -import { IndicatorFieldsTable } from '../../components/indicator_fields_table'; +import { Indicator } from '../../../../../../common/types/indicator'; +import { IndicatorEmptyPrompt } from '../empty_prompt'; +import { IndicatorFieldsTable } from '../fields_table'; export const TABLE_TEST_ID = 'tiFlyoutTableTabRow'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_field_value/indicator_field_value.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_field_value/indicator_field_value.tsx index c0b46cd1b44b0..55dfa883c30ad 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_field_value/indicator_field_value.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicator_field_value/indicator_field_value.tsx @@ -10,7 +10,7 @@ import { useFieldTypes } from '../../../../hooks/use_field_types'; import { EMPTY_VALUE } from '../../../../../common/constants'; import { Indicator, RawIndicatorFieldId } from '../../../../../common/types/indicator'; import { DateFormatter } from '../../../../components/date_formatter'; -import { unwrapValue } from '../../lib/unwrap_value'; +import { unwrapValue } from '../../utils/unwrap_value'; export interface IndicatorFieldValueProps { /** diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.stories.tsx index 465ef3bd1ab78..bb0a1b1205b52 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.stories.tsx @@ -11,8 +11,8 @@ import { Story } from '@storybook/react'; import { TimeRangeBounds } from '@kbn/data-plugin/common'; import { StoryProvidersComponent } from '../../../../common/mocks/story_providers'; import { mockKibanaTimelinesService } from '../../../../common/mocks/mock_kibana_timelines_service'; -import { ChartSeries } from '../../hooks/use_aggregated_indicators'; import { IndicatorsBarChart } from './indicators_barchart'; +import { ChartSeries } from '../../services/fetch_aggregated_indicators'; const mockIndicators: ChartSeries[] = [ { diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.test.tsx index 38de7df2b3d4e..19542bdf200a5 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.test.tsx @@ -10,8 +10,8 @@ import React from 'react'; import { render } from '@testing-library/react'; import { TimeRangeBounds } from '@kbn/data-plugin/common'; import { TestProvidersComponent } from '../../../../common/mocks/test_providers'; -import { ChartSeries } from '../../hooks/use_aggregated_indicators'; import { IndicatorsBarChart } from './indicators_barchart'; +import { ChartSeries } from '../../services/fetch_aggregated_indicators'; moment.suppressDeprecationWarnings = true; moment.tz.setDefault('UTC'); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.tsx index 75d731b23c3b5..d5535f53a862f 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart/indicators_barchart.tsx @@ -11,7 +11,7 @@ import { EuiThemeProvider } from '@elastic/eui'; import { TimeRangeBounds } from '@kbn/data-plugin/common'; import { IndicatorBarchartLegendAction } from '../indicator_barchart_legend_action/indicator_barchart_legend_action'; import { barChartTimeAxisLabelFormatter } from '../../../../common/utils/dates'; -import { ChartSeries } from '../../hooks/use_aggregated_indicators'; +import type { ChartSeries } from '../../services/fetch_aggregated_indicators'; const ID = 'tiIndicator'; const DEFAULT_CHART_HEIGHT = '200px'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.stories.tsx index a9eec2afcf196..f08e8f3b2f0e8 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.stories.tsx @@ -16,9 +16,9 @@ import { DataPublicPluginStart } from '@kbn/data-plugin/public'; import { IUiSettingsClient } from '@kbn/core/public'; import { StoryProvidersComponent } from '../../../../common/mocks/story_providers'; import { mockKibanaTimelinesService } from '../../../../common/mocks/mock_kibana_timelines_service'; -import { Aggregation, AGGREGATION_NAME } from '../../hooks/use_aggregated_indicators'; import { DEFAULT_TIME_RANGE } from '../../../query_bar/hooks/use_filters/utils'; import { IndicatorsBarChartWrapper } from './indicators_barchart_wrapper'; +import { Aggregation, AGGREGATION_NAME } from '../../services/fetch_aggregated_indicators'; export default { component: IndicatorsBarChartWrapper, @@ -120,7 +120,16 @@ export const Default: Story = () => { - + ); }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.test.tsx index 997cfc7922b9d..48d084b0e832a 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.test.tsx @@ -13,6 +13,7 @@ import { TestProvidersComponent } from '../../../../common/mocks/test_providers' import { IndicatorsBarChartWrapper } from './indicators_barchart_wrapper'; import { DEFAULT_TIME_RANGE } from '../../../query_bar/hooks/use_filters/utils'; import { useFilters } from '../../../query_bar/hooks/use_filters'; +import moment from 'moment'; jest.mock('../../../query_bar/hooks/use_filters'); @@ -47,7 +48,14 @@ describe('', () => { it('should render barchart and field selector dropdown', () => { const component = render( - + ); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.tsx index fab1cfc5473d1..31148685e370d 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_barchart_wrapper/indicators_barchart_wrapper.tsx @@ -9,11 +9,12 @@ import React, { memo } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { TimeRange } from '@kbn/es-query'; +import { TimeRangeBounds } from '@kbn/data-plugin/common'; import { SecuritySolutionDataViewBase } from '../../../../types'; import { RawIndicatorFieldId } from '../../../../../common/types/indicator'; -import { useAggregatedIndicators } from '../../hooks/use_aggregated_indicators'; import { IndicatorsFieldSelector } from '../indicators_field_selector/indicators_field_selector'; import { IndicatorsBarChart } from '../indicators_barchart/indicators_barchart'; +import { ChartSeries } from '../../services/fetch_aggregated_indicators'; const DEFAULT_FIELD = RawIndicatorFieldId.Feed; @@ -26,6 +27,14 @@ export interface IndicatorsBarChartWrapperProps { * List of fields coming from the Security Solution sourcerer data view, passed down to the {@link IndicatorFieldSelector} to populate the dropdown. */ indexPattern: SecuritySolutionDataViewBase; + + series: ChartSeries[]; + + dateRange: TimeRangeBounds; + + field: string; + + onFieldChange: (value: string) => void; } /** @@ -33,11 +42,7 @@ export interface IndicatorsBarChartWrapperProps { * and handles retrieving aggregated indicator data. */ export const IndicatorsBarChartWrapper = memo( - ({ timeRange, indexPattern }) => { - const { dateRange, indicators, selectedField, onFieldChange } = useAggregatedIndicators({ - timeRange, - }); - + ({ timeRange, indexPattern, series, dateRange, field, onFieldChange }) => { return ( <> @@ -60,7 +65,7 @@ export const IndicatorsBarChartWrapper = memo(
    {timeRange ? ( - + ) : ( <> )} diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/index.tsx deleted file mode 100644 index 71fcb871adf42..0000000000000 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_overview/index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export * from './indicators_flyout_overview'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/index.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/index.tsx deleted file mode 100644 index fa8190bee8364..0000000000000 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_flyout/tabs/indicators_flyout_table/index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export * from './indicators_flyout_table'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_actions.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_actions.tsx index 0f111f96c4c25..d10ba709bfa2f 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_actions.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_actions.tsx @@ -9,11 +9,11 @@ import React, { VFC } from 'react'; import { EuiDataGridColumnCellActionProps } from '@elastic/eui/src/components/datagrid/data_grid_types'; import { ComponentType } from '../../../../../common/types/component_type'; import { Indicator } from '../../../../../common/types/indicator'; -import { Pagination } from '../../hooks/use_indicators'; import { AddToTimeline } from '../../../timeline/components/add_to_timeline'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../lib/field_value'; +import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../utils/field_value'; import { FilterIn } from '../../../query_bar/components/filter_in'; import { FilterOut } from '../../../query_bar/components/filter_out'; +import type { Pagination } from '../../services/fetch_indicators'; export const CELL_TIMELINE_BUTTON_TEST_ID = 'tiIndicatorsTableCellTimelineButton'; export const CELL_FILTER_IN_BUTTON_TEST_ID = 'tiIndicatorsTableCellFilterInButton'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_renderer.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_renderer.tsx index b95a378a35a5b..394d996d0ce9a 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_renderer.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/cell_renderer.tsx @@ -11,7 +11,7 @@ import { euiLightVars as themeLight, euiDarkVars as themeDark } from '@kbn/ui-th import React from 'react'; import { useKibana } from '../../../../hooks/use_kibana'; import { Indicator } from '../../../../../common/types/indicator'; -import { IndicatorFieldValue } from '../indicator_field_value/indicator_field_value'; +import { IndicatorFieldValue } from '../indicator_field_value'; import { IndicatorsTableContext } from './context'; import { ActionsRowCell } from './actions_row_cell'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.stories.tsx index 1d563141952e3..6505996a26a7d 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.stories.tsx @@ -11,7 +11,7 @@ import { mockIndicatorsFiltersContext } from '../../../../common/mocks/mock_indi import { StoryProvidersComponent } from '../../../../common/mocks/story_providers'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; import { IndicatorsTable } from './indicators_table'; -import { IndicatorsFiltersContext } from '../../context'; +import { IndicatorsFiltersContext } from '../../containers/indicators_filters/context'; import { DEFAULT_COLUMNS } from './hooks/use_column_settings'; export default { @@ -44,7 +44,7 @@ export function WithIndicators() { diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.test.tsx index 71786878bdae3..027033ae47710 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.test.tsx @@ -10,8 +10,8 @@ import React from 'react'; import { IndicatorsTable, IndicatorsTableProps } from './indicators_table'; import { TestProvidersComponent } from '../../../../common/mocks/test_providers'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; -import { BUTTON_TEST_ID } from '../open_indicator_flyout_button/open_indicator_flyout_button'; -import { TITLE_TEST_ID } from '../indicators_flyout/indicators_flyout'; +import { BUTTON_TEST_ID } from '../open_indicator_flyout_button'; +import { TITLE_TEST_ID } from '../flyout'; import { SecuritySolutionDataViewBase } from '../../../../types'; const stub = () => {}; @@ -22,7 +22,7 @@ const tableProps: IndicatorsTableProps = { indicators: [], pagination: { pageSize: 10, pageIndex: 0, pageSizeOptions: [10] }, indicatorCount: 0, - loading: false, + isLoading: false, browserFields: {}, indexPattern: { fields: [], title: '' } as SecuritySolutionDataViewBase, columnSettings: { @@ -60,7 +60,7 @@ describe('', () => { await act(async () => { render( - + ); }); @@ -74,7 +74,7 @@ describe('', () => { diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.tsx index 072fd42db696e..d1888431f7d82 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/components/indicators_table/indicators_table.tsx @@ -23,12 +23,12 @@ import { Indicator, RawIndicatorFieldId } from '../../../../../common/types/indi import { cellRendererFactory } from './cell_renderer'; import { EmptyState } from '../../../../components/empty_state'; import { IndicatorsTableContext, IndicatorsTableContextValue } from './context'; -import { IndicatorsFlyout } from '../indicators_flyout/indicators_flyout'; -import { Pagination } from '../../hooks/use_indicators'; +import { IndicatorsFlyout } from '../flyout'; import { useToolbarOptions } from './hooks/use_toolbar_options'; import { ColumnSettingsValue } from './hooks/use_column_settings'; import { useFieldTypes } from '../../../../hooks/use_field_types'; -import { getFieldSchema } from '../../lib/get_field_schema'; +import { getFieldSchema } from '../../utils/get_field_schema'; +import { Pagination } from '../../services/fetch_indicators'; export interface IndicatorsTableProps { indicators: Indicator[]; @@ -36,7 +36,10 @@ export interface IndicatorsTableProps { pagination: Pagination; onChangeItemsPerPage: (value: number) => void; onChangePage: (value: number) => void; - loading: boolean; + /** + * If true, no data is available yet + */ + isLoading: boolean; indexPattern: SecuritySolutionDataViewBase; browserFields: BrowserFields; columnSettings: ColumnSettingsValue; @@ -57,7 +60,7 @@ export const IndicatorsTable: VFC = ({ onChangePage, onChangeItemsPerPage, pagination, - loading, + isLoading, browserFields, columnSettings: { columns, columnVisibility, handleResetColumns, handleToggleColumn, sorting }, }) => { @@ -137,7 +140,7 @@ export const IndicatorsTable: VFC = ({ ); const gridFragment = useMemo(() => { - if (loading) { + if (isLoading) { return ( @@ -177,7 +180,7 @@ export const IndicatorsTable: VFC = ({ mappedColumns, indicatorCount, leadingControlColumns, - loading, + isLoading, onChangeItemsPerPage, onChangePage, pagination, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/context.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/context.ts similarity index 55% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/context.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/context.ts index b6a4d17754f17..b075668c5015e 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/context.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/context.ts @@ -6,13 +6,18 @@ */ import { createContext } from 'react'; -import { FilterManager } from '@kbn/data-plugin/public'; +import { FilterManager, SavedQuery } from '@kbn/data-plugin/public'; +import { Filter, Query, TimeRange } from '@kbn/es-query'; export interface IndicatorsFiltersContextValue { - /** - * FilterManager is used to interact with KQL bar. - */ + timeRange?: TimeRange; + filters: Filter[]; + filterQuery: Query; + handleSavedQuery: (savedQuery: SavedQuery | undefined) => void; + handleSubmitTimeRange: (timeRange?: TimeRange) => void; + handleSubmitQuery: (filterQuery: Query) => void; filterManager: FilterManager; + savedQuery?: SavedQuery; } export const IndicatorsFiltersContext = createContext( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/index.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/index.ts similarity index 79% rename from x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/index.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/index.ts index a1ca62d0cc862..4ef23e3e95001 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/index.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/index.ts @@ -5,4 +5,6 @@ * 2.0. */ -export { getActionType as getEmailActionType } from './email'; +export * from './indicators_filters'; + +export * from './context'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/indicators_filters.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/indicators_filters.tsx index 0fdd5c60ce5ce..2e8a2b55e4384 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/indicators_filters.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/containers/indicators_filters/indicators_filters.tsx @@ -5,26 +5,105 @@ * 2.0. */ -import React, { ReactNode, VFC } from 'react'; -import { FilterManager } from '@kbn/data-plugin/public'; -import { IndicatorsFiltersContext, IndicatorsFiltersContextValue } from '../../context'; - -export interface IndicatorsFiltersProps { - /** - * Get {@link FilterManager} from the useFilters hook and save it in context to use within the indicators table. - */ - filterManager: FilterManager; - /** - * Component(s) to be displayed inside - */ - children: ReactNode; -} +import React, { FC, useCallback, useEffect, useMemo, useState } from 'react'; +import { useHistory, useLocation } from 'react-router-dom'; +import { SavedQuery } from '@kbn/data-plugin/common'; +import { Filter, Query, TimeRange } from '@kbn/es-query'; +import deepEqual from 'fast-deep-equal'; +import { IndicatorsFiltersContext, IndicatorsFiltersContextValue } from './context'; +import { useKibana } from '../../../../hooks/use_kibana'; + +import { + DEFAULT_QUERY, + DEFAULT_TIME_RANGE, + encodeState, + FILTERS_QUERYSTRING_NAMESPACE, + stateFromQueryParams, +} from '../../../query_bar/hooks/use_filters/utils'; /** * Container used to wrap components and share the {@link FilterManager} through React context. */ -export const IndicatorsFilters: VFC = ({ filterManager, children }) => { - const contextValue: IndicatorsFiltersContextValue = { filterManager }; +export const IndicatorsFilters: FC = ({ children }) => { + const { pathname: browserPathName, search } = useLocation(); + const history = useHistory(); + const [savedQuery, setSavedQuery] = useState(undefined); + + const { + services: { + data: { + query: { filterManager }, + }, + }, + } = useKibana(); + + // Filters are picked using the UI widgets + const [filters, setFilters] = useState([]); + + // Time range is self explanatory + const [timeRange, setTimeRange] = useState(DEFAULT_TIME_RANGE); + + // filterQuery is raw kql query that user can type in to filter results + const [filterQuery, setFilterQuery] = useState(DEFAULT_QUERY); + + // Serialize filters into query string + useEffect(() => { + const filterStateAsString = encodeState({ filters, filterQuery, timeRange }); + if (!deepEqual(filterManager.getFilters(), filters)) { + filterManager.setFilters(filters); + } + + history.replace({ + pathname: browserPathName, + search: `${FILTERS_QUERYSTRING_NAMESPACE}=${filterStateAsString}`, + }); + }, [browserPathName, filterManager, filterQuery, filters, history, timeRange]); + + // Sync filterManager to local state (after they are changed from the ui) + useEffect(() => { + const subscription = filterManager.getUpdates$().subscribe(() => { + setFilters(filterManager.getFilters()); + }); + + return () => subscription.unsubscribe(); + }, [filterManager]); + + // Update local state with filter values from the url (on initial mount) + useEffect(() => { + const { + filters: filtersFromQuery, + timeRange: timeRangeFromQuery, + filterQuery: filterQueryFromQuery, + } = stateFromQueryParams(search); + + setTimeRange(timeRangeFromQuery); + setFilterQuery(filterQueryFromQuery); + setFilters(filtersFromQuery); + + // We only want to have it done on initial render with initial 'search' value; + // that is why 'search' is ommited from the deps array + + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [filterManager]); + + const onSavedQuery = useCallback( + (newSavedQuery: SavedQuery | undefined) => setSavedQuery(newSavedQuery), + [] + ); + + const contextValue: IndicatorsFiltersContextValue = useMemo( + () => ({ + timeRange, + filters, + filterQuery, + handleSavedQuery: onSavedQuery, + handleSubmitTimeRange: setTimeRange, + handleSubmitQuery: setFilterQuery, + filterManager, + savedQuery, + }), + [filterManager, filterQuery, filters, onSavedQuery, savedQuery, timeRange] + ); return ( diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.test.tsx index be8ea27374a1b..85c703cf5dca1 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.test.tsx @@ -5,143 +5,93 @@ * 2.0. */ -import moment from 'moment'; -import { BehaviorSubject, throwError } from 'rxjs'; -import { renderHook } from '@testing-library/react-hooks'; -import { IKibanaSearchResponse, TimeRangeBounds } from '@kbn/data-plugin/common'; -import { - AGGREGATION_NAME, - RawAggregatedIndicatorsResponse, - useAggregatedIndicators, - UseAggregatedIndicatorsParam, -} from './use_aggregated_indicators'; +import { act, renderHook } from '@testing-library/react-hooks'; +import { useAggregatedIndicators, UseAggregatedIndicatorsParam } from './use_aggregated_indicators'; import { DEFAULT_TIME_RANGE } from '../../query_bar/hooks/use_filters/utils'; import { - TestProvidersComponent, - mockedSearchService, mockedTimefilterService, + TestProvidersComponent, } from '../../../common/mocks/test_providers'; -import { useFilters } from '../../query_bar/hooks/use_filters'; +import { createFetchAggregatedIndicators } from '../services/fetch_aggregated_indicators'; -jest.mock('../../query_bar/hooks/use_filters/use_filters'); - -const aggregationResponse = { - rawResponse: { aggregations: { [AGGREGATION_NAME]: { buckets: [] } } }, -}; - -const calculateBoundsResponse: TimeRangeBounds = { - min: moment('1 Jan 2022 06:00:00 GMT'), - max: moment('1 Jan 2022 12:00:00 GMT'), -}; +jest.mock('../services/fetch_aggregated_indicators'); const useAggregatedIndicatorsParams: UseAggregatedIndicatorsParam = { timeRange: DEFAULT_TIME_RANGE, + filters: [], + filterQuery: { language: 'kuery', query: '' }, }; -const stub = () => {}; +const renderUseAggregatedIndicators = () => + renderHook((props: UseAggregatedIndicatorsParam) => useAggregatedIndicators(props), { + initialProps: useAggregatedIndicatorsParams, + wrapper: TestProvidersComponent, + }); describe('useAggregatedIndicators()', () => { beforeEach(jest.clearAllMocks); - beforeEach(() => { - mockedSearchService.search.mockReturnValue(new BehaviorSubject(aggregationResponse)); - mockedTimefilterService.timefilter.calculateBounds.mockReturnValue(calculateBoundsResponse); - }); + type MockedCreateFetchAggregatedIndicators = jest.MockedFunction< + typeof createFetchAggregatedIndicators + >; + let aggregatedIndicatorsQuery: jest.MockedFunction< + ReturnType + >; - describe('when mounted', () => { - beforeEach(() => { - (useFilters as jest.MockedFunction).mockReturnValue({ - filters: [], - filterQuery: { language: 'kuery', query: '' }, - filterManager: {} as any, - handleSavedQuery: stub, - handleSubmitQuery: stub, - handleSubmitTimeRange: stub, - }); - - renderHook(() => useAggregatedIndicators(useAggregatedIndicatorsParams), { - wrapper: TestProvidersComponent, - }); - }); - - it('should query the database for threat indicators', async () => { - expect(mockedSearchService.search).toHaveBeenCalledTimes(1); - }); + beforeEach(jest.clearAllMocks); - it('should use the calculateBounds to convert TimeRange to TimeRangeBounds', () => { - expect(mockedTimefilterService.timefilter.calculateBounds).toHaveBeenCalledTimes(1); - }); + beforeEach(() => { + aggregatedIndicatorsQuery = jest.fn(); + (createFetchAggregatedIndicators as MockedCreateFetchAggregatedIndicators).mockReturnValue( + aggregatedIndicatorsQuery + ); }); - describe('when query fails', () => { - beforeEach(async () => { - mockedSearchService.search.mockReturnValue(throwError(() => new Error('some random error'))); - mockedTimefilterService.timefilter.calculateBounds.mockReturnValue(calculateBoundsResponse); - }); + it('should create and call the aggregatedIndicatorsQuery correctly', async () => { + aggregatedIndicatorsQuery.mockResolvedValue([]); - beforeEach(() => { - renderHook(() => useAggregatedIndicators(useAggregatedIndicatorsParams), { - wrapper: TestProvidersComponent, - }); - }); + const { result, rerender } = renderUseAggregatedIndicators(); - it('should show an error', async () => { - expect(mockedSearchService.showError).toHaveBeenCalledTimes(1); + // indicators service and the query should be called just once + expect( + createFetchAggregatedIndicators as MockedCreateFetchAggregatedIndicators + ).toHaveBeenCalledTimes(1); + expect(aggregatedIndicatorsQuery).toHaveBeenCalledTimes(1); - expect(mockedSearchService.search).toHaveBeenCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - aggregations: expect.any(Object), - query: expect.any(Object), - size: expect.any(Number), - fields: expect.any(Array), - }), - }), - }), - expect.objectContaining({ - abortSignal: expect.any(AbortSignal), - }) - ); - }); - }); - - describe('when query is successful', () => { - beforeEach(async () => { - mockedSearchService.search.mockReturnValue( - new BehaviorSubject>({ - rawResponse: { - aggregations: { - [AGGREGATION_NAME]: { - buckets: [ - { - doc_count: 1, - key: '[Filebeat] AbuseCH Malware', - events: { - buckets: [ - { - doc_count: 0, - key: 1641016800000, - key_as_string: '1 Jan 2022 06:00:00 GMT', - }, - ], - }, - }, - ], - }, - }, - }, - }) - ); - mockedTimefilterService.timefilter.calculateBounds.mockReturnValue(calculateBoundsResponse); - }); - - it('should call mapping function on every hit', async () => { - const { result } = renderHook(() => useAggregatedIndicators(useAggregatedIndicatorsParams), { - wrapper: TestProvidersComponent, - }); + // Ensure the timefilter service is called + expect(mockedTimefilterService.timefilter.calculateBounds).toHaveBeenCalled(); + // Call the query function + expect(aggregatedIndicatorsQuery).toHaveBeenLastCalledWith( + expect.objectContaining({ + filterQuery: { language: 'kuery', query: '' }, + }), + expect.any(AbortSignal) + ); - expect(result.current.indicators.length).toEqual(1); - }); + await act(async () => + rerender({ + filterQuery: { language: 'kuery', query: "threat.indicator.type: 'file'" }, + filters: [], + }) + ); + + expect(aggregatedIndicatorsQuery).toHaveBeenCalledTimes(2); + expect(aggregatedIndicatorsQuery).toHaveBeenLastCalledWith( + expect.objectContaining({ + filterQuery: { language: 'kuery', query: "threat.indicator.type: 'file'" }, + }), + expect.any(AbortSignal) + ); + expect(result.current).toMatchInlineSnapshot(` + Object { + "dateRange": Object { + "max": "2022-01-02T00:00:00.000Z", + "min": "2022-01-01T00:00:00.000Z", + }, + "onFieldChange": [Function], + "selectedField": "threat.feed.name", + "series": Array [], + } + `); }); }); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.ts index 02230defa9688..98e672ac3ad91 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_aggregated_indicators.ts @@ -5,26 +5,20 @@ * 2.0. */ -import { TimeRange } from '@kbn/es-query'; -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Subscription } from 'rxjs'; -import { - IEsSearchRequest, - IKibanaSearchResponse, - isCompleteResponse, - isErrorResponse, - TimeRangeBounds, -} from '@kbn/data-plugin/common'; +import { useQuery } from '@tanstack/react-query'; +import { Filter, Query, TimeRange } from '@kbn/es-query'; +import { useMemo, useState } from 'react'; +import { TimeRangeBounds } from '@kbn/data-plugin/common'; import { useInspector } from '../../../hooks/use_inspector'; -import { useFilters } from '../../query_bar/hooks/use_filters'; -import { convertAggregationToChartSeries } from '../../../common/utils/barchart'; import { RawIndicatorFieldId } from '../../../../common/types/indicator'; -import { calculateBarchartColumnTimeInterval } from '../../../common/utils/dates'; import { useKibana } from '../../../hooks/use_kibana'; import { DEFAULT_TIME_RANGE } from '../../query_bar/hooks/use_filters/utils'; import { useSourcererDataView } from './use_sourcerer_data_view'; -import { getRuntimeMappings } from '../lib/get_runtime_mappings'; -import { getIndicatorsQuery } from '../lib/get_indicators_query'; +import { + ChartSeries, + createFetchAggregatedIndicators, + FetchAggregatedIndicatorsParams, +} from '../services/fetch_aggregated_indicators'; export interface UseAggregatedIndicatorsParam { /** @@ -32,13 +26,15 @@ export interface UseAggregatedIndicatorsParam { * to query indicators for the Indicators barchart. */ timeRange?: TimeRange; + filters: Filter[]; + filterQuery: Query; } export interface UseAggregatedIndicatorsValue { /** * Array of {@link ChartSeries}, ready to be used in the Indicators barchart. */ - indicators: ChartSeries[]; + series: ChartSeries[]; /** * Callback used by the IndicatorsFieldSelector component to query a new set of * aggregated indicators. @@ -55,40 +51,12 @@ export interface UseAggregatedIndicatorsValue { selectedField: string; } -export interface Aggregation { - doc_count: number; - key: string; - events: { - buckets: AggregationValue[]; - }; -} - -export interface AggregationValue { - doc_count: number; - key: number; - key_as_string: string; -} - -export interface ChartSeries { - x: string; - y: number; - g: string; -} - -const TIMESTAMP_FIELD = RawIndicatorFieldId.TimeStamp; const DEFAULT_FIELD = RawIndicatorFieldId.Feed; -export const AGGREGATION_NAME = 'barchartAggregation'; - -export interface RawAggregatedIndicatorsResponse { - aggregations: { - [AGGREGATION_NAME]: { - buckets: Aggregation[]; - }; - }; -} export const useAggregatedIndicators = ({ timeRange = DEFAULT_TIME_RANGE, + filters, + filterQuery, }: UseAggregatedIndicatorsParam): UseAggregatedIndicatorsValue => { const { services: { @@ -100,132 +68,47 @@ export const useAggregatedIndicators = ({ const { inspectorAdapters } = useInspector(); - const searchSubscription$ = useRef(new Subscription()); - const abortController = useRef(new AbortController()); - - const [indicators, setIndicators] = useState([]); const [field, setField] = useState(DEFAULT_FIELD); - const { filters, filterQuery } = useFilters(); - const dateRange: TimeRangeBounds = useMemo( - () => queryService.timefilter.timefilter.calculateBounds(timeRange), - [queryService, timeRange] + const aggregatedIndicatorsQuery = useMemo( + () => + createFetchAggregatedIndicators({ + queryService, + searchService, + inspectorAdapter: inspectorAdapters.requests, + }), + [inspectorAdapters, queryService, searchService] ); - const queryToExecute = useMemo(() => { - return getIndicatorsQuery({ timeRange, filters, filterQuery }); - }, [filterQuery, filters, timeRange]); - - const loadData = useCallback(async () => { - const dateFrom: number = (dateRange.min as moment.Moment).toDate().getTime(); - const dateTo: number = (dateRange.max as moment.Moment).toDate().getTime(); - const interval = calculateBarchartColumnTimeInterval(dateFrom, dateTo); - - const request = inspectorAdapters.requests.start('Indicator barchart', {}); - - request.stats({ - indexPattern: { - label: 'Index patterns', - value: selectedPatterns, + const { data } = useQuery( + [ + 'indicatorsBarchart', + { + filters, + field, + filterQuery, + selectedPatterns, + timeRange, }, - }); - - abortController.current = new AbortController(); - - const requestBody = { - aggregations: { - [AGGREGATION_NAME]: { - terms: { - field, - }, - aggs: { - events: { - date_histogram: { - field: TIMESTAMP_FIELD, - fixed_interval: interval, - min_doc_count: 0, - extended_bounds: { - min: dateFrom, - max: dateTo, - }, - }, - }, - }, - }, - }, - fields: [TIMESTAMP_FIELD, field], - size: 0, - query: queryToExecute, - runtime_mappings: getRuntimeMappings(), - }; - - searchSubscription$.current = searchService - .search>( - { - params: { - index: selectedPatterns, - body: requestBody, - }, - }, - { - abortSignal: abortController.current.signal, - } - ) - .subscribe({ - next: (response) => { - if (isCompleteResponse(response)) { - const aggregations: Aggregation[] = - response.rawResponse.aggregations[AGGREGATION_NAME]?.buckets; - const chartSeries: ChartSeries[] = convertAggregationToChartSeries(aggregations); - setIndicators(chartSeries); - searchSubscription$.current.unsubscribe(); - - request.stats({}).ok({ json: response }); - request.json(requestBody); - } else if (isErrorResponse(response)) { - request.error({ json: response }); - searchSubscription$.current.unsubscribe(); - } - }, - error: (requestError) => { - searchService.showError(requestError); - searchSubscription$.current.unsubscribe(); - - if (requestError instanceof Error && requestError.name.includes('Abort')) { - inspectorAdapters.requests.reset(); - } else { - request.error({ json: requestError }); - } - }, - }); - }, [ - dateRange.max, - dateRange.min, - field, - inspectorAdapters.requests, - queryToExecute, - searchService, - selectedPatterns, - ]); - - const onFieldChange = useCallback( - async (f: string) => { - setField(f); - loadData(); - }, - [loadData, setField] + ], + ({ + signal, + queryKey: [_key, queryParams], + }: { + signal?: AbortSignal; + queryKey: [string, FetchAggregatedIndicatorsParams]; + }) => aggregatedIndicatorsQuery(queryParams, signal) ); - useEffect(() => { - loadData(); - - return () => abortController.current.abort(); - }, [loadData]); + const dateRange = useMemo( + () => queryService.timefilter.timefilter.calculateBounds(timeRange), + [queryService.timefilter.timefilter, timeRange] + ); return { dateRange, - indicators, - onFieldChange, + series: data || [], + onFieldChange: setField, selectedField: field, }; }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.test.tsx index 1b1762eb8b67d..7292dbcd1b03a 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.test.tsx @@ -6,17 +6,11 @@ */ import { renderHook, act } from '@testing-library/react-hooks'; -import { - useIndicators, - RawIndicatorsResponse, - UseIndicatorsParams, - UseIndicatorsValue, -} from './use_indicators'; -import { BehaviorSubject, throwError } from 'rxjs'; -import { TestProvidersComponent, mockedSearchService } from '../../../common/mocks/test_providers'; -import { IKibanaSearchResponse } from '@kbn/data-plugin/public'; - -const indicatorsResponse = { rawResponse: { hits: { hits: [], total: 0 } } }; +import { useIndicators, UseIndicatorsParams, UseIndicatorsValue } from './use_indicators'; +import { TestProvidersComponent } from '../../../common/mocks/test_providers'; +import { createFetchIndicators } from '../services/fetch_indicators'; + +jest.mock('../services/fetch_indicators'); const useIndicatorsParams: UseIndicatorsParams = { filters: [], @@ -24,66 +18,71 @@ const useIndicatorsParams: UseIndicatorsParams = { sorting: [], }; +const indicatorsQueryResult = { indicators: [], total: 0 }; + +const renderUseIndicators = (initialProps = useIndicatorsParams) => + renderHook((props) => useIndicators(props), { + initialProps, + wrapper: TestProvidersComponent, + }); + describe('useIndicators()', () => { + type MockedCreateFetchIndicators = jest.MockedFunction; + let indicatorsQuery: jest.MockedFunction>; + beforeEach(jest.clearAllMocks); + beforeEach(() => { + indicatorsQuery = jest.fn(); + (createFetchIndicators as MockedCreateFetchIndicators).mockReturnValue(indicatorsQuery); + }); + describe('when mounted', () => { - beforeEach(() => { - mockedSearchService.search.mockReturnValue(new BehaviorSubject(indicatorsResponse)); - }); + it('should create and call the indicatorsQuery', async () => { + indicatorsQuery.mockResolvedValue(indicatorsQueryResult); - beforeEach(async () => { - renderHook( - () => useIndicators(useIndicatorsParams), - { - wrapper: TestProvidersComponent, - } - ); - }); + const hookResult = renderUseIndicators(); - it('should query the database for threat indicators', async () => { - expect(mockedSearchService.search).toHaveBeenCalledTimes(1); - }); - }); + // isLoading should be true + expect(hookResult.result.current.isLoading).toEqual(true); + + // indicators service and the query should be called just once + expect(createFetchIndicators as MockedCreateFetchIndicators).toHaveBeenCalledTimes(1); + expect(indicatorsQuery).toHaveBeenCalledTimes(1); - describe('when filters change', () => { - beforeEach(() => { - mockedSearchService.search.mockReturnValue(new BehaviorSubject(indicatorsResponse)); + // isLoading should turn to false eventually + await hookResult.waitFor(() => !hookResult.result.current.isLoading); + expect(hookResult.result.current.isLoading).toEqual(false); }); + }); + describe('when inputs change', () => { it('should query the database again and reset page to 0', async () => { - const hookResult = renderHook( - (props) => useIndicators(props), - { - initialProps: useIndicatorsParams, - wrapper: TestProvidersComponent, - } - ); + const hookResult = renderUseIndicators(); + expect(indicatorsQuery).toHaveBeenCalledTimes(1); - expect(mockedSearchService.search).toHaveBeenCalledTimes(1); - expect(mockedSearchService.search).toHaveBeenLastCalledWith( + // Change page + await act(async () => hookResult.result.current.onChangePage(42)); + + expect(indicatorsQuery).toHaveBeenCalledTimes(2); + expect(indicatorsQuery).toHaveBeenLastCalledWith( expect.objectContaining({ - params: expect.objectContaining({ body: expect.objectContaining({ from: 0 }) }), + pagination: expect.objectContaining({ pageIndex: 42 }), }), - expect.objectContaining({ - abortSignal: expect.any(AbortSignal), - }) + expect.any(AbortSignal) ); - // Change page - await act(async () => hookResult.result.current.onChangePage(42)); + // Change page size + await act(async () => hookResult.result.current.onChangeItemsPerPage(50)); - expect(mockedSearchService.search).toHaveBeenLastCalledWith( + expect(indicatorsQuery).toHaveBeenCalledTimes(3); + expect(indicatorsQuery).toHaveBeenLastCalledWith( expect.objectContaining({ - params: expect.objectContaining({ body: expect.objectContaining({ from: 42 * 25 }) }), + pagination: expect.objectContaining({ pageIndex: 0, pageSize: 50 }), }), - expect.objectContaining({ - abortSignal: expect.any(AbortSignal), - }) + expect.any(AbortSignal) ); - expect(mockedSearchService.search).toHaveBeenCalledTimes(2); - // Change filters act(() => hookResult.rerender({ @@ -92,164 +91,34 @@ describe('useIndicators()', () => { }) ); - // From range should be reset to 0 - expect(mockedSearchService.search).toHaveBeenCalledTimes(3); - expect(mockedSearchService.search).toHaveBeenLastCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ body: expect.objectContaining({ from: 0 }) }), - }), - expect.objectContaining({ - abortSignal: expect.any(AbortSignal), - }) - ); - }); - }); - - describe('when query fails', () => { - beforeEach(async () => { - mockedSearchService.search.mockReturnValue(throwError(() => new Error('some random error'))); - - renderHook((props) => useIndicators(props), { - initialProps: useIndicatorsParams, - wrapper: TestProvidersComponent, - }); - }); - - it('should show an error', async () => { - expect(mockedSearchService.showError).toHaveBeenCalledTimes(1); - - expect(mockedSearchService.search).toHaveBeenCalledWith( + expect(indicatorsQuery).toHaveBeenLastCalledWith( expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - query: expect.any(Object), - from: expect.any(Number), - size: expect.any(Number), - fields: expect.any(Array), - }), - }), + pagination: expect.objectContaining({ pageIndex: 0 }), + filterQuery: { language: 'kuery', query: "threat.indicator.type: 'file'" }, }), - expect.objectContaining({ - abortSignal: expect.any(AbortSignal), - }) + expect.any(AbortSignal) ); - }); - }); - describe('when query is successful', () => { - beforeEach(async () => { - mockedSearchService.search.mockReturnValue( - new BehaviorSubject>({ - rawResponse: { hits: { hits: [{ fields: {} }], total: 1 } }, - }) - ); - }); - - it('should call mapping function on every hit', async () => { - const { result } = renderHook( - (props) => useIndicators(props), - { - initialProps: useIndicatorsParams, - wrapper: TestProvidersComponent, + expect(hookResult.result.current).toMatchInlineSnapshot(` + Object { + "handleRefresh": [Function], + "indicatorCount": 0, + "indicators": Array [], + "isFetching": true, + "isLoading": true, + "onChangeItemsPerPage": [Function], + "onChangePage": [Function], + "pagination": Object { + "pageIndex": 0, + "pageSize": 50, + "pageSizeOptions": Array [ + 10, + 25, + 50, + ], + }, } - ); - expect(result.current.indicatorCount).toEqual(1); - }); - }); - - describe('pagination', () => { - beforeEach(async () => { - mockedSearchService.search.mockReturnValue( - new BehaviorSubject>({ - rawResponse: { hits: { hits: [{ fields: {} }], total: 1 } }, - }) - ); - }); - - describe('when page changes', () => { - it('should run the query again with pagination parameters', async () => { - const { result } = renderHook( - () => useIndicators(useIndicatorsParams), - { - wrapper: TestProvidersComponent, - } - ); - - await act(async () => { - result.current.onChangePage(42); - }); - - expect(mockedSearchService.search).toHaveBeenCalledTimes(2); - - expect(mockedSearchService.search).toHaveBeenCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - size: 25, - from: 0, - }), - }), - }), - expect.anything() - ); - - expect(mockedSearchService.search).toHaveBeenLastCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - size: 25, - from: 42 * 25, - }), - }), - }), - expect.anything() - ); - - expect(result.current.pagination.pageIndex).toEqual(42); - }); - - describe('when page size changes', () => { - it('should fetch the first page and update internal page size', async () => { - const { result } = renderHook( - () => useIndicators(useIndicatorsParams), - { - wrapper: TestProvidersComponent, - } - ); - - await act(async () => { - result.current.onChangeItemsPerPage(50); - }); - - expect(mockedSearchService.search).toHaveBeenCalledTimes(3); - - expect(mockedSearchService.search).toHaveBeenCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - size: 25, - from: 0, - }), - }), - }), - expect.anything() - ); - - expect(mockedSearchService.search).toHaveBeenLastCalledWith( - expect.objectContaining({ - params: expect.objectContaining({ - body: expect.objectContaining({ - size: 50, - from: 0, - }), - }), - }), - expect.anything() - ); - - expect(result.current.pagination.pageIndex).toEqual(0); - }); - }); + `); }); }); }); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.ts index e44e2e05ca230..1855d411eb8c7 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators.ts @@ -5,21 +5,15 @@ * 2.0. */ -import { - IEsSearchRequest, - IKibanaSearchResponse, - isCompleteResponse, - isErrorResponse, -} from '@kbn/data-plugin/common'; -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import type { Subscription } from 'rxjs'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { Filter, Query, TimeRange } from '@kbn/es-query'; +import { useQuery } from '@tanstack/react-query'; +import { EuiDataGridSorting } from '@elastic/eui'; import { useInspector } from '../../../hooks/use_inspector'; import { Indicator } from '../../../../common/types/indicator'; import { useKibana } from '../../../hooks/use_kibana'; import { useSourcererDataView } from './use_sourcerer_data_view'; -import { getRuntimeMappings } from '../lib/get_runtime_mappings'; -import { getIndicatorsQuery } from '../lib/get_indicators_query'; +import { createFetchIndicators, FetchParams, Pagination } from '../services/fetch_indicators'; const PAGE_SIZES = [10, 25, 50]; @@ -29,30 +23,30 @@ export interface UseIndicatorsParams { filterQuery: Query; filters: Filter[]; timeRange?: TimeRange; - sorting: any[]; + sorting: EuiDataGridSorting['columns']; } export interface UseIndicatorsValue { handleRefresh: () => void; + + /** + * Array of {@link Indicator} ready to render inside the IndicatorTable component + */ indicators: Indicator[]; indicatorCount: number; pagination: Pagination; onChangeItemsPerPage: (value: number) => void; onChangePage: (value: number) => void; - loading: boolean; -} -export interface RawIndicatorsResponse { - hits: { - hits: any[]; - total: number; - }; -} + /** + * No data loaded yet + */ + isLoading: boolean; -export interface Pagination { - pageSize: number; - pageIndex: number; - pageSizeOptions: number[]; + /** + * Data loading is in progress (see docs on `isFetching` here: https://tanstack.com/query/v4/docs/guides/queries) + */ + isFetching: boolean; } export const useIndicators = ({ @@ -70,12 +64,20 @@ export const useIndicators = ({ const { inspectorAdapters } = useInspector(); - const searchSubscription$ = useRef(); - const abortController = useRef(new AbortController()); + const onChangeItemsPerPage = useCallback( + (pageSize) => + setPagination((currentPagination) => ({ + ...currentPagination, + pageSize, + pageIndex: 0, + })), + [] + ); - const [indicators, setIndicators] = useState([]); - const [indicatorCount, setIndicatorCount] = useState(0); - const [loading, setLoading] = useState(true); + const onChangePage = useCallback( + (pageIndex) => setPagination((currentPagination) => ({ ...currentPagination, pageIndex })), + [] + ); const [pagination, setPagination] = useState({ pageIndex: 0, @@ -83,119 +85,52 @@ export const useIndicators = ({ pageSizeOptions: PAGE_SIZES, }); - const query = useMemo( - () => getIndicatorsQuery({ filters, timeRange, filterQuery }), - [filterQuery, filters, timeRange] - ); - - const loadData = useCallback( - async (from: number, size: number) => { - abortController.current = new AbortController(); - - setLoading(true); - - const request = inspectorAdapters.requests.start('Indicator search', {}); - - request.stats({ - indexPattern: { - label: 'Index patterns', - value: selectedPatterns, - }, - }); - - const requestBody = { - query, - runtime_mappings: getRuntimeMappings(), - fields: [{ field: '*', include_unmapped: true }], - size, - from, - sort: sorting.map(({ id, direction }) => ({ [id]: direction })), - }; - - searchSubscription$.current = searchService - .search>( - { - params: { - index: selectedPatterns, - body: requestBody, - }, - }, - { - abortSignal: abortController.current.signal, - } - ) - .subscribe({ - next: (response) => { - setIndicators(response.rawResponse.hits.hits); - setIndicatorCount(response.rawResponse.hits.total || 0); - - if (isCompleteResponse(response)) { - setLoading(false); - searchSubscription$.current?.unsubscribe(); - request.stats({}).ok({ json: response }); - request.json(requestBody); - } else if (isErrorResponse(response)) { - setLoading(false); - request.error({ json: response }); - searchSubscription$.current?.unsubscribe(); - } - }, - error: (requestError) => { - searchService.showError(requestError); - searchSubscription$.current?.unsubscribe(); - - if (requestError instanceof Error && requestError.name.includes('Abort')) { - inspectorAdapters.requests.reset(); - } else { - request.error({ json: requestError }); - } - - setLoading(false); - }, - }); - }, - [inspectorAdapters.requests, query, searchService, selectedPatterns, sorting] - ); - - const onChangeItemsPerPage = useCallback( - async (pageSize) => { - setPagination((currentPagination) => ({ - ...currentPagination, - pageSize, - pageIndex: 0, - })); + // Go to first page after filters are changed + useEffect(() => { + onChangePage(0); + }, [filters, filterQuery, timeRange, sorting, onChangePage]); - loadData(0, pageSize); - }, - [loadData] + const fetchIndicators = useMemo( + () => createFetchIndicators({ searchService, inspectorAdapter: inspectorAdapters.requests }), + [inspectorAdapters, searchService] ); - const onChangePage = useCallback( - async (pageIndex) => { - setPagination((currentPagination) => ({ ...currentPagination, pageIndex })); - loadData(pageIndex * pagination.pageSize, pagination.pageSize); - }, - [loadData, pagination.pageSize] + const { isLoading, isFetching, data, refetch } = useQuery( + [ + 'indicatorsTable', + { + timeRange, + filterQuery, + filters, + selectedPatterns, + sorting, + pagination, + }, + ], + ({ signal, queryKey: [_key, queryParams] }) => + fetchIndicators(queryParams as FetchParams, signal), + { + /** + * See https://tanstack.com/query/v4/docs/guides/paginated-queries + * This is essential for our ux + */ + keepPreviousData: true, + } ); const handleRefresh = useCallback(() => { onChangePage(0); - }, [onChangePage]); - - // Initial data load (on mount) - useEffect(() => { - handleRefresh(); - - return () => abortController.current.abort(); - }, [handleRefresh]); + refetch(); + }, [onChangePage, refetch]); return { - indicators, - indicatorCount, + indicators: data?.indicators || [], + indicatorCount: data?.total || 0, pagination, onChangePage, onChangeItemsPerPage, - loading, + isLoading, + isFetching, handleRefresh, }; }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_filters_context.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_filters_context.ts index e8cc4b18474bf..e4c7c48d03d1b 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_filters_context.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_filters_context.ts @@ -6,7 +6,10 @@ */ import { useContext } from 'react'; -import { IndicatorsFiltersContext, IndicatorsFiltersContextValue } from '../context'; +import { + IndicatorsFiltersContext, + IndicatorsFiltersContextValue, +} from '../containers/indicators_filters/context'; /** * Hook to retrieve {@link IndicatorsFiltersContext} (contains FilterManager) diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_total_count.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_total_count.tsx index 9c49ad8126a21..d99d7c0fc4b01 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_total_count.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/hooks/use_indicators_total_count.tsx @@ -12,8 +12,8 @@ import { isCompleteResponse, } from '@kbn/data-plugin/common'; import { useKibana } from '../../../hooks/use_kibana'; -import type { RawIndicatorsResponse } from './use_indicators'; import { useSourcererDataView } from './use_sourcerer_data_view'; +import type { RawIndicatorsResponse } from '../services/fetch_indicators'; export const useIndicatorsTotalCount = () => { const { diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.test.tsx index 371f917c27746..7740345f468d4 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.test.tsx @@ -27,7 +27,7 @@ describe('', () => { useAggregatedIndicators as jest.MockedFunction ).mockReturnValue({ dateRange: { min: moment(), max: moment() }, - indicators: [], + series: [], selectedField: '', onFieldChange: () => {}, }); @@ -35,7 +35,8 @@ describe('', () => { (useIndicators as jest.MockedFunction).mockReturnValue({ indicators: [{ fields: {} }], indicatorCount: 1, - loading: false, + isLoading: false, + isFetching: false, pagination: { pageIndex: 0, pageSize: 10, pageSizeOptions: [10] }, onChangeItemsPerPage: stub, onChangePage: stub, diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.tsx b/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.tsx index 8c138ffec502b..fff2caad5715f 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/indicators_page.tsx @@ -6,7 +6,7 @@ */ import React, { FC, VFC } from 'react'; -import { IndicatorsFilters } from './containers/indicators_filters/indicators_filters'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { IndicatorsBarChartWrapper } from './components/indicators_barchart_wrapper/indicators_barchart_wrapper'; import { IndicatorsTable } from './components/indicators_table/indicators_table'; import { useIndicators } from './hooks/use_indicators'; @@ -18,11 +18,19 @@ import { useSourcererDataView } from './hooks/use_sourcerer_data_view'; import { FieldTypesProvider } from '../../containers/field_types_provider'; import { InspectorProvider } from '../../containers/inspector'; import { useColumnSettings } from './components/indicators_table/hooks/use_column_settings'; +import { useAggregatedIndicators } from './hooks/use_aggregated_indicators'; +import { IndicatorsFilters } from './containers/indicators_filters'; + +const queryClient = new QueryClient(); const IndicatorsPageProviders: FC = ({ children }) => ( - - {children} - + + + + {children} + + + ); const IndicatorsPageContent: VFC = () => { @@ -41,13 +49,27 @@ const IndicatorsPageContent: VFC = () => { savedQuery, } = useFilters(); - const { handleRefresh, ...indicators } = useIndicators({ + const { + handleRefresh, + indicatorCount, + indicators, + isLoading, + onChangeItemsPerPage, + onChangePage, + pagination, + } = useIndicators({ filters, filterQuery, timeRange, sorting: columnSettings.sorting.columns, }); + const { dateRange, series, selectedField, onFieldChange } = useAggregatedIndicators({ + timeRange, + filters, + filterQuery, + }); + return ( @@ -68,15 +90,25 @@ const IndicatorsPageContent: VFC = () => { onSubmitDateRange={handleSubmitTimeRange} /> - - - - + + ); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_indicators_query.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_indicators_query.ts deleted file mode 100644 index 160fa22db7632..0000000000000 --- a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_indicators_query.ts +++ /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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { buildEsQuery, Filter, Query, TimeRange } from '@kbn/es-query'; -import { THREAT_QUERY_BASE } from '../../../../common/constants'; -import { RawIndicatorFieldId } from '../../../../common/types/indicator'; - -const TIMESTAMP_FIELD = RawIndicatorFieldId.TimeStamp; - -export const getIndicatorsQuery = ({ - filters, - filterQuery, - timeRange, -}: { - filters: Filter[]; - filterQuery: Query; - timeRange?: TimeRange; -}) => { - return buildEsQuery( - undefined, - [ - { - query: THREAT_QUERY_BASE, - language: 'kuery', - }, - { - query: filterQuery.query as string, - language: 'kuery', - }, - ], - [ - ...filters, - { - query: { - range: { - [TIMESTAMP_FIELD]: { - gte: timeRange?.from, - lte: timeRange?.to, - }, - }, - }, - meta: {}, - }, - ] - ); -}; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts new file mode 100644 index 0000000000000..c5503f1b32a0c --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts @@ -0,0 +1,117 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { mockedQueryService, mockedSearchService } from '../../../common/mocks/test_providers'; +import { BehaviorSubject, throwError } from 'rxjs'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; +import { AGGREGATION_NAME, createFetchAggregatedIndicators } from './fetch_aggregated_indicators'; + +const aggregationResponse = { + rawResponse: { aggregations: { [AGGREGATION_NAME]: { buckets: [] } } }, +}; + +describe('FetchAggregatedIndicatorsService', () => { + beforeEach(jest.clearAllMocks); + + describe('aggregatedIndicatorsQuery()', () => { + describe('when query is successful', () => { + beforeEach(() => { + mockedSearchService.search.mockReturnValue(new BehaviorSubject(aggregationResponse)); + }); + + it('should pass the query down to searchService', async () => { + const aggregatedIndicatorsQuery = createFetchAggregatedIndicators({ + searchService: mockedSearchService, + queryService: mockedQueryService as any, + inspectorAdapter: new RequestAdapter(), + }); + + const result = await aggregatedIndicatorsQuery({ + selectedPatterns: [], + filterQuery: { language: 'kuery', query: '' }, + filters: [], + field: 'myField', + timeRange: { + from: '', + to: '', + }, + }); + + expect(mockedSearchService.search).toHaveBeenCalled(); + expect(mockedSearchService.search).toHaveBeenCalledWith( + expect.objectContaining({ + params: expect.objectContaining({ + body: expect.objectContaining({ + size: 0, + query: expect.objectContaining({ bool: expect.anything() }), + runtime_mappings: { + 'threat.indicator.name': { script: expect.anything(), type: 'keyword' }, + 'threat.indicator.name_origin': { script: expect.anything(), type: 'keyword' }, + }, + aggregations: { + [AGGREGATION_NAME]: { + terms: { + field: 'myField', + }, + aggs: { + events: { + date_histogram: { + field: '@timestamp', + fixed_interval: expect.anything(), + min_doc_count: 0, + extended_bounds: expect.anything(), + }, + }, + }, + }, + }, + fields: ['@timestamp', 'myField'], + }), + index: [], + }), + }), + expect.anything() + ); + + expect(result).toMatchInlineSnapshot(`Array []`); + }); + }); + + describe('when query fails', () => { + beforeEach(() => { + mockedSearchService.search.mockReturnValue( + throwError(() => new Error('some random exception')) + ); + }); + + it('should throw an error', async () => { + const aggregatedIndicatorsQuery = createFetchAggregatedIndicators({ + searchService: mockedSearchService, + queryService: mockedQueryService as any, + inspectorAdapter: new RequestAdapter(), + }); + + try { + await aggregatedIndicatorsQuery({ + selectedPatterns: [], + filterQuery: { language: 'kuery', query: '' }, + filters: [], + field: 'myField', + timeRange: { + from: '', + to: '', + }, + }); + } catch (error) { + expect(error).toMatchInlineSnapshot(`[Error: some random exception]`); + } + + expect.assertions(1); + }); + }); + }); +}); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts new file mode 100644 index 0000000000000..6cf0fea18b2c3 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts @@ -0,0 +1,125 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { TimeRangeBounds } from '@kbn/data-plugin/common'; +import type { ISearchStart, QueryStart } from '@kbn/data-plugin/public'; +import type { Filter, Query, TimeRange } from '@kbn/es-query'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; +import { convertAggregationToChartSeries } from '../../../common/utils/barchart'; +import { calculateBarchartColumnTimeInterval } from '../../../common/utils/dates'; +import { RawIndicatorFieldId } from '../../../../common/types/indicator'; +import { getIndicatorQueryParams } from '../utils/get_indicator_query_params'; +import { search } from '../utils/search'; + +const TIMESTAMP_FIELD = RawIndicatorFieldId.TimeStamp; + +export const AGGREGATION_NAME = 'barchartAggregation'; + +export interface AggregationValue { + doc_count: number; + key: number; + key_as_string: string; +} + +export interface Aggregation { + doc_count: number; + key: string; + events: { + buckets: AggregationValue[]; + }; +} + +export interface RawAggregatedIndicatorsResponse { + aggregations: { + [AGGREGATION_NAME]: { + buckets: Aggregation[]; + }; + }; +} + +export interface ChartSeries { + x: string; + y: number; + g: string; +} + +export interface FetchAggregatedIndicatorsParams { + selectedPatterns: string[]; + filters: Filter[]; + filterQuery: Query; + timeRange: TimeRange; + field: string; +} + +export const createFetchAggregatedIndicators = + ({ + inspectorAdapter, + searchService, + queryService, + }: { + inspectorAdapter: RequestAdapter; + searchService: ISearchStart; + queryService: QueryStart; + }) => + async ( + { selectedPatterns, timeRange, field, filterQuery, filters }: FetchAggregatedIndicatorsParams, + signal?: AbortSignal + ): Promise => { + const dateRange: TimeRangeBounds = + queryService.timefilter.timefilter.calculateBounds(timeRange); + + const dateFrom: number = (dateRange.min as moment.Moment).toDate().getTime(); + const dateTo: number = (dateRange.max as moment.Moment).toDate().getTime(); + const interval = calculateBarchartColumnTimeInterval(dateFrom, dateTo); + + const sharedParams = getIndicatorQueryParams({ timeRange, filters, filterQuery }); + + const searchRequestBody = { + aggregations: { + [AGGREGATION_NAME]: { + terms: { + field, + }, + aggs: { + events: { + date_histogram: { + field: TIMESTAMP_FIELD, + fixed_interval: interval, + min_doc_count: 0, + extended_bounds: { + min: dateFrom, + max: dateTo, + }, + }, + }, + }, + }, + }, + fields: [TIMESTAMP_FIELD, field], + size: 0, + ...sharedParams, + }; + + const { + aggregations: { [AGGREGATION_NAME]: aggregation }, + } = await search( + searchService, + { + params: { + index: selectedPatterns, + body: searchRequestBody, + }, + }, + { signal, inspectorAdapter, requestName: 'Indicators barchart' } + ); + + const aggregations: Aggregation[] = aggregation?.buckets; + + const chartSeries: ChartSeries[] = convertAggregationToChartSeries(aggregations); + + return chartSeries; + }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts new file mode 100644 index 0000000000000..388b1c9c9e7c5 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { mockedSearchService } from '../../../common/mocks/test_providers'; +import { BehaviorSubject, throwError } from 'rxjs'; +import { createFetchIndicators } from './fetch_indicators'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; + +const indicatorsResponse = { rawResponse: { hits: { hits: [], total: 0 } } }; + +describe('FetchIndicatorsService', () => { + beforeEach(jest.clearAllMocks); + + describe('indicatorsQuery()', () => { + describe('when query is successful', () => { + beforeEach(() => { + mockedSearchService.search.mockReturnValue(new BehaviorSubject(indicatorsResponse)); + }); + + it('should pass the query down to searchService', async () => { + const indicatorsQuery = createFetchIndicators({ + searchService: mockedSearchService, + inspectorAdapter: new RequestAdapter(), + }); + + const result = await indicatorsQuery({ + pagination: { + pageIndex: 0, + pageSize: 25, + pageSizeOptions: [1, 2, 3], + }, + selectedPatterns: [], + sorting: [], + filterQuery: { language: 'kuery', query: '' }, + filters: [], + }); + + expect(mockedSearchService.search).toHaveBeenCalled(); + expect(mockedSearchService.search).toHaveBeenCalledWith( + expect.objectContaining({ + params: { + body: { + fields: [{ field: '*', include_unmapped: true }], + from: 0, + query: expect.objectContaining({ bool: expect.anything() }), + runtime_mappings: { + 'threat.indicator.name': { script: expect.anything(), type: 'keyword' }, + 'threat.indicator.name_origin': { script: expect.anything(), type: 'keyword' }, + }, + size: 25, + sort: [], + }, + index: [], + }, + }), + expect.anything() + ); + + expect(result).toMatchInlineSnapshot(` + Object { + "indicators": Array [], + "total": 0, + } + `); + }); + }); + + describe('when query fails', () => { + beforeEach(() => { + mockedSearchService.search.mockReturnValue( + throwError(() => new Error('some random exception')) + ); + }); + + it('should throw an error', async () => { + const indicatorsQuery = createFetchIndicators({ + searchService: mockedSearchService, + inspectorAdapter: new RequestAdapter(), + }); + + try { + await indicatorsQuery({ + pagination: { + pageIndex: 0, + pageSize: 25, + pageSizeOptions: [1, 2, 3], + }, + selectedPatterns: [], + sorting: [], + filterQuery: { language: 'kuery', query: '' }, + filters: [], + }); + } catch (error) { + expect(error).toMatchInlineSnapshot(`[Error: some random exception]`); + } + + expect.assertions(1); + }); + }); + }); +}); diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts new file mode 100644 index 0000000000000..f06038c320116 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ISearchStart } from '@kbn/data-plugin/public'; +import type { Filter, Query, TimeRange } from '@kbn/es-query'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; +import { Indicator } from '../../../../common/types/indicator'; +import { getIndicatorQueryParams } from '../utils/get_indicator_query_params'; +import { search } from '../utils/search'; + +export interface RawIndicatorsResponse { + hits: { + hits: any[]; + total: number; + }; +} + +export interface Pagination { + pageSize: number; + pageIndex: number; + pageSizeOptions: number[]; +} + +interface FetchIndicatorsDependencies { + searchService: ISearchStart; + inspectorAdapter: RequestAdapter; +} + +export interface FetchParams { + pagination: Pagination; + selectedPatterns: string[]; + sorting: any[]; + filters: Filter[]; + timeRange?: TimeRange; + filterQuery: Query; +} + +type ReactQueryKey = [string, FetchParams]; + +export interface IndicatorsQueryParams { + signal?: AbortSignal; + queryKey: ReactQueryKey; +} + +export interface IndicatorsResponse { + indicators: Indicator[]; + total: number; +} + +export const createFetchIndicators = + ({ searchService, inspectorAdapter }: FetchIndicatorsDependencies) => + async ( + { pagination, selectedPatterns, timeRange, filterQuery, filters, sorting }: FetchParams, + signal?: AbortSignal + ): Promise => { + const sharedParams = getIndicatorQueryParams({ timeRange, filters, filterQuery }); + + const searchRequestBody = { + size: pagination.pageSize, + from: pagination.pageIndex, + fields: [{ field: '*', include_unmapped: true } as const], + sort: sorting.map(({ id, direction }) => ({ [id]: direction })), + ...sharedParams, + }; + + const { + hits: { hits: indicators, total }, + } = await search( + searchService, + { + params: { + index: selectedPatterns, + body: searchRequestBody, + }, + }, + { inspectorAdapter, requestName: 'Indicators table', signal } + ); + + return { indicators, total }; + }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/display_name.test.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/display_name.test.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/display_name.test.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/display_name.test.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/display_name.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/display_name.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/display_name.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/display_name.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/field_value.test.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/field_value.test.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/field_value.test.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/field_value.test.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/field_value.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/field_value.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/field_value.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/field_value.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_field_schema.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_field_schema.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_field_schema.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_field_schema.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_indicator_query_params.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_indicator_query_params.ts new file mode 100644 index 0000000000000..bcaf304fdfd70 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_indicator_query_params.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { buildEsQuery, Filter, Query, TimeRange } from '@kbn/es-query'; +import { THREAT_QUERY_BASE } from '../../../../common/constants'; +import { RawIndicatorFieldId } from '../../../../common/types/indicator'; +import { threatIndicatorNamesOriginScript, threatIndicatorNamesScript } from './display_name'; + +const TIMESTAMP_FIELD = RawIndicatorFieldId.TimeStamp; + +/** + * Prepare shared `runtime_mappings` and `query` fields used within indicator search request + */ +export const getIndicatorQueryParams = ({ + filters, + filterQuery, + timeRange, +}: { + filters: Filter[]; + filterQuery: Query; + timeRange?: TimeRange; +}) => { + return { + runtime_mappings: { + [RawIndicatorFieldId.Name]: { + type: 'keyword', + script: { + source: threatIndicatorNamesScript(), + }, + }, + [RawIndicatorFieldId.NameOrigin]: { + type: 'keyword', + script: { + source: threatIndicatorNamesOriginScript(), + }, + }, + } as const, + query: buildEsQuery( + undefined, + [ + { + query: THREAT_QUERY_BASE, + language: 'kuery', + }, + { + query: filterQuery.query as string, + language: 'kuery', + }, + ], + [ + ...filters, + { + query: { + range: { + [TIMESTAMP_FIELD]: { + gte: timeRange?.from, + lte: timeRange?.to, + }, + }, + }, + meta: {}, + }, + ] + ), + }; +}; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_runtime_mappings.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_runtime_mappings.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/get_runtime_mappings.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/get_runtime_mappings.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/search.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/search.ts new file mode 100644 index 0000000000000..49cd371680ce0 --- /dev/null +++ b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/search.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + IEsSearchRequest, + IKibanaSearchResponse, + isCompleteResponse, + isErrorResponse, +} from '@kbn/data-plugin/common'; +import { ISearchStart } from '@kbn/data-plugin/public'; +import { RequestAdapter } from '@kbn/inspector-plugin/common'; + +interface SearchOptions { + /** + * Inspector adapter, available in the context + */ + inspectorAdapter: RequestAdapter; + + /** + * Request name registered in the inspector panel + */ + requestName: string; + + /** + * Abort signal + */ + signal?: AbortSignal; +} + +/** + * This is a searchService wrapper that will instrument your query with `inspector` and turn it into a Promise, + * resolved when complete result set is returned or rejected on any error, other than Abort. + */ +export const search = async ( + searchService: ISearchStart, + searchRequest: IEsSearchRequest, + { inspectorAdapter, requestName, signal }: SearchOptions +): Promise => { + const requestId = `${Date.now()}`; + const request = inspectorAdapter.start(requestName, { id: requestId }); + + return new Promise((resolve, reject) => { + searchService + .search>(searchRequest, { + abortSignal: signal, + }) + .subscribe({ + next: (response) => { + if (isCompleteResponse(response)) { + request.stats({}).ok({ json: response }); + request.json(searchRequest.params?.body || {}); + + resolve(response.rawResponse); + } else if (isErrorResponse(response)) { + request.error({ json: response }); + reject(response); + } + }, + error: (requestError) => { + if (requestError instanceof Error && requestError.name.includes('Abort')) { + inspectorAdapter.resetRequest(requestId); + } else { + request.error({ json: requestError }); + } + + searchService.showError(requestError); + reject(requestError); + }, + }); + }); +}; diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/unwrap_value.test.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/unwrap_value.test.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/unwrap_value.test.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/unwrap_value.test.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/indicators/lib/unwrap_value.ts b/x-pack/plugins/threat_intelligence/public/modules/indicators/utils/unwrap_value.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/indicators/lib/unwrap_value.ts rename to x-pack/plugins/threat_intelligence/public/modules/indicators/utils/unwrap_value.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.stories.tsx index 1e6c7d0c2614e..08297774e51f6 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.stories.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { Story } from '@storybook/react'; import { mockIndicatorsFiltersContext } from '../../../../common/mocks/mock_indicators_filters_context'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; -import { IndicatorsFiltersContext } from '../../../indicators/context'; +import { IndicatorsFiltersContext } from '../../../indicators/containers/indicators_filters/context'; import { FilterIn } from '.'; export default { diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.tsx index d801f46915921..d6d62b3e35380 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_in/filter_in.tsx @@ -11,8 +11,11 @@ import { EuiButtonEmpty, EuiButtonIcon, EuiContextMenuItem, EuiToolTip } from '@ import { Filter } from '@kbn/es-query'; import { ComponentType } from '../../../../../common/types/component_type'; import { useIndicatorsFiltersContext } from '../../../indicators/hooks/use_indicators_filters_context'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../../indicators/lib/field_value'; -import { FilterIn as FilterInConst, updateFiltersArray } from '../../lib/filter'; +import { + fieldAndValueValid, + getIndicatorFieldAndValue, +} from '../../../indicators/utils/field_value'; +import { FilterIn as FilterInConst, updateFiltersArray } from '../../utils/filter'; import { Indicator } from '../../../../../common/types/indicator'; import { useStyles } from './styles'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.stories.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.stories.tsx index a2f0061d36a94..cf625c23754a3 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.stories.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.stories.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { Story } from '@storybook/react'; import { mockIndicatorsFiltersContext } from '../../../../common/mocks/mock_indicators_filters_context'; import { generateMockIndicator, Indicator } from '../../../../../common/types/indicator'; -import { IndicatorsFiltersContext } from '../../../indicators/context'; +import { IndicatorsFiltersContext } from '../../../indicators/containers/indicators_filters/context'; import { FilterOut } from '.'; export default { diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.tsx index 67f28a66b486e..afa1bc02a6ba9 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/filter_out/filter_out.tsx @@ -11,8 +11,11 @@ import { EuiButtonEmpty, EuiButtonIcon, EuiContextMenuItem, EuiToolTip } from '@ import { Filter } from '@kbn/es-query'; import { ComponentType } from '../../../../../common/types/component_type'; import { useIndicatorsFiltersContext } from '../../../indicators/hooks/use_indicators_filters_context'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../../indicators/lib/field_value'; -import { FilterOut as FilterOutConst, updateFiltersArray } from '../../lib/filter'; +import { + fieldAndValueValid, + getIndicatorFieldAndValue, +} from '../../../indicators/utils/field_value'; +import { FilterOut as FilterOutConst, updateFiltersArray } from '../../utils/filter'; import { Indicator } from '../../../../../common/types/indicator'; import { useStyles } from './styles'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/query_bar/query_bar.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/query_bar/query_bar.tsx index d2739476d7d6b..e564c898f894a 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/query_bar/query_bar.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/components/query_bar/query_bar.tsx @@ -82,15 +82,17 @@ export const QueryBar = memo( }) => { const onQuerySubmit = useCallback( ({ query, dateRange }: QueryPayload) => { - if (isQuery(query) && !deepEqual(query, filterQuery)) { - onSubmitQuery(query); - } - if (dateRange != null) { onSubmitDateRange(dateRange); } + + if (isQuery(query) && !deepEqual(query, filterQuery)) { + onSubmitQuery(query); + } else { + onRefresh(); + } }, - [filterQuery, onSubmitDateRange, onSubmitQuery] + [filterQuery, onRefresh, onSubmitDateRange, onSubmitQuery] ); const onQueryChange = useCallback( @@ -169,7 +171,6 @@ export const QueryBar = memo( dataTestSubj={dataTestSubj} savedQuery={savedQuery} displayStyle={displayStyle} - onRefresh={onRefresh} /> ); } diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.test.tsx b/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.test.tsx index b9c16240df4b0..4d34c9ee6ff0f 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.test.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.test.tsx @@ -9,28 +9,37 @@ import { mockUseKibanaForFilters } from '../../../../common/mocks/mock_use_kiban import { renderHook, act, RenderHookResult, Renderer } from '@testing-library/react-hooks'; import { useFilters, UseFiltersValue } from './use_filters'; -import { useHistory, useLocation } from 'react-router-dom'; +import { useLocation, useHistory } from 'react-router-dom'; import { Filter } from '@kbn/es-query'; import { TestProvidersComponent } from '../../../../common/mocks/test_providers'; +import React, { FC } from 'react'; +import { IndicatorsFilters } from '../../../indicators/containers/indicators_filters'; jest.mock('react-router-dom', () => ({ - useLocation: jest.fn().mockReturnValue({ - search: '', - }), + MemoryRouter: ({ children }: any) => <>{children}, + useLocation: jest.fn().mockReturnValue({ pathname: '', search: '' }), useHistory: jest.fn().mockReturnValue({ replace: jest.fn() }), })); +const FiltersWrapper: FC = ({ children }) => ( + + {children}{' '} + +); + +const renderUseFilters = () => renderHook(() => useFilters(), { wrapper: FiltersWrapper }); + describe('useFilters()', () => { let hookResult: RenderHookResult<{}, UseFiltersValue, Renderer>; let mockRef: ReturnType; + afterAll(() => jest.unmock('react-router-dom')); + describe('when mounted', () => { beforeEach(async () => { mockRef = mockUseKibanaForFilters(); - hookResult = renderHook(() => useFilters(), { - wrapper: TestProvidersComponent, - }); + hookResult = renderUseFilters(); }); it('should have valid initial filterQuery value', () => { @@ -44,9 +53,7 @@ describe('useFilters()', () => { '?indicators=(filterQuery:(language:kuery,query:%27threat.indicator.type%20:%20"file"%20%27),filters:!(),timeRange:(from:now/d,to:now/d))', }); - hookResult = renderHook(() => useFilters(), { - wrapper: TestProvidersComponent, - }); + hookResult = renderUseFilters(); expect(hookResult.result.current.filterQuery).toMatchObject({ language: 'kuery', @@ -61,9 +68,7 @@ describe('useFilters()', () => { beforeEach(async () => { mockRef = mockUseKibanaForFilters(); - hookResult = renderHook(() => useFilters(), { - wrapper: TestProvidersComponent, - }); + hookResult = renderUseFilters(); (useHistory as jest.Mock).mockReturnValue({ replace: historyReplace }); diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.ts b/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.ts index 73ce49691d5a6..c50a10c17b709 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/query_bar/hooks/use_filters/use_filters.ts @@ -5,110 +5,24 @@ * 2.0. */ -import { Filter, Query, TimeRange } from '@kbn/es-query'; -import { useCallback, useEffect, useState } from 'react'; -import { useHistory, useLocation } from 'react-router-dom'; -import deepEqual from 'fast-deep-equal'; -import type { FilterManager, SavedQuery } from '@kbn/data-plugin/public'; -import { useKibana } from '../../../../hooks/use_kibana'; +import { useContext } from 'react'; import { - DEFAULT_QUERY, - DEFAULT_TIME_RANGE, - encodeState, - FILTERS_QUERYSTRING_NAMESPACE, - stateFromQueryParams, -} from './utils'; + IndicatorsFiltersContext, + IndicatorsFiltersContextValue, +} from '../../../indicators/containers/indicators_filters'; -export interface UseFiltersValue { - timeRange?: TimeRange; - filters: Filter[]; - filterQuery: Query; - handleSavedQuery: (savedQuery: SavedQuery | undefined) => void; - handleSubmitTimeRange: (timeRange?: TimeRange) => void; - handleSubmitQuery: (filterQuery: Query) => void; - filterManager: FilterManager; - savedQuery?: SavedQuery; -} +export type UseFiltersValue = IndicatorsFiltersContextValue; /** * Custom react hook housing logic for KQL bar * @returns Filters and TimeRange for use with KQL bar */ -export const useFilters = (): UseFiltersValue => { - const { pathname: browserPathName, search } = useLocation(); - const history = useHistory(); - const [savedQuery, setSavedQuery] = useState(undefined); +export const useFilters = () => { + const contextValue = useContext(IndicatorsFiltersContext); - const { - services: { - data: { - query: { filterManager }, - }, - }, - } = useKibana(); + if (!contextValue) { + throw new Error('Filters can only be used inside IndicatorFiltersContext'); + } - // Filters are picked using the UI widgets - const [filters, setFilters] = useState([]); - - // Time range is self explanatory - const [timeRange, setTimeRange] = useState(DEFAULT_TIME_RANGE); - - // filterQuery is raw kql query that user can type in to filter results - const [filterQuery, setFilterQuery] = useState(DEFAULT_QUERY); - - // Serialize filters into query string - useEffect(() => { - const filterStateAsString = encodeState({ filters, filterQuery, timeRange }); - if (!deepEqual(filterManager.getFilters(), filters)) { - filterManager.setFilters(filters); - } - - history.replace({ - pathname: browserPathName, - search: `${FILTERS_QUERYSTRING_NAMESPACE}=${filterStateAsString}`, - }); - }, [browserPathName, filterManager, filterQuery, filters, history, timeRange]); - - // Sync filterManager to local state (after they are changed from the ui) - useEffect(() => { - const subscription = filterManager.getUpdates$().subscribe(() => { - setFilters(filterManager.getFilters()); - }); - - return () => subscription.unsubscribe(); - }, [filterManager]); - - // Update local state with filter values from the url (on initial mount) - useEffect(() => { - const { - filters: filtersFromQuery, - timeRange: timeRangeFromQuery, - filterQuery: filterQueryFromQuery, - } = stateFromQueryParams(search); - - setTimeRange(timeRangeFromQuery); - setFilterQuery(filterQueryFromQuery); - setFilters(filtersFromQuery); - - // We only want to have it done on initial render with initial 'search' value; - // that is why 'search' is ommited from the deps array - - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [filterManager]); - - const onSavedQuery = useCallback( - (newSavedQuery: SavedQuery | undefined) => setSavedQuery(newSavedQuery), - [] - ); - - return { - timeRange, - filters, - filterQuery, - handleSavedQuery: onSavedQuery, - handleSubmitTimeRange: setTimeRange, - handleSubmitQuery: setFilterQuery, - filterManager, - savedQuery, - }; + return contextValue; }; diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/lib/filter.test.ts b/x-pack/plugins/threat_intelligence/public/modules/query_bar/utils/filter.test.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/query_bar/lib/filter.test.ts rename to x-pack/plugins/threat_intelligence/public/modules/query_bar/utils/filter.test.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/query_bar/lib/filter.ts b/x-pack/plugins/threat_intelligence/public/modules/query_bar/utils/filter.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/query_bar/lib/filter.ts rename to x-pack/plugins/threat_intelligence/public/modules/query_bar/utils/filter.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/timeline/components/add_to_timeline/add_to_timeline.tsx b/x-pack/plugins/threat_intelligence/public/modules/timeline/components/add_to_timeline/add_to_timeline.tsx index 2c0d2ec6c5f37..5b33a3bfeaa35 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/timeline/components/add_to_timeline/add_to_timeline.tsx +++ b/x-pack/plugins/threat_intelligence/public/modules/timeline/components/add_to_timeline/add_to_timeline.tsx @@ -12,9 +12,12 @@ import { EuiButtonEmpty, EuiButtonIcon } from '@elastic/eui/src/components/butto import { EuiContextMenuItem, EuiFlexItem, EuiToolTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { generateDataProvider } from '../../lib/data_provider'; +import { generateDataProvider } from '../../utils/data_provider'; import { ComponentType } from '../../../../../common/types/component_type'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../../indicators/lib/field_value'; +import { + fieldAndValueValid, + getIndicatorFieldAndValue, +} from '../../../indicators/utils/field_value'; import { useKibana } from '../../../../hooks/use_kibana'; import { Indicator } from '../../../../../common/types/indicator'; import { useStyles } from './styles'; diff --git a/x-pack/plugins/threat_intelligence/public/modules/timeline/hooks/use_investigate_in_timeline.ts b/x-pack/plugins/threat_intelligence/public/modules/timeline/hooks/use_investigate_in_timeline.ts index 904a0afc4fd93..4f79990d00c34 100644 --- a/x-pack/plugins/threat_intelligence/public/modules/timeline/hooks/use_investigate_in_timeline.ts +++ b/x-pack/plugins/threat_intelligence/public/modules/timeline/hooks/use_investigate_in_timeline.ts @@ -8,10 +8,10 @@ import { useContext } from 'react'; import moment from 'moment'; import { DataProvider } from '@kbn/timelines-plugin/common'; -import { generateDataProvider } from '../lib/data_provider'; +import { generateDataProvider } from '../utils/data_provider'; import { SecuritySolutionContext } from '../../../containers/security_solution_context'; -import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../indicators/lib/field_value'; -import { unwrapValue } from '../../indicators/lib/unwrap_value'; +import { fieldAndValueValid, getIndicatorFieldAndValue } from '../../indicators/utils/field_value'; +import { unwrapValue } from '../../indicators/utils/unwrap_value'; import { Indicator, IndicatorFieldEventEnrichmentMap, diff --git a/x-pack/plugins/threat_intelligence/public/modules/timeline/lib/data_provider.test.ts b/x-pack/plugins/threat_intelligence/public/modules/timeline/utils/data_provider.test.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/timeline/lib/data_provider.test.ts rename to x-pack/plugins/threat_intelligence/public/modules/timeline/utils/data_provider.test.ts diff --git a/x-pack/plugins/threat_intelligence/public/modules/timeline/lib/data_provider.ts b/x-pack/plugins/threat_intelligence/public/modules/timeline/utils/data_provider.ts similarity index 100% rename from x-pack/plugins/threat_intelligence/public/modules/timeline/lib/data_provider.ts rename to x-pack/plugins/threat_intelligence/public/modules/timeline/utils/data_provider.ts diff --git a/x-pack/plugins/threat_intelligence/scripts/generate_indicators.js b/x-pack/plugins/threat_intelligence/scripts/generate_indicators.js index 44e0ad166353c..0d5c170965fe7 100644 --- a/x-pack/plugins/threat_intelligence/scripts/generate_indicators.js +++ b/x-pack/plugins/threat_intelligence/scripts/generate_indicators.js @@ -50,7 +50,7 @@ const main = async () => { 'threat.feed.name': { type: 'keyword', }, - 'threat.indicator.url.original': { + 'threat.indicator.url.full': { type: 'keyword', }, 'threat.indicator.first_seen': { @@ -92,7 +92,7 @@ const main = async () => { 'threat.indicator.first_seen': timestamp, 'threat.feed.name': FEED_NAMES[Math.ceil(Math.random() * FEED_NAMES.length) - 1], 'threat.indicator.type': 'url', - 'threat.indicator.url.original': faker.internet.url(), + 'threat.indicator.url.full': faker.internet.url(), 'event.type': 'indicator', 'event.category': 'threat', }, diff --git a/x-pack/plugins/translations/translations/fr-FR.json b/x-pack/plugins/translations/translations/fr-FR.json index 4b06b5ae9b13e..60b692e720ec0 100644 --- a/x-pack/plugins/translations/translations/fr-FR.json +++ b/x-pack/plugins/translations/translations/fr-FR.json @@ -988,7 +988,6 @@ "dashboard.panel.copyToDashboard.goToDashboard": "Copier et accéder au tableau de bord", "dashboard.panel.copyToDashboard.newDashboardOptionLabel": "Nouveau tableau de bord", "dashboard.panel.copyToDashboard.title": "Copier dans le tableau de bord", - "dashboard.panel.invalidData": "Données non valides dans l'url", "dashboard.panel.LibraryNotification": "Notification de la bibliothèque Visualize", "dashboard.panel.libraryNotification.ariaLabel": "Afficher les informations de la bibliothèque et dissocier ce panneau", "dashboard.panel.libraryNotification.toolTip": "La modification de ce panneau pourrait affecter d’autres tableaux de bord. Pour modifier ce panneau uniquement, dissociez-le de la bibliothèque.", @@ -6377,6 +6376,380 @@ "xpack.stackConnectors.xmatters.shouldNotHaveSecretsUrl": "secretsUrl ne doit pas être fournie lorsque usesBasic est vrai", "xpack.stackConnectors.xmatters.shouldNotHaveUsernamePassword": "Le nom d'utilisateur et le mot de passe ne doivent pas être fournis lorsque usesBasic est faux", "xpack.stackConnectors.xmatters.title": "xMatters", + "xpack.stackConnectors.components.casesWebhook.error.missingVariables": "{variableCount, plural, one {Variable obligatoire manquante} other {Variables obligatoires manquantes}} : {variables}", + "xpack.stackConnectors.components.index.preconfiguredIndexHelpText": "Les documents sont indexés dans l'index {alertHistoryIndex}. ", + "xpack.stackConnectors.components.jira.unableToGetIssueMessage": "Impossible d'obtenir le problème ayant l'ID {id}", + "xpack.stackConnectors.components.pagerDuty.error.invalidTimestamp": "L'horodatage doit être une date valide, telle que {nowShortFormat} ou {nowLongFormat}.", + "xpack.stackConnectors.components.serviceNow.apiInfoError": "Statut reçu : {status} lors de la tentative d'obtention d'informations sur l'application", + "xpack.stackConnectors.components.serviceNow.appInstallationInfo": "{update} {create} ", + "xpack.stackConnectors.components.serviceNow.updateSuccessToastTitle": "Connecteur {connectorName} mis à jour", + "xpack.stackConnectors.components.serviceNow.apiUrlHelpLabel": "Fournissez l'URL complète vers l'instance ServiceNow souhaitée. Si vous n'en avez pas, {instance}.", + "xpack.stackConnectors.components.serviceNow.appRunning": "L'application Elastic de l'app store ServiceNow doit être installée avant d'exécuter la mise à jour. {visitLink} pour installer l'application", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationMessage": "Impossible d'obtenir l'application avec l'ID {id}", + "xpack.stackConnectors.components.casesWebhook.commentsTextAreaFieldLabel": "Commentaires supplémentaires", + "xpack.stackConnectors.components.casesWebhook.descriptionTextAreaFieldLabel": "Description", + "xpack.stackConnectors.components.casesWebhook.tagsFieldLabel": "Balises", + "xpack.stackConnectors.components.casesWebhook.titleFieldLabel": "Résumé (requis)", + "xpack.stackConnectors.components.casesWebhook.addHeaderButton": "Ajouter", + "xpack.stackConnectors.components.casesWebhook.addVariable": "Ajouter une variable", + "xpack.stackConnectors.components.casesWebhook.authenticationLabel": "Authentification", + "xpack.stackConnectors.components.casesWebhook.caseCommentDesc": "Commentaire de cas Kibana", + "xpack.stackConnectors.components.casesWebhook.caseDescriptionDesc": "Description de cas Kibana", + "xpack.stackConnectors.components.casesWebhook.caseTagsDesc": "Balises de cas Kibana", + "xpack.stackConnectors.components.casesWebhook.caseTitleDesc": "Titre de cas Kibana", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonHelp": "Objet JSON pour créer un commentaire. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonTextFieldLabel": "Objet de création de commentaire", + "xpack.stackConnectors.components.casesWebhook.createCommentMethodTextFieldLabel": "Méthode de création de commentaire", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlHelp": "URL de l'API pour ajouter un commentaire au cas.", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlTextFieldLabel": "URL de création de commentaire", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonHelpText": "Objet JSON pour créer un cas. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonTextFieldLabel": "Objet de création de cas", + "xpack.stackConnectors.components.casesWebhook.createIncidentMethodTextFieldLabel": "Méthode de création de cas", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyHelpText": "Clé JSON dans la réponse de création de cas qui contient l'ID de cas externe", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyTextFieldLabel": "Clé de cas pour la réponse de création de cas", + "xpack.stackConnectors.components.casesWebhook.createIncidentUrlTextFieldLabel": "URL de création de cas", + "xpack.stackConnectors.components.casesWebhook.deleteHeaderButton": "Supprimer", + "xpack.stackConnectors.components.casesWebhook.docLink": "Configuration de Webhook - Connecteur de gestion des cas.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentIncidentText": "L'objet de création de commentaire doit être un JSON valide.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentUrlText": "L'URL de création de commentaire doit être au format URL.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentText": "L'objet de création de cas est requis et doit être un JSON valide.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateUrlText": "L'URL de création de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentUrlText": "L'URL d'obtention de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateIncidentText": "L'objet de mise à jour de cas est requis et doit être un JSON valide.", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateUrlText": "L'URL de mise à jour de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.externalIdDesc": "ID du système externe", + "xpack.stackConnectors.components.casesWebhook.externalTitleDesc": "Titre du système externe", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyHelp": "Clé JSON dans la réponse d’obtention de cas qui contient le titre de cas externe", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyTextFieldLabel": "Clé de titre externe pour la réponse d’obtention de cas", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlHelp": "URL d’API pour le JSON de détails d’obtention de cas provenant d’un système externe. Utilisez le sélecteur de variable pour ajouter à l’URL l'ID du système externe.", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlTextFieldLabel": "URL d’obtention de cas", + "xpack.stackConnectors.components.casesWebhook.hasAuthSwitchLabel": "Demander une authentification pour ce webhook", + "xpack.stackConnectors.components.casesWebhook.httpHeadersTitle": "En-têtes utilisés", + "xpack.stackConnectors.components.casesWebhook.jsonCodeEditorAriaLabel": "Éditeur de code", + "xpack.stackConnectors.components.casesWebhook.jsonFieldLabel": "JSON", + "xpack.stackConnectors.components.casesWebhook.keyTextFieldLabel": "Clé", + "xpack.stackConnectors.components.casesWebhook.next": "Suivant", + "xpack.stackConnectors.components.casesWebhook.passwordTextFieldLabel": "Mot de passe", + "xpack.stackConnectors.components.casesWebhook.previous": "Précédent", + "xpack.stackConnectors.components.casesWebhook.selectMessageText": "Envoyer une requête à un service web de gestion de cas.", + "xpack.stackConnectors.components.casesWebhook.step1": "Configurer le connecteur", + "xpack.stackConnectors.components.casesWebhook.step2": "Créer un cas", + "xpack.stackConnectors.components.casesWebhook.step2Description": "Définissez les champs pour créer le cas dans le système externe. Consultez la documentation de l'API de votre service pour savoir quels sont les champs obligatoires", + "xpack.stackConnectors.components.casesWebhook.step3": "Informations sur l’obtention de cas", + "xpack.stackConnectors.components.casesWebhook.step3Description": "Définissez les champs pour ajouter des commentaires au cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour la création de mises à jour dans les cas. Consultez la documentation de l'API de votre service pour savoir quels sont les champs obligatoires.", + "xpack.stackConnectors.components.casesWebhook.step4": "Commentaires et mises à jour", + "xpack.stackConnectors.components.casesWebhook.step4a": "Créer une mise à jour dans le cas", + "xpack.stackConnectors.components.casesWebhook.step4aDescription": "Définissez les champs pour créer des mises à jour du cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour l’ajout de commentaires aux cas.", + "xpack.stackConnectors.components.casesWebhook.step4b": "Ajouter un commentaire dans le cas", + "xpack.stackConnectors.components.casesWebhook.step4bDescription": "Définissez les champs pour ajouter des commentaires au cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour la création de mises à jour dans les cas.", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonHelpl": "Objet JSON pour mettre à jour le cas. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonTextFieldLabel": "Objet de mise à jour de cas", + "xpack.stackConnectors.components.casesWebhook.updateIncidentMethodTextFieldLabel": "Méthode de mise à jour de cas", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlHelp": "URL d’API pour mettre à jour le cas.", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlTextFieldLabel": "URL de mise à jour du cas", + "xpack.stackConnectors.components.casesWebhook.userTextFieldLabel": "Nom d'utilisateur", + "xpack.stackConnectors.components.casesWebhook.valueTextFieldLabel": "Valeur", + "xpack.stackConnectors.components.casesWebhook.viewHeadersSwitch": "Ajouter un en-tête HTTP", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlHelp": "URL pour voir le cas dans le système externe. Utilisez le sélecteur de variable pour ajouter à l’URL l'ID ou le titre du système externe.", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlTextFieldLabel": "URL de visualisation de cas externe", + "xpack.stackConnectors.components.serviceNow.requiredShortDescTextField": "Une brève description est requise.", + "xpack.stackConnectors.components.email.exchangeForm.clientIdHelpLabel": "Configurer l'ID client", + "xpack.stackConnectors.components.email.exchangeForm.clientSecretHelpLabel": "Configurer l'identifiant client secret", + "xpack.stackConnectors.components.email.exchangeForm.tenantIdHelpLabel": "Configurer l'ID locataire", + "xpack.stackConnectors.components.email.connectorTypeTitle": "Envoyer vers la messagerie électronique", + "xpack.stackConnectors.components.email.amazonSesServerTypeLabel": "Amazon SES", + "xpack.stackConnectors.components.email.configureAccountsHelpLabel": "Configurer les comptes de messagerie électronique", + "xpack.stackConnectors.components.email.elasticCloudServerTypeLabel": "Elastic Cloud", + "xpack.stackConnectors.components.email.exchangeServerTypeLabel": "MS Exchange Server", + "xpack.stackConnectors.components.email.gmailServerTypeLabel": "Gmail", + "xpack.stackConnectors.components.email.otherServerTypeLabel": "Autre", + "xpack.stackConnectors.components.email.outlookServerTypeLabel": "Outlook", + "xpack.stackConnectors.components.email.selectMessageText": "Envoyez un e-mail à partir de votre serveur.", + "xpack.stackConnectors.components.email.updateErrorNotificationText": "Impossible d’obtenir la configuration du service", + "xpack.stackConnectors.components.index.error.badIndexOverrideSuffix": "L'index d'historique d'alertes doit contenir un suffixe valide.", + "xpack.stackConnectors.components.email.error.invalidPortText": "Le port n'est pas valide.", + "xpack.stackConnectors.components.email.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", + "xpack.stackConnectors.components.email.error.requiredClientIdText": "L'ID client est requis.", + "xpack.stackConnectors.components.index.error.requiredDocumentJson": "Le document est requis et doit être un objet JSON valide.", + "xpack.stackConnectors.components.email.error.requiredEntryText": "Aucune entrée À, Cc ou Cci. Au moins une entrée est requise.", + "xpack.stackConnectors.components.email.error.requiredFromText": "L'expéditeur est requis.", + "xpack.stackConnectors.components.email.error.requiredHostText": "L'hôte est requis.", + "xpack.stackConnectors.components.email.error.requiredMessageText": "Le message est requis.", + "xpack.stackConnectors.components.email.error.requiredPortText": "Le port est requis.", + "xpack.stackConnectors.components.serverLog.error.requiredServerLogMessageText": "Le message est requis.", + "xpack.stackConnectors.components.email.error.requiredServiceText": "Le service est requis.", + "xpack.stackConnectors.components.email.error.requiredSubjectText": "Le sujet est requis.", + "xpack.stackConnectors.components.email.error.requiredTenantIdText": "L'ID locataire est requis.", + "xpack.stackConnectors.components.webhook.error.requiredWebhookBodyText": "Le corps est requis.", + "xpack.stackConnectors.components.casesWebhook.error.requiredWebhookSummaryText": "Le titre est requis.", + "xpack.stackConnectors.components.index.connectorTypeTitle": "Données d'index", + "xpack.stackConnectors.components.index.configureIndexHelpLabel": "Configuration du connecteur d'index.", + "xpack.stackConnectors.components.index.connectorSectionTitle": "Écrire dans l'index", + "xpack.stackConnectors.components.index.definedateFieldTooltip": "Définissez ce champ temporel sur l'heure à laquelle le document a été indexé.", + "xpack.stackConnectors.components.index.defineTimeFieldLabel": "Définissez l'heure pour chaque document", + "xpack.stackConnectors.components.index.documentsFieldLabel": "Document à indexer", + "xpack.stackConnectors.components.index.error.notValidIndexText": "L’index n’est pas valide.", + "xpack.stackConnectors.components.index.executionTimeFieldLabel": "Champ temporel", + "xpack.stackConnectors.components.index.howToBroadenSearchQueryDescription": "Utilisez le caractère * pour élargir votre recherche.", + "xpack.stackConnectors.components.index.indexDocumentHelpLabel": "Exemple de document d'index.", + "xpack.stackConnectors.components.index.indicesToQueryLabel": "Index", + "xpack.stackConnectors.components.index.jsonDocAriaLabel": "Éditeur de code", + "xpack.stackConnectors.components.index.preconfiguredIndex": "Index Elasticsearch", + "xpack.stackConnectors.components.index.preconfiguredIndexDocLink": "Affichez les documents.", + "xpack.stackConnectors.components.index.refreshLabel": "Actualiser l'index", + "xpack.stackConnectors.components.index.refreshTooltip": "Actualisez les partitions affectées pour rendre cette opération visible pour la recherche.", + "xpack.stackConnectors.components.index.selectMessageText": "Indexez les données dans Elasticsearch.", + "xpack.stackConnectors.components.jira.connectorTypeTitle": "Jira", + "xpack.stackConnectors.components.jira.apiTokenTextFieldLabel": "Token d'API", + "xpack.stackConnectors.components.jira.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.jira.commentsTextAreaFieldLabel": "Commentaires supplémentaires", + "xpack.stackConnectors.components.jira.descriptionTextAreaFieldLabel": "Description", + "xpack.stackConnectors.components.jira.emailTextFieldLabel": "Adresse e-mail", + "xpack.stackConnectors.components.jira.impactSelectFieldLabel": "Étiquettes", + "xpack.stackConnectors.components.jira.labelsSpacesErrorMessage": "Les étiquettes ne peuvent pas contenir d'espaces.", + "xpack.stackConnectors.components.jira.parentIssueSearchLabel": "Problème parent", + "xpack.stackConnectors.components.jira.projectKey": "Clé de projet", + "xpack.stackConnectors.components.jira.requiredSummaryTextField": "Le résumé est requis.", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxAriaLabel": "Taper pour rechercher", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxPlaceholder": "Taper pour rechercher", + "xpack.stackConnectors.components.jira.searchIssuesLoading": "Chargement...", + "xpack.stackConnectors.components.jira.selectMessageText": "Créez un incident dans Jira.", + "xpack.stackConnectors.components.jira.severitySelectFieldLabel": "Priorité", + "xpack.stackConnectors.components.jira.summaryFieldLabel": "Résumé (requis)", + "xpack.stackConnectors.components.jira.unableToGetFieldsMessage": "Impossible d'obtenir les champs", + "xpack.stackConnectors.components.jira.unableToGetIssuesMessage": "Impossible d'obtenir les problèmes", + "xpack.stackConnectors.components.jira.unableToGetIssueTypesMessage": "Impossible d'obtenir les types d'erreurs", + "xpack.stackConnectors.components.jira.urgencySelectFieldLabel": "Type d'erreur", + "xpack.stackConnectors.components.pagerDuty.connectorTypeTitle": "Envoyer à PagerDuty", + "xpack.stackConnectors.components.pagerDuty.apiUrlInvalid": "URL d’API non valide", + "xpack.stackConnectors.components.pagerDuty.apiUrlTextFieldLabel": "URL de l'API (facultative)", + "xpack.stackConnectors.components.pagerDuty.classFieldLabel": "Classe (facultative)", + "xpack.stackConnectors.components.pagerDuty.componentTextFieldLabel": "Composant (facultatif)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextFieldLabel": "DedupKey (facultatif)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextRequiredFieldLabel": "DedupKey", + "xpack.stackConnectors.components.pagerDuty.error.requiredDedupKeyText": "DedupKey est requis lors de la résolution ou de la reconnaissance d'un incident.", + "xpack.stackConnectors.components.pagerDuty.error.requiredRoutingKeyText": "Une clé d'intégration / clé de routage est requise.", + "xpack.stackConnectors.components.pagerDuty.error.requiredSummaryText": "Le résumé est requis.", + "xpack.stackConnectors.components.pagerDuty.eventActionSelectFieldLabel": "Action de l'événement", + "xpack.stackConnectors.components.pagerDuty.eventSelectAcknowledgeOptionLabel": "Reconnaissance", + "xpack.stackConnectors.components.pagerDuty.eventSelectResolveOptionLabel": "Résoudre", + "xpack.stackConnectors.components.pagerDuty.eventSelectTriggerOptionLabel": "Déclencher", + "xpack.stackConnectors.components.pagerDuty.groupTextFieldLabel": "Regrouper (facultatif)", + "xpack.stackConnectors.components.pagerDuty.routingKeyNameHelpLabel": "Configurer un compte PagerDuty", + "xpack.stackConnectors.components.pagerDuty.routingKeyTextFieldLabel": "Clé d'intégration", + "xpack.stackConnectors.components.pagerDuty.selectMessageText": "Envoyez un événement dans PagerDuty.", + "xpack.stackConnectors.components.pagerDuty.severitySelectCriticalOptionLabel": "Critique", + "xpack.stackConnectors.components.pagerDuty.severitySelectErrorOptionLabel": "Erreur", + "xpack.stackConnectors.components.pagerDuty.severitySelectFieldLabel": "Sévérité (facultative)", + "xpack.stackConnectors.components.pagerDuty.severitySelectInfoOptionLabel": "Info", + "xpack.stackConnectors.components.pagerDuty.severitySelectWarningOptionLabel": "Avertissement", + "xpack.stackConnectors.components.pagerDuty.sourceTextFieldLabel": "Source (facultative)", + "xpack.stackConnectors.components.pagerDuty.summaryFieldLabel": "Résumé", + "xpack.stackConnectors.components.pagerDuty.timestampTextFieldLabel": "Horodatage (facultatif)", + "xpack.stackConnectors.components.resilient.connectorTypeTitle": "Résilient", + "xpack.stackConnectors.components.resilient.apiKeyId": "ID de clé d'API", + "xpack.stackConnectors.components.resilient.apiKeySecret": "Secret de clé d'API", + "xpack.stackConnectors.components.resilient.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.resilient.commentsTextAreaFieldLabel": "Commentaires supplémentaires", + "xpack.stackConnectors.components.resilient.descriptionTextAreaFieldLabel": "Description", + "xpack.stackConnectors.components.resilient.nameFieldLabel": "Nom (requis)", + "xpack.stackConnectors.components.resilient.orgId": "ID d'organisation", + "xpack.stackConnectors.components.resilient.requiredNameTextField": "Un nom est requis.", + "xpack.stackConnectors.components.resilient.selectMessageText": "Créez un incident dans IBM Resilient.", + "xpack.stackConnectors.components.resilient.severity": "Sévérité", + "xpack.stackConnectors.components.resilient.unableToGetIncidentTypesMessage": "Impossible d'obtenir les types d'incidents", + "xpack.stackConnectors.components.resilient.unableToGetSeverityMessage": "Impossible d'obtenir la sévérité", + "xpack.stackConnectors.components.resilient.urgencySelectFieldLabel": "Type d'incident", + "xpack.stackConnectors.components.serverLog.connectorTypeTitle": "Envoyer vers le log de serveur", + "xpack.stackConnectors.components.serverLog.logLevelFieldLabel": "Niveau", + "xpack.stackConnectors.components.serverLog.logMessageFieldLabel": "Message", + "xpack.stackConnectors.components.serverLog.selectMessageText": "Ajouter un message au log Kibana.", + "xpack.stackConnectors.components.serviceNow.apiUrlTextFieldLabel": "URL d'instance ServiceNow", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout": "Application Elastic ServiceNow non installée", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.content": "Veuillez vous rendre dans l'app store ServiceNow pour installer l'application", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.errorMessage": "Message d'erreur", + "xpack.stackConnectors.components.serviceNow.authenticationLabel": "Authentification", + "xpack.stackConnectors.components.serviceNow.cancelButtonText": "Annuler", + "xpack.stackConnectors.components.serviceNow.categoryTitle": "Catégorie", + "xpack.stackConnectors.components.serviceNow.clientIdTextFieldLabel": "ID client", + "xpack.stackConnectors.components.serviceNow.clientSecretTextFieldLabel": "Identifiant client secret", + "xpack.stackConnectors.components.serviceNow.commentsTextAreaFieldLabel": "Commentaires supplémentaires", + "xpack.stackConnectors.components.serviceNow.confirmButtonText": "Mettre à jour", + "xpack.stackConnectors.components.serviceNow.correlationDisplay": "Affichage de la corrélation (facultatif)", + "xpack.stackConnectors.components.serviceNow.correlationID": "ID corrélation (facultatif)", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutCreate": "ou créez-en un nouveau.", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutMigrate": "Supprimez ce connecteur", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutTitle": "Ce type de connecteur est déclassé", + "xpack.stackConnectors.components.serviceNow.descriptionTextAreaFieldLabel": "Description", + "xpack.stackConnectors.components.serviceNow.eventClassTextAreaFieldLabel": "Instance source", + "xpack.stackConnectors.components.serviceNow.fetchErrorMsg": "Impossible de récupérer. Vérifiez l'URL ou la configuration CORS de votre instance ServiceNow.", + "xpack.stackConnectors.components.serviceNow.impactSelectFieldLabel": "Impact", + "xpack.stackConnectors.components.serviceNow.installationCalloutTitle": "Pour utiliser ce connecteur, installez d'abord l'application Elastic à partir de l'app store ServiceNow.", + "xpack.stackConnectors.components.serviceNow.invalidApiUrlTextField": "L'URL n'est pas valide.", + "xpack.stackConnectors.components.serviceNow.keyIdTextFieldLabel": "ID de clé du vérificateur JWT", + "xpack.stackConnectors.components.serviceNow.messageKeyTextAreaFieldLabel": "Clé de message", + "xpack.stackConnectors.components.serviceNow.metricNameTextAreaFieldLabel": "Nom de l'indicateur", + "xpack.stackConnectors.components.serviceNow.nodeTextAreaFieldLabel": "Nœud", + "xpack.stackConnectors.components.serviceNow.passwordTextFieldLabel": "Mot de passe", + "xpack.stackConnectors.components.serviceNow.prioritySelectFieldLabel": "Priorité", + "xpack.stackConnectors.components.serviceNow.privateKeyPassLabelHelpText": "Il est requis uniquement si vous avez défini un mot de passe sur votre clé privée", + "xpack.stackConnectors.components.serviceNow.privateKeyPassTextFieldLabel": "Mot de passe de clé privée", + "xpack.stackConnectors.components.serviceNow.privateKeyTextFieldLabel": "Clé privée", + "xpack.stackConnectors.components.serviceNow.requiredClientIdTextField": "L'ID client est requis.", + "xpack.stackConnectors.components.serviceNow.requiredKeyIdTextField": "L'ID de clé du vérificateur JWT est requis.", + "xpack.stackConnectors.components.serviceNow.requiredPrivateKeyTextField": "La clé privée est requise.", + "xpack.stackConnectors.components.serviceNow.requiredSeverityTextField": "La sévérité est requise.", + "xpack.stackConnectors.components.serviceNow.requiredUserIdentifierTextField": "L'identifiant de l'utilisateur est requis.", + "xpack.stackConnectors.components.serviceNow.requiredUsernameTextField": "Le nom d'utilisateur est requis.", + "xpack.stackConnectors.components.serviceNow.resourceTextAreaFieldLabel": "Ressource", + "xpack.stackConnectors.components.serviceNow.setupDevInstance": "configurer une instance de développeur", + "xpack.stackConnectors.components.serviceNow.severityRequiredSelectFieldLabel": "Sévérité (requise)", + "xpack.stackConnectors.components.serviceNow.severitySelectFieldLabel": "Sévérité", + "xpack.stackConnectors.components.serviceNow.snInstanceLabel": "Instance ServiceNow", + "xpack.stackConnectors.components.serviceNow.sourceTextAreaFieldLabel": "Source", + "xpack.stackConnectors.components.serviceNow.subcategoryTitle": "Sous-catégorie", + "xpack.stackConnectors.components.serviceNow.title": "Incident", + "xpack.stackConnectors.components.serviceNow.titleFieldLabel": "Brève description (requise)", + "xpack.stackConnectors.components.serviceNow.typeTextAreaFieldLabel": "Type", + "xpack.stackConnectors.components.serviceNow.unableToGetChoicesMessage": "Impossible d'obtenir les choix", + "xpack.stackConnectors.components.serviceNow.unknown": "INCONNU", + "xpack.stackConnectors.components.serviceNow.updateCalloutText": "Le connecteur a été mis à jour.", + "xpack.stackConnectors.components.serviceNow.updateFormCredentialsTitle": "Fournir les informations d'authentification", + "xpack.stackConnectors.components.serviceNow.updateFormInstallTitle": "Installer l'application Elastic ServiceNow", + "xpack.stackConnectors.components.serviceNow.updateFormTitle": "Mettre à jour le connecteur ServiceNow", + "xpack.stackConnectors.components.serviceNow.updateFormUrlTitle": "Entrer votre URL d'instance ServiceNow", + "xpack.stackConnectors.components.serviceNow.urgencySelectFieldLabel": "Urgence", + "xpack.stackConnectors.components.serviceNow.useOAuth": "Utiliser l'authentification OAuth", + "xpack.stackConnectors.components.serviceNow.userEmailTextFieldLabel": "Identifiant de l'utilisateur", + "xpack.stackConnectors.components.serviceNow.usernameTextFieldLabel": "Nom d'utilisateur", + "xpack.stackConnectors.components.serviceNow.visitSNStore": "Visiter l'app store ServiceNow", + "xpack.stackConnectors.components.serviceNow.warningMessage": "Cette action mettra à jour toutes les instances de ce connecteur et ne pourra pas être annulée.", + "xpack.stackConnectors.components.serviceNow.correlationIDHelpLabel": "Identificateur pour les incidents de mise à jour", + "xpack.stackConnectors.components.serviceNowITOM.connectorTypeTitle": "ServiceNow ITOM", + "xpack.stackConnectors.components.serviceNowITOM.event": "Événement", + "xpack.stackConnectors.components.serviceNowITOM.selectMessageText": "Créez un événement dans ServiceNow ITOM.", + "xpack.stackConnectors.components.serviceNowITSM.connectorTypeTitle": "ServiceNow ITSM", + "xpack.stackConnectors.components.serviceNowITSM.selectMessageText": "Créez un incident dans ServiceNow ITSM.", + "xpack.stackConnectors.components.serviceNowSIR.connectorTypeTitle": "ServiceNow SecOps", + "xpack.stackConnectors.components.serviceNowSIR.selectMessageText": "Créez un incident dans ServiceNow SecOps.", + "xpack.stackConnectors.components.serviceNowSIR.title": "Incident de sécurité", + "xpack.stackConnectors.components.serviceNowSIR.correlationIDHelpLabel": "Identificateur pour les incidents de mise à jour", + "xpack.stackConnectors.components.slack.connectorTypeTitle": "Envoyer vers Slack", + "xpack.stackConnectors.components.slack.error.invalidWebhookUrlText": "L'URL de webhook n'est pas valide.", + "xpack.stackConnectors.components.slack.messageTextAreaFieldLabel": "Message", + "xpack.stackConnectors.components.slack.selectMessageText": "Envoyez un message à un canal ou à un utilisateur Slack.", + "xpack.stackConnectors.components.slack.webhookUrlHelpLabel": "Créer une URL de webhook Slack", + "xpack.stackConnectors.components.slack.webhookUrlTextFieldLabel": "URL de webhook", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationFieldsMessage": "Impossible d'obtenir les champs de l'application", + "xpack.stackConnectors.components.swimlane.connectorTypeTitle": "Créer l'enregistrement Swimlane", + "xpack.stackConnectors.components.swimlane.alertIdFieldLabel": "ID de l'alerte", + "xpack.stackConnectors.components.swimlane.apiTokenNameHelpLabel": "Fournir un token d'API Swimlane", + "xpack.stackConnectors.components.swimlane.apiTokenTextFieldLabel": "Token d'API", + "xpack.stackConnectors.components.swimlane.apiUrlTextFieldLabel": "URL d'API", + "xpack.stackConnectors.components.swimlane.appIdTextFieldLabel": "ID d'application", + "xpack.stackConnectors.components.swimlane.caseIdFieldLabel": "ID de cas", + "xpack.stackConnectors.components.swimlane.caseNameFieldLabel": "Nom de cas", + "xpack.stackConnectors.components.swimlane.commentsFieldLabel": "Commentaires", + "xpack.stackConnectors.components.swimlane.configureConnectionLabel": "Configurer la connexion de l'API", + "xpack.stackConnectors.components.swimlane.connectorType": "Type de connecteur", + "xpack.stackConnectors.components.swimlane.descriptionFieldLabel": "Description", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningDesc": "Ce connecteur ne peut pas être sélectionné, car il ne possède pas les mappings de champs d'alerte requis. Vous pouvez modifier ce connecteur pour ajouter les mappings de champs requis ou sélectionner un connecteur de type Alertes.", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningTitle": "Ce connecteur ne possède pas de mappings de champs", + "xpack.stackConnectors.components.swimlane.error.requiredAlertID": "L'ID d'alerte est requis.", + "xpack.stackConnectors.components.swimlane.error.requiredAppIdText": "Un ID d'application est requis.", + "xpack.stackConnectors.components.swimlane.error.requiredCaseID": "L'ID de cas est requis.", + "xpack.stackConnectors.components.swimlane.error.requiredCaseName": "Le nom de cas est requis.", + "xpack.stackConnectors.components.swimlane.error.requiredComments": "Les commentaires sont requis.", + "xpack.stackConnectors.components.swimlane.error.requiredDescription": "La description est requise.", + "xpack.stackConnectors.components.swimlane.error.requiredRuleName": "Le nom de règle est requis.", + "xpack.stackConnectors.components.swimlane.error.requiredSeverity": "La sévérité est requise.", + "xpack.stackConnectors.components.swimlane.invalidApiUrlTextField": "L'URL n'est pas valide.", + "xpack.stackConnectors.components.swimlane.mappingTitleTextFieldLabel": "Configurer les mappings de champs", + "xpack.stackConnectors.components.swimlane.nextStep": "Suivant", + "xpack.stackConnectors.components.swimlane.nextStepHelpText": "Si les mappings de champs ne sont pas configurés, le type de connecteur Swimlane sera défini sur Tous.", + "xpack.stackConnectors.components.swimlane.prevStep": "Retour", + "xpack.stackConnectors.components.swimlane.ruleNameFieldLabel": "Nom de règle", + "xpack.stackConnectors.components.swimlane.selectMessageText": "Créer un enregistrement dans Swimlane", + "xpack.stackConnectors.components.swimlane.severityFieldLabel": "Sévérité", + "xpack.stackConnectors.components.teams.connectorTypeTitle": "Envoyer un message à un canal Microsoft Teams.", + "xpack.stackConnectors.components.teams.error.invalidWebhookUrlText": "L'URL de webhook n'est pas valide.", + "xpack.stackConnectors.components.teams.error.requiredMessageText": "Le message est requis.", + "xpack.stackConnectors.components.teams.error.webhookUrlTextLabel": "URL de webhook", + "xpack.stackConnectors.components.teams.messageTextAreaFieldLabel": "Message", + "xpack.stackConnectors.components.teams.selectMessageText": "Envoyer un message à un canal Microsoft Teams.", + "xpack.stackConnectors.components.teams.webhookUrlHelpLabel": "Créer une URL de webhook Microsoft Teams", + "xpack.stackConnectors.components.webhook.connectorTypeTitle": "Données de webhook", + "xpack.stackConnectors.components.webhook.addHeaderButtonLabel": "Ajouter un en-tête", + "xpack.stackConnectors.components.webhook.authenticationLabel": "Authentification", + "xpack.stackConnectors.components.webhook.bodyCodeEditorAriaLabel": "Éditeur de code", + "xpack.stackConnectors.components.webhook.bodyFieldLabel": "Corps", + "xpack.stackConnectors.components.webhook.error.invalidUrlTextField": "L'URL n'est pas valide.", + "xpack.stackConnectors.components.webhook.hasAuthSwitchLabel": "Demander une authentification pour ce webhook", + "xpack.stackConnectors.components.webhook.headerKeyTextFieldLabel": "Clé", + "xpack.stackConnectors.components.webhook.headerValueTextFieldLabel": "Valeur", + "xpack.stackConnectors.components.webhook.methodTextFieldLabel": "Méthode", + "xpack.stackConnectors.components.webhook.passwordTextFieldLabel": "Mot de passe", + "xpack.stackConnectors.components.webhook.removeHeaderIconLabel": "Clé", + "xpack.stackConnectors.components.webhook.selectMessageText": "Envoyer une requête à un service Web.", + "xpack.stackConnectors.components.webhook.urlTextFieldLabel": "URL", + "xpack.stackConnectors.components.webhook.userTextFieldLabel": "Nom d'utilisateur", + "xpack.stackConnectors.components.webhook.viewHeadersSwitch": "Ajouter un en-tête HTTP", + "xpack.stackConnectors.components.xmatters.connectorTypeTitle": "Données xMatters", + "xpack.stackConnectors.components.xmatters.authenticationLabel": "Authentification", + "xpack.stackConnectors.components.xmatters.basicAuthButtonGroupLegend": "Authentification de base", + "xpack.stackConnectors.components.xmatters.basicAuthLabel": "Authentification de base", + "xpack.stackConnectors.components.xmatters.connectorSettingsLabel": "Sélectionnez la méthode d'authentification utilisée pour la configuration du déclencheur xMatters.", + "xpack.stackConnectors.components.xmatters.error.invalidUrlTextField": "L'URL n'est pas valide.", + "xpack.stackConnectors.components.xmatters.error.invalidUsernameTextField": "Nom d'utilisateur non valide.", + "xpack.stackConnectors.components.xmatters.error.requiredUrlText": "L'URL est requise.", + "xpack.stackConnectors.components.xmatters.initiationUrlHelpText": "Spécifiez l'URL xMatters complète.", + "xpack.stackConnectors.components.xmatters.passwordTextFieldLabel": "Mot de passe", + "xpack.stackConnectors.components.xmatters.selectMessageText": "Déclenchez un workflow xMatters.", + "xpack.stackConnectors.components.xmatters.severity": "Sévérité", + "xpack.stackConnectors.components.xmatters.severitySelectCriticalOptionLabel": "Critique", + "xpack.stackConnectors.components.xmatters.severitySelectHighOptionLabel": "Élevé", + "xpack.stackConnectors.components.xmatters.severitySelectLowOptionLabel": "Bas", + "xpack.stackConnectors.components.xmatters.severitySelectMediumOptionLabel": "Moyenne", + "xpack.stackConnectors.components.xmatters.severitySelectMinimalOptionLabel": "Minimale", + "xpack.stackConnectors.components.xmatters.tags": "Balises", + "xpack.stackConnectors.components.xmatters.urlAuthLabel": "Authentification de l'URL", + "xpack.stackConnectors.components.xmatters.urlLabel": "URL d'initiation", + "xpack.stackConnectors.components.xmatters.userCredsLabel": "Identifiants d'utilisateur", + "xpack.stackConnectors.components.xmatters.userTextFieldLabel": "Nom d'utilisateur", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningDesc": "Configurez les champs Create Comment URL et Create Comment Objects pour que le connecteur puisse partager les commentaires.", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningTitle": "Impossible de partager les commentaires du cas", + "xpack.stackConnectors.components.serviceNow.deprecatedTooltipTitle": "Connecteur déclassé", + "xpack.stackConnectors.components.casesWebhook.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentMethodText": "La méthode de création de commentaire est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentResponseKeyText": "La clé d’ID de cas pour la réponse de création de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateMethodText": "La méthode de création de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseCreatedKeyText": "La clé de date de création de la réponse d’obtention de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseExternalTitleKeyText": "La clé de titre du cas externe pour la réponse d’obtention de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseUpdatedKeyText": "La clé de date de mise à jour de la réponse d’obtention de cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentViewUrlKeyText": "L'URL de visualisation du cas est requise.", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateMethodText": "La méthode de mise à jour du cas est requise.", + "xpack.stackConnectors.components.webhook.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", + "xpack.stackConnectors.components.webhook.error.requiredMethodText": "La méthode est requise.", + "xpack.stackConnectors.components.email.addBccButton": "Cci", + "xpack.stackConnectors.components.email.addCcButton": "Cc", + "xpack.stackConnectors.components.email.authenticationLabel": "Authentification", + "xpack.stackConnectors.components.email.clientIdFieldLabel": "ID client", + "xpack.stackConnectors.components.email.clientSecretTextFieldLabel": "Identifiant client secret", + "xpack.stackConnectors.components.email.fromTextFieldLabel": "Expéditeur", + "xpack.stackConnectors.components.email.hasAuthSwitchLabel": "Demander une authentification pour ce serveur", + "xpack.stackConnectors.components.email.hostTextFieldLabel": "Hôte", + "xpack.stackConnectors.components.email.messageTextAreaFieldLabel": "Message", + "xpack.stackConnectors.components.email.passwordFieldLabel": "Mot de passe", + "xpack.stackConnectors.components.email.portTextFieldLabel": "Port", + "xpack.stackConnectors.components.email.recipientBccTextFieldLabel": "Cci", + "xpack.stackConnectors.components.email.recipientCopyTextFieldLabel": "Cc", + "xpack.stackConnectors.components.email.recipientTextFieldLabel": "À", + "xpack.stackConnectors.components.email.secureSwitchLabel": "Sécurisé", + "xpack.stackConnectors.components.email.serviceTextFieldLabel": "Service", + "xpack.stackConnectors.components.email.subjectTextFieldLabel": "Objet", + "xpack.stackConnectors.components.email.tenantIdFieldLabel": "ID locataire", + "xpack.stackConnectors.components.email.userTextFieldLabel": "Nom d'utilisateur", + "xpack.stackConnectors.components.index.resetDefaultIndexLabel": "Réinitialiser l'index par défaut", "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldCandidates": "{fieldCandidatesCount, plural, one {# candidat de champ identifié} other {# candidats de champs identifiés}}.", "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldValuePairs": "{fieldValuePairsCount, plural, one {# paire significative champ/valeur identifiée} other {# paires significatives champ/valeur identifiées}}.", "xpack.aiops.index.dataLoader.internalServerErrorMessage": "Erreur lors du chargement des données dans l'index {index}. {message}. La requête a peut-être expiré. Essayez d'utiliser un échantillon d'une taille inférieure ou de réduire la plage temporelle.", @@ -7169,7 +7542,6 @@ "xpack.apm.serviceGroups.selectServicesForm.preview": "Aperçu", "xpack.apm.serviceGroups.selectServicesForm.refresh": "Actualiser", "xpack.apm.serviceGroups.selectServicesForm.saveGroup": "Enregistrer le groupe", - "xpack.apm.serviceGroups.selectServicesForm.subtitle": "Utilisez une requête pour sélectionner les services pour ce groupe. Les services qui correspondent à cette requête dans les dernières 24 heures seront affectés au groupe.", "xpack.apm.serviceGroups.selectServicesForm.title": "Sélectionner des services", "xpack.apm.serviceGroups.selectServicesList.environmentColumnLabel": "Environnements", "xpack.apm.serviceGroups.selectServicesList.nameColumnLabel": "Nom", @@ -8912,7 +9284,6 @@ "xpack.cases.confirmDeleteCase.confirmQuestion": "Si vous supprimez {quantity, plural, =1 {ce cas} other {ces cas}}, toutes les données des cas connexes seront définitivement retirées et vous ne pourrez plus transmettre de données à un système de gestion des incidents externes. Voulez-vous vraiment continuer ?", "xpack.cases.confirmDeleteCase.deleteCase": "Supprimer {quantity, plural, =1 {le cas} other {les cas}}", "xpack.cases.confirmDeleteCase.deleteTitle": "Supprimer \"{caseTitle}\"", - "xpack.cases.confirmDeleteCase.selectedCases": "Supprimer \"{quantity, plural, =1 {{title}} other {{quantity} cas sélectionnés}}\"", "xpack.cases.connecors.get.missingCaseConnectorErrorMessage": "Le type d'objet \"{id}\" n'est pas enregistré.", "xpack.cases.connecors.register.duplicateCaseConnectorErrorMessage": "Le type d'objet \"{id}\" est déjà enregistré.", "xpack.cases.connectors.card.createCommentWarningDesc": "Configurez les champs Create Comment URL et Create Comment Objects pour que le connecteur {connectorName} puisse partager les commentaires.", @@ -8922,7 +9293,6 @@ "xpack.cases.connectors.cases.externalIncidentUpdated": "(mis à jour le {date} par {user})", "xpack.cases.connectors.jira.unableToGetIssueMessage": "Impossible d'obtenir le problème ayant l'ID {id}", "xpack.cases.containers.closedCases": "Fermeture de {totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases} cas}} effectuée", - "xpack.cases.containers.deletedCases": "Suppression de {totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases} cas}} effectuée", "xpack.cases.containers.markInProgressCases": "Marquage effectué de {totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases} cas}} comme étant en cours", "xpack.cases.containers.pushToExternalService": "Envoyé avec succès à { serviceName }", "xpack.cases.containers.reopenedCases": "Ouverture de {totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases} cas}} effectuée", @@ -8954,7 +9324,6 @@ "xpack.cases.caseTable.changeStatus": "Modifier le statut", "xpack.cases.caseTable.closed": "Fermé", "xpack.cases.caseTable.closedCases": "Cas fermés", - "xpack.cases.caseTable.delete": "Supprimer", "xpack.cases.caseTable.incidentSystem": "Système de gestion des incidents", "xpack.cases.caseTable.inProgressCases": "Cas en cours", "xpack.cases.caseTable.noCases.body": "Créer un cas ou modifiez vos filtres.", @@ -12510,9 +12879,7 @@ "xpack.fleet.unenrollAgents.forceDeleteMultipleTitle": "Désenregistrer {count} agents", "xpack.fleet.unenrollAgents.forceUnenrollCheckboxLabel": "Supprimer {count, plural, one {l'agent} other {les agents}} immédiatement. N'attendez pas que l'agent envoie les dernières données.", "xpack.fleet.unenrollAgents.forceUnenrollLegendText": "Forcer le désenregistrement {count, plural, one {de l'agent} other {des agents}}", - "xpack.fleet.upgradeAgents.bulkResultErrorResultsSummary": "Échec de {count} {count, plural, one {agent} other {agents}}", "xpack.fleet.upgradeAgents.hourLabel": "{option} {count, plural, one {heure} other {heures}}", - "xpack.fleet.upgradeAgents.successSingleNotificationTitle": "Mise à niveau de l'agent {count}", "xpack.fleet.upgradeAgents.upgradeMultipleDescription": "Cette action met à niveau plusieurs agents vers la version {version}. Impossible d'annuler cette action. Voulez-vous vraiment continuer ?", "xpack.fleet.upgradeAgents.upgradeSingleDescription": "Cette action met à niveau l'agent qui s'exécute sur \"{hostName}\" vers la version {version}. Impossible d'annuler cette action. Voulez-vous vraiment continuer ?", "xpack.fleet.upgradeAgents.warningCallout": "Les mises à niveau propagées sont uniquement disponible pour Elastic Agent à partir de la version {version}.", @@ -13415,7 +13782,6 @@ "xpack.fleet.unenrollAgents.unenrollFleetServerTitle": "Cet agent exécute le serveur Fleet", "xpack.fleet.updateAgentTags.errorNotificationTitle": "Échec de la mise à jour des balises", "xpack.fleet.updateAgentTags.successNotificationTitle": "Balises mises à jour", - "xpack.fleet.upgradeAgents.bulkResultAllErrorsNotificationTitle": "Erreur lors de la mise à niveau de {count, plural, one {l'agent} other {{count} agents} =true {tous les agents sélectionnés}}", "xpack.fleet.upgradeAgents.cancelButtonLabel": "Annuler", "xpack.fleet.upgradeAgents.chooseVersionLabel": "Mettre à niveau la version", "xpack.fleet.upgradeAgents.confirmMultipleButtonLabel": "Mettre à niveau {count, plural, one {l'agent} other {{count} agents} =true {tous les agents sélectionnés}}", @@ -13551,9 +13917,6 @@ "xpack.graph.icon.tachometer": "Tachymètre", "xpack.graph.icon.user": "Utilisateur", "xpack.graph.icon.users": "Utilisateurs", - "xpack.graph.inspect.requestTabTitle": "Requête", - "xpack.graph.inspect.responseTabTitle": "Réponse", - "xpack.graph.inspect.title": "Inspecter", "xpack.graph.leaveWorkspace.confirmButtonLabel": "Quitter", "xpack.graph.leaveWorkspace.confirmText": "Si vous quittez maintenant, vous perdez les modifications non enregistrées.", "xpack.graph.leaveWorkspace.modalTitle": "Modifications non enregistrées", @@ -15114,8 +15477,6 @@ "xpack.infra.deprecations.tiebreakerAdjustIndexing": "Ajustez votre indexation pour utiliser \"{field}\" comme moyen de départager.", "xpack.infra.deprecations.timestampAdjustIndexing": "Ajustez votre indexation pour utiliser \"{field}\" comme horodatage.", "xpack.infra.homePage.toolbar.showingLastOneMinuteDataText": "Dernières {duration} de données pour l'heure sélectionnée", - "xpack.infra.infrastructureMetricsExplorerPage.documentTitle": "{previousTitle} | Metrics Explorer", - "xpack.infra.infrastructureSnapshotPage.documentTitle": "{previousTitle} | Inventory", "xpack.infra.inventoryTimeline.header": "{metricLabel} moyen", "xpack.infra.kibanaMetrics.cloudIdMissingErrorMessage": "Le modèle de {metricId} nécessite un cloudId, mais aucun n'a été attribué à {nodeId}.", "xpack.infra.kibanaMetrics.invalidInfraMetricErrorMessage": "{id} n'est pas une valeur inframétrique valide", @@ -15155,7 +15516,6 @@ "xpack.infra.logs.searchResultTooltip": "{bucketCount, plural, one {# entrée mise en surbrillance} other {# entrées mises en surbrillance}}", "xpack.infra.logs.showingEntriesFromTimestamp": "Affichage des entrées à partir de {timestamp}", "xpack.infra.logs.showingEntriesUntilTimestamp": "Affichage des entrées jusqu'à {timestamp}", - "xpack.infra.logs.streamPage.documentTitle": "{previousTitle} | Flux", "xpack.infra.logs.viewInContext.logsFromContainerTitle": "Les logs affichés proviennent du conteneur {container}", "xpack.infra.logs.viewInContext.logsFromFileTitle": "Les logs affichés proviennent du fichier {file} et de l'hôte {host}", "xpack.infra.logSourceConfiguration.invalidMessageFieldTypeErrorMessage": "Le champ {messageField} doit être un champ textuel.", @@ -15164,8 +15524,7 @@ "xpack.infra.logSourceConfiguration.missingDataViewsLabel": "Vue de données {indexPatternId} manquante", "xpack.infra.logSourceConfiguration.missingMessageFieldErrorMessage": "La vue de données doit contenir un champ {messageField}.", "xpack.infra.logSourceErrorPage.savedObjectNotFoundErrorMessage": "Impossible de localiser ce {savedObjectType} : {savedObjectId}", - "xpack.infra.metricDetailPage.documentTitle": "Infrastructure | Indicateurs | {name}", - "xpack.infra.metricDetailPage.documentTitleError": "{previousTitle} | Oups", + "xpack.infra.metricDetailPage.documentTitleError": "Oups", "xpack.infra.metrics.alertFlyout.alertPerRedundantFilterError": "Il est possible que cette règle signale {matchedGroups} moins que prévu, car la requête de filtre comporte une correspondance pour {groupCount, plural, one {ce champ} other {ces champs}}. Pour en savoir plus, veuillez consulter {filteringAndGroupingLink}.", "xpack.infra.metrics.alertFlyout.ofExpression.helpTextDetail": "Vous ne trouvez pas d'indicateur ? {documentationLink}.", "xpack.infra.metrics.alerting.anomaly.summaryHigher": "{differential} x plus élevé", @@ -15319,7 +15678,6 @@ "xpack.infra.header.logsTitle": "Logs", "xpack.infra.header.observabilityTitle": "Observability", "xpack.infra.hideHistory": "Masquer l'historique", - "xpack.infra.homePage.documentTitle": "Indicateurs", "xpack.infra.homePage.inventoryTabTitle": "Inventory", "xpack.infra.homePage.metricsExplorerTabTitle": "Metrics Explorer", "xpack.infra.homePage.noMetricsIndicesInstructionsActionLabel": "Voir les instructions de configuration", @@ -17122,7 +17480,6 @@ "xpack.lens.configure.invalidReferenceLineDimension": "La ligne de référence est affectée à un axe qui n’existe plus. Vous pouvez déplacer cette ligne de référence vers un autre axe disponible ou la supprimer.", "xpack.lens.confirmModal.cancelButtonLabel": "Annuler", "xpack.lens.customBucketContainer.dragToReorder": "Faire glisser pour réorganiser", - "xpack.lens.dataPanelWrapper.switchDatasource": "Basculer vers la source de données", "xpack.lens.datatable.addLayer": "Visualisation", "xpack.lens.datatable.breakdownColumns": "Colonnes", "xpack.lens.datatable.breakdownColumns.description": "Divisez les colonnes d'indicateurs par champ. Il est recommandé de conserver un faible nombre de colonnes pour éviter le défilement horizontal.", @@ -25332,9 +25689,6 @@ "xpack.securitySolution.endpoint.resolver.relatedEventLimitTitle": "Cette liste inclut {numberOfEntries} événements de processus.", "xpack.securitySolution.endpointPolicyStatus.revisionNumber": "rév. {revNumber}", "xpack.securitySolution.endpointResponseActions.actionError.errorMessage": "{ errorCount, plural, =1 {Erreur rencontrée} other {Erreurs rencontrées}} :", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessage": "L'erreur suivante a été rencontrée : {error}", - "xpack.securitySolution.endpointResponseActions.killProcess.performApiErrorMessage": "L'erreur suivante a été rencontrée : {error}", - "xpack.securitySolution.endpointResponseActions.suspendProcess.performApiErrorMessage": "L'erreur suivante a été rencontrée : {error}", "xpack.securitySolution.event.reason.reasonRendererTitle": "Outil de rendu d'événement : {eventRendererName} ", "xpack.securitySolution.eventDetails.nestedColumnCheckboxAriaLabel": "Le champ {field} est un objet, et il est composé de champs imbriqués qui peuvent être ajoutés en tant que colonne", "xpack.securitySolution.eventDetails.viewColumnCheckboxAriaLabel": "Afficher la colonne {field}", @@ -25493,7 +25847,6 @@ "xpack.securitySolution.usersTable.rows": "{numRows} {numRows, plural, =0 {ligne} =1 {ligne} other {lignes}}", "xpack.securitySolution.usersTable.unit": "{totalCount, plural, =1 {utilisateur} other {utilisateurs}}", "xpack.securitySolution.accessibility.tooltipWithKeyboardShortcut.pressTooltipLabel": "Appuyer", - "xpack.securitySolution.actionLogButton.label": "Log des actions", "xpack.securitySolution.actionsContextMenu.label": "Ouvrir", "xpack.securitySolution.administration.os.linux": "Linux", "xpack.securitySolution.administration.os.macos": "Mac", @@ -27268,7 +27621,6 @@ "xpack.securitySolution.effectedPolicySelect.assignmentSectionTitle": "Affectation", "xpack.securitySolution.effectedPolicySelect.viewPolicyLinkLabel": "Afficher la politique", "xpack.securitySolution.emptyString.emptyStringDescription": "Chaîne vide", - "xpack.securitySolution.endpoint.actions.actionsLog": "Afficher le log d’actions", "xpack.securitySolution.endpoint.actions.agentDetails": "Afficher les détails de l'agent", "xpack.securitySolution.endpoint.actions.agentPolicy": "Afficher la politique de l'agent", "xpack.securitySolution.endpoint.actions.agentPolicyReassign": "Réaffecter la politique de l'agent", @@ -27736,7 +28088,6 @@ "xpack.securitySolution.endpointConsoleCommands.suspendProcess.commandArgAbout": "Commentaire qui doit accompagner l'action", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.entityId.arg.comment": "Un ID d’entité représentant le processus à suspendre", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.pid.arg.comment": "Un PID représentant le processus à suspendre", - "xpack.securitySolution.endpointDetails.activityLog": "Log d’actions", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.endOfLog": "Pas d'autre élément à afficher", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointIsolateAction": "n'a pas pu envoyer la requête : Isoler l'hôte", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointReleaseAction": "n'a pas pu envoyer la requête : Libérer l'hôte", @@ -27757,8 +28108,6 @@ "xpack.securitySolution.endpointManagement.noPermissionsSubText": "Vous devez disposer du rôle de superutilisateur pour utiliser cette fonctionnalité. Si vous ne disposez pas de ce rôle, ni d'autorisations pour modifier les rôles d'utilisateur, contactez votre administrateur Kibana.", "xpack.securitySolution.endpointManagemnet.noPermissionsText": "Vous ne disposez pas des autorisations Kibana requises pour utiliser Elastic Security Administration", "xpack.securitySolution.endpointPolicyStatus.tooltipTitleLabel": "Politique appliquée", - "xpack.securitySolution.endpointResponseActions.getProcesses.errorMessageTitle": "Échec de l’obtention des processus", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessageTitle": "Échec de l’exécution de l’action d’obtention des processus", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.command": "COMMANDE", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.enityId": "ID D’ENTITÉ", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.pid": "PID", @@ -31836,20 +32185,7 @@ "xpack.triggersActionsUI.actionVariables.legacyTagsLabel": "Cet élément a été déclassé au profit de {variable}.", "xpack.triggersActionsUI.checkActionTypeEnabled.actionTypeDisabledByLicenseMessage": "Ce connecteur requiert une licence {minimumLicenseRequired}.", "xpack.triggersActionsUI.checkRuleTypeEnabled.ruleTypeDisabledByLicenseMessage": "Ce type de règle requiert une licence {minimumLicenseRequired}.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.missingVariables": "{variableCount, plural, one {Variable obligatoire manquante} other {Variables obligatoires manquantes}} : {variables}", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideValue": "L'index d'historique d'alertes doit commencer par \"{alertHistoryPrefix}\".", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidEmail": "L'adresse e-mail {email} n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.notAllowed": "L'adresse e-mail {email} n'est pas autorisée.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexHelpText": "Les documents sont indexés dans l'index {alertHistoryIndex}. ", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueMessage": "Impossible d'obtenir le problème ayant l'ID {id}", "xpack.triggersActionsUI.components.builtinActionTypes.missingSecretsValuesLabel": "Les informations sensibles ne sont pas importées. Veuillez entrer {encryptedFieldsLength, plural, one {la valeur} other {les valeurs}} pour {encryptedFieldsLength, plural, one {le champ suivant} other {les champs suivants}} {secretFieldsLabel}.", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.invalidTimestamp": "L'horodatage doit être une date valide, telle que {nowShortFormat} ou {nowLongFormat}.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiInfoError": "Statut reçu : {status} lors de la tentative d'obtention d'informations sur l'application", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.appInstallationInfo": "{update} {create} ", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateSuccessToastTitle": "Connecteur {connectorName} mis à jour", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.apiUrlHelpLabel": "Fournissez l'URL complète vers l'instance ServiceNow souhaitée. Si vous n'en avez pas, {instance}.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.serviceNowAppRunning": "L'application Elastic de l'app store ServiceNow doit être installée avant d'exécuter la mise à jour. {visitLink} pour installer l'application", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationMessage": "Impossible d'obtenir l'application avec l'ID {id}", "xpack.triggersActionsUI.components.buttonGroupField.error.requiredField": "{label} est obligatoire.", "xpack.triggersActionsUI.components.deleteSelectedIdsErrorNotification.descriptionText": "Impossible de supprimer {numErrors, number} {numErrors, plural, one {{singleTitle}} other {{multipleTitle}}}", "xpack.triggersActionsUI.components.deleteSelectedIdsSuccessNotification.descriptionText": "Suppression de {numSuccesses, number} {numSuccesses, plural, one {{singleTitle}} other {{multipleTitle}}} effectuée", @@ -32005,340 +32341,6 @@ "xpack.triggersActionsUI.components.addMessageVariables.addRuleVariableTitle": "Ajouter une variable de règle", "xpack.triggersActionsUI.components.addMessageVariables.addVariablePopoverButton": "Ajouter une variable", "xpack.triggersActionsUI.components.alertTable.useFetchAlerts.errorMessageText": "Une erreur s'est produite lors de la recherche des alertes", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.commentsTextAreaFieldLabel": "Commentaires supplémentaires", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.descriptionTextAreaFieldLabel": "Description", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.tagsFieldLabel": "Balises", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.titleFieldLabel": "Résumé (requis)", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.actionTypeTitle": "Webhook - Données de gestion des cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addHeaderButton": "Ajouter", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addVariable": "Ajouter une variable", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseCommentDesc": "Commentaire de cas Kibana", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseDescriptionDesc": "Description de cas Kibana", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTagsDesc": "Balises de cas Kibana", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTitleDesc": "Titre de cas Kibana", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonHelp": "Objet JSON pour créer un commentaire. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonTextFieldLabel": "Objet de création de commentaire", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentMethodTextFieldLabel": "Méthode de création de commentaire", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlHelp": "URL de l'API pour ajouter un commentaire au cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlTextFieldLabel": "URL de création de commentaire", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonHelpText": "Objet JSON pour créer un cas. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonTextFieldLabel": "Objet de création de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentMethodTextFieldLabel": "Méthode de création de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyHelpText": "Clé JSON dans la réponse de création de cas qui contient l'ID de cas externe", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyTextFieldLabel": "Clé de cas pour la réponse de création de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentUrlTextFieldLabel": "URL de création de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.deleteHeaderButton": "Supprimer", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.docLink": "Configuration de Webhook - Connecteur de gestion des cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentIncidentText": "L'objet de création de commentaire doit être un JSON valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentUrlText": "L'URL de création de commentaire doit être au format URL.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateIncidentText": "L'objet de création de cas est requis et doit être un JSON valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateUrlText": "L'URL de création de cas est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredGetIncidentUrlText": "L'URL d'obtention de cas est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateIncidentText": "L'objet de mise à jour de cas est requis et doit être un JSON valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateUrlText": "L'URL de mise à jour de cas est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalIdDesc": "ID du système externe", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalTitleDesc": "Titre du système externe", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyHelp": "Clé JSON dans la réponse d’obtention de cas qui contient le titre de cas externe", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyTextFieldLabel": "Clé de titre externe pour la réponse d’obtention de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlHelp": "URL d’API pour le JSON de détails d’obtention de cas provenant d’un système externe. Utilisez le sélecteur de variable pour ajouter à l’URL l'ID du système externe.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlTextFieldLabel": "URL d’obtention de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.hasAuthSwitchLabel": "Demander une authentification pour ce webhook", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.httpHeadersTitle": "En-têtes utilisés", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonCodeEditorAriaLabel": "Éditeur de code", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonFieldLabel": "JSON", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.keyTextFieldLabel": "Clé", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.next": "Suivant", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.passwordTextFieldLabel": "Mot de passe", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.previous": "Précédent", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.selectMessageText": "Envoyer une requête à un service web de gestion de cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step1": "Configurer le connecteur", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2": "Créer un cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2Description": "Définissez les champs pour créer le cas dans le système externe. Consultez la documentation de l'API de votre service pour savoir quels sont les champs obligatoires", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3": "Informations sur l’obtention de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3Description": "Définissez les champs pour ajouter des commentaires au cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour la création de mises à jour dans les cas. Consultez la documentation de l'API de votre service pour savoir quels sont les champs obligatoires.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4": "Commentaires et mises à jour", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4a": "Créer une mise à jour dans le cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4aDescription": "Définissez les champs pour créer des mises à jour du cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour l’ajout de commentaires aux cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4b": "Ajouter un commentaire dans le cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4bDescription": "Définissez les champs pour ajouter des commentaires au cas dans le système externe. Pour certains systèmes, cela peut être la même méthode que pour la création de mises à jour dans les cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonHelpl": "Objet JSON pour mettre à jour le cas. Utilisez le sélecteur de variable pour ajouter des données de cas à la charge de travail.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonTextFieldLabel": "Objet de mise à jour de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentMethodTextFieldLabel": "Méthode de mise à jour de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlHelp": "URL d’API pour mettre à jour le cas.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlTextFieldLabel": "URL de mise à jour du cas", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.userTextFieldLabel": "Nom d'utilisateur", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.valueTextFieldLabel": "Valeur", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewHeadersSwitch": "Ajouter un en-tête HTTP", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlHelp": "URL pour voir le cas dans le système externe. Utilisez le sélecteur de variable pour ajouter à l’URL l'ID ou le titre du système externe.", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlTextFieldLabel": "URL de visualisation de cas externe", - "xpack.triggersActionsUI.components.builtinActionTypes.common.requiredShortDescTextField": "Une brève description est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientIdHelpLabel": "Configurer l'ID client", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientSecretHelpLabel": "Configurer l'identifiant client secret", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.tenantIdHelpLabel": "Configurer l'ID locataire", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.actionTypeTitle": "Envoyer vers la messagerie électronique", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.amazonSesServerTypeLabel": "Amazon SES", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.configureAccountsHelpLabel": "Configurer les comptes de messagerie électronique", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.elasticCloudServerTypeLabel": "Elastic Cloud", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.exchangeServerTypeLabel": "MS Exchange Server", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.gmailServerTypeLabel": "Gmail", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.otherServerTypeLabel": "Autre", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.outlookServerTypeLabel": "Outlook", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.selectMessageText": "Envoyez un e-mail à partir de votre serveur.", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.updateErrorNotificationText": "Impossible d’obtenir la configuration du service", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideSuffix": "L'index d'historique d'alertes doit contenir un suffixe valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidPortText": "Le port n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredClientIdText": "L'ID client est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredDocumentJson": "Le document est requis et doit être un objet JSON valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredEntryText": "Aucune entrée À, Cc ou Cci. Au moins une entrée est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredFromText": "L'expéditeur est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredHostText": "L'hôte est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredMessageText": "Le message est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredPortText": "Le port est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServerLogMessageText": "Le message est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServiceText": "Le service est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSlackMessageText": "Le message est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSubjectText": "Le sujet est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredTenantIdText": "L'ID locataire est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookBodyText": "Le corps est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookSummaryText": "Le titre est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.actionTypeTitle": "Données d'index", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.chooseLabel": "Choisir…", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.configureIndexHelpLabel": "Configuration du connecteur d'index.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.connectorSectionTitle": "Écrire dans l'index", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.definedateFieldTooltip": "Définissez ce champ temporel sur l'heure à laquelle le document a été indexé.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.defineTimeFieldLabel": "Définissez l'heure pour chaque document", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel": "Document à indexer", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.error.notValidIndexText": "L’index n’est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.executionTimeFieldLabel": "Champ temporel", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.howToBroadenSearchQueryDescription": "Utilisez le caractère * pour élargir votre recherche.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indexDocumentHelpLabel": "Exemple de document d'index.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesAndIndexPatternsLabel": "Basé sur vos vues de données", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesToQueryLabel": "Index", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel": "Éditeur de code", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndex": "Index Elasticsearch", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexDocLink": "Affichez les documents.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshLabel": "Actualiser l'index", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshTooltip": "Actualisez les partitions affectées pour rendre cette opération visible pour la recherche.", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.selectMessageText": "Indexez les données dans Elasticsearch.", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.actionTypeTitle": "Jira", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiTokenTextFieldLabel": "Token d'API", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.commentsTextAreaFieldLabel": "Commentaires supplémentaires", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.descriptionTextAreaFieldLabel": "Description", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.emailTextFieldLabel": "Adresse e-mail", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.impactSelectFieldLabel": "Étiquettes", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.labelsSpacesErrorMessage": "Les étiquettes ne peuvent pas contenir d'espaces.", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.parentIssueSearchLabel": "Problème parent", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.projectKey": "Clé de projet", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.requiredSummaryTextField": "Le résumé est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxAriaLabel": "Taper pour rechercher", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxPlaceholder": "Taper pour rechercher", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesLoading": "Chargement...", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.selectMessageText": "Créez un incident dans Jira.", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.severitySelectFieldLabel": "Priorité", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.summaryFieldLabel": "Résumé (requis)", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetFieldsMessage": "Impossible d'obtenir les champs", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssuesMessage": "Impossible d'obtenir les problèmes", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueTypesMessage": "Impossible d'obtenir les types d'erreurs", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.urgencySelectFieldLabel": "Type d'erreur", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.actionTypeTitle": "Envoyer à PagerDuty", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlInvalid": "URL d’API non valide", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlTextFieldLabel": "URL de l'API (facultative)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.classFieldLabel": "Classe (facultative)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.componentTextFieldLabel": "Composant (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextFieldLabel": "DedupKey (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextRequiredFieldLabel": "DedupKey", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredDedupKeyText": "DedupKey est requis lors de la résolution ou de la reconnaissance d'un incident.", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredRoutingKeyText": "Une clé d'intégration / clé de routage est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredSummaryText": "Le résumé est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventActionSelectFieldLabel": "Action de l'événement", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectAcknowledgeOptionLabel": "Reconnaissance", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectResolveOptionLabel": "Résoudre", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectTriggerOptionLabel": "Déclencher", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.groupTextFieldLabel": "Regrouper (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyNameHelpLabel": "Configurer un compte PagerDuty", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyTextFieldLabel": "Clé d'intégration", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.selectMessageText": "Envoyez un événement dans PagerDuty.", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectCriticalOptionLabel": "Critique", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectErrorOptionLabel": "Erreur", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectFieldLabel": "Sévérité (facultative)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectInfoOptionLabel": "Info", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectWarningOptionLabel": "Avertissement", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.sourceTextFieldLabel": "Source (facultative)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.summaryFieldLabel": "Résumé", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.timestampTextFieldLabel": "Horodatage (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.actionTypeTitle": "Résilient", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeyId": "ID de clé d'API", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeySecret": "Secret de clé d'API", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.commentsTextAreaFieldLabel": "Commentaires supplémentaires", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.descriptionTextAreaFieldLabel": "Description", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.nameFieldLabel": "Nom (requis)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.orgId": "ID d'organisation", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredNameTextField": "Un nom est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.selectMessageText": "Créez un incident dans IBM Resilient.", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.severity": "Sévérité", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetIncidentTypesMessage": "Impossible d'obtenir les types d'incidents", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetSeverityMessage": "Impossible d'obtenir la sévérité", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.urgencySelectFieldLabel": "Type d'incident", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.actionTypeTitle": "Envoyer vers le log de serveur", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logLevelFieldLabel": "Niveau", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logMessageFieldLabel": "Message", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.selectMessageText": "Ajouter un message au log Kibana.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiUrlTextFieldLabel": "URL d'instance ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout": "Application Elastic ServiceNow non installée", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.content": "Veuillez vous rendre dans l'app store ServiceNow pour installer l'application", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.errorMessage": "Message d'erreur", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.cancelButtonText": "Annuler", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.categoryTitle": "Catégorie", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientIdTextFieldLabel": "ID client", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientSecretTextFieldLabel": "Identifiant client secret", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.commentsTextAreaFieldLabel": "Commentaires supplémentaires", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.confirmButtonText": "Mettre à jour", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationDisplay": "Affichage de la corrélation (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationID": "ID corrélation (facultatif)", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutCreate": "ou créez-en un nouveau.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutMigrate": "Supprimez ce connecteur", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutTitle": "Ce type de connecteur est déclassé", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.descriptionTextAreaFieldLabel": "Description", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.eventClassTextAreaFieldLabel": "Instance source", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.fetchErrorMsg": "Impossible de récupérer. Vérifiez l'URL ou la configuration CORS de votre instance ServiceNow.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.impactSelectFieldLabel": "Impact", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.installationCalloutTitle": "Pour utiliser ce connecteur, installez d'abord l'application Elastic à partir de l'app store ServiceNow.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.invalidApiUrlTextField": "L'URL n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.keyIdTextFieldLabel": "ID de clé du vérificateur JWT", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.messageKeyTextAreaFieldLabel": "Clé de message", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.metricNameTextAreaFieldLabel": "Nom de l'indicateur", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.nodeTextAreaFieldLabel": "Nœud", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.passwordTextFieldLabel": "Mot de passe", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.prioritySelectFieldLabel": "Priorité", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassLabelHelpText": "Il est requis uniquement si vous avez défini un mot de passe sur votre clé privée", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassTextFieldLabel": "Mot de passe de clé privée", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyTextFieldLabel": "Clé privée", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredClientIdTextField": "L'ID client est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredKeyIdTextField": "L'ID de clé du vérificateur JWT est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredPrivateKeyTextField": "La clé privée est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredSeverityTextField": "La sévérité est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUserIdentifierTextField": "L'identifiant de l'utilisateur est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUsernameTextField": "Le nom d'utilisateur est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.resourceTextAreaFieldLabel": "Ressource", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.setupDevInstance": "configurer une instance de développeur", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severityRequiredSelectFieldLabel": "Sévérité (requise)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severitySelectFieldLabel": "Sévérité", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.snInstanceLabel": "Instance ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.sourceTextAreaFieldLabel": "Source", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.subcategoryTitle": "Sous-catégorie", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.title": "Incident", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.titleFieldLabel": "Brève description (requise)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.typeTextAreaFieldLabel": "Type", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unableToGetChoicesMessage": "Impossible d'obtenir les choix", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unknown": "INCONNU", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateCalloutText": "Le connecteur a été mis à jour.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormCredentialsTitle": "Fournir les informations d'authentification", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormInstallTitle": "Installer l'application Elastic ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormTitle": "Mettre à jour le connecteur ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormUrlTitle": "Entrer votre URL d'instance ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.urgencySelectFieldLabel": "Urgence", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.useOAuth": "Utiliser l'authentification OAuth", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.userEmailTextFieldLabel": "Identifiant de l'utilisateur", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.usernameTextFieldLabel": "Nom d'utilisateur", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.visitSNStore": "Visiter l'app store ServiceNow", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.warningMessage": "Cette action mettra à jour toutes les instances de ce connecteur et ne pourra pas être annulée.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.correlationIDHelpLabel": "Identificateur pour les incidents de mise à jour", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.actionTypeTitle": "ServiceNow ITOM", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowITOM.event": "Événement", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.selectMessageText": "Créez un événement dans ServiceNow ITOM.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.actionTypeTitle": "ServiceNow ITSM", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.selectMessageText": "Créez un incident dans ServiceNow ITSM.", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.actionTypeTitle": "ServiceNow SecOps", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.selectMessageText": "Créez un incident dans ServiceNow SecOps.", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowSIR.title": "Incident de sécurité", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIRAction.correlationIDHelpLabel": "Identificateur pour les incidents de mise à jour", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.actionTypeTitle": "Envoyer vers Slack", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.error.invalidWebhookUrlText": "L'URL de webhook n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.messageTextAreaFieldLabel": "Message", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.selectMessageText": "Envoyez un message à un canal ou à un utilisateur Slack.", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlHelpLabel": "Créer une URL de webhook Slack", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlTextFieldLabel": "URL de webhook", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationFieldsMessage": "Impossible d'obtenir les champs de l'application", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.actionTypeTitle": "Créer l'enregistrement Swimlane", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.alertIdFieldLabel": "ID de l'alerte", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenNameHelpLabel": "Fournir un token d'API Swimlane", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenTextFieldLabel": "Token d'API", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiUrlTextFieldLabel": "URL d'API", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.appIdTextFieldLabel": "ID d'application", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseIdFieldLabel": "ID de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseNameFieldLabel": "Nom de cas", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.commentsFieldLabel": "Commentaires", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.configureConnectionLabel": "Configurer la connexion de l'API", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.connectorType": "Type de connecteur", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.descriptionFieldLabel": "Description", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningDesc": "Ce connecteur ne peut pas être sélectionné, car il ne possède pas les mappings de champs d'alerte requis. Vous pouvez modifier ce connecteur pour ajouter les mappings de champs requis ou sélectionner un connecteur de type Alertes.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningTitle": "Ce connecteur ne possède pas de mappings de champs", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAlertID": "L'ID d'alerte est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAppIdText": "Un ID d'application est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseID": "L'ID de cas est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseName": "Le nom de cas est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredComments": "Les commentaires sont requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredDescription": "La description est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredRuleName": "Le nom de règle est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredSeverity": "La sévérité est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.invalidApiUrlTextField": "L'URL n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.mappingTitleTextFieldLabel": "Configurer les mappings de champs", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStep": "Suivant", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStepHelpText": "Si les mappings de champs ne sont pas configurés, le type de connecteur Swimlane sera défini sur Tous.", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.prevStep": "Retour", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.ruleNameFieldLabel": "Nom de règle", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.selectMessageText": "Créer un enregistrement dans Swimlane", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.severityFieldLabel": "Sévérité", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.actionTypeTitle": "Envoyer un message à un canal Microsoft Teams.", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.invalidWebhookUrlText": "L'URL de webhook n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.requiredMessageText": "Le message est requis.", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.webhookUrlTextLabel": "URL de webhook", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.messageTextAreaFieldLabel": "Message", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.selectMessageText": "Envoyer un message à un canal Microsoft Teams.", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.webhookUrlHelpLabel": "Créer une URL de webhook Microsoft Teams", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.actionTypeTitle": "Données de webhook", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.addHeaderButtonLabel": "Ajouter un en-tête", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyCodeEditorAriaLabel": "Éditeur de code", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyFieldLabel": "Corps", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.error.invalidUrlTextField": "L'URL n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.hasAuthSwitchLabel": "Demander une authentification pour ce webhook", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerKeyTextFieldLabel": "Clé", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerValueTextFieldLabel": "Valeur", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.methodTextFieldLabel": "Méthode", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.passwordTextFieldLabel": "Mot de passe", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.removeHeaderIconLabel": "Clé", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.selectMessageText": "Envoyer une requête à un service Web.", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.urlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.userTextFieldLabel": "Nom d'utilisateur", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.viewHeadersSwitch": "Ajouter un en-tête HTTP", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.actionTypeTitle": "Données xMatters", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthButtonGroupLegend": "Authentification de base", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthLabel": "Authentification de base", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.connectorSettingsLabel": "Sélectionnez la méthode d'authentification utilisée pour la configuration du déclencheur xMatters.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUrlTextField": "L'URL n'est pas valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUsernameTextField": "Nom d'utilisateur non valide.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.requiredUrlText": "L'URL est requise.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.initiationUrlHelpText": "Spécifiez l'URL xMatters complète.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.passwordTextFieldLabel": "Mot de passe", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.selectMessageText": "Déclenchez un workflow xMatters.", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severity": "Sévérité", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectCriticalOptionLabel": "Critique", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectHighOptionLabel": "Élevé", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectLowOptionLabel": "Bas", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMediumOptionLabel": "Moyenne", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMinimalOptionLabel": "Minimale", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.tags": "Balises", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlAuthLabel": "Authentification de l'URL", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlLabel": "URL d'initiation", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userCredsLabel": "Identifiants d'utilisateur", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userTextFieldLabel": "Nom d'utilisateur", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorButtonLabel": "Créer un connecteur", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyBody": "Configurer les services de messagerie électronique, Slack, Elasticsearch et tiers que Kibana exécute.", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyTitle": "Créer votre premier connecteur", @@ -32360,8 +32362,6 @@ "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorMessage": "L'éditeur est introuvable. Veuillez actualiser la page et réessayer", "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorTitle": "Impossible d'ajouter une variable de message", "xpack.triggersActionsUI.components.simpleConnectorForm.secrets.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningDesc": "Configurez les champs Create Comment URL et Create Comment Objects pour que le connecteur puisse partager les commentaires.", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningTitle": "Impossible de partager les commentaires du cas", "xpack.triggersActionsUI.connectors.breadcrumbTitle": "Connecteurs", "xpack.triggersActionsUI.data.coreQueryParams.dateStartGTdateEndErrorMessage": "[dateStart] : est postérieure à [dateEnd]", "xpack.triggersActionsUI.data.coreQueryParams.intervalRequiredErrorMessage": "[interval] : doit être spécifié si [dateStart] n'est pas égale à [dateEnd]", @@ -32422,7 +32422,6 @@ "xpack.triggersActionsUI.ruleSnoozeScheduler.saveSchedule": "Enregistrer le calendrier", "xpack.triggersActionsUI.ruleSnoozeScheduler.timezoneLabel": "Fuseau horaire", "xpack.triggersActionsUI.sections.actionConnectorAdd.backButtonLabel": "Retour", - "xpack.triggersActionsUI.sections.actionConnectorAdd.cancelButtonLabel": "Annuler", "xpack.triggersActionsUI.sections.actionConnectorAdd.manageLicensePlanBannerLinkTitle": "Gérer la licence", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveAndTestButtonLabel": "Enregistrer et tester", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveButtonLabel": "Enregistrer", @@ -32435,7 +32434,6 @@ "xpack.triggersActionsUI.sections.actionConnectorForm.loadingConnectorSettingsDescription": "Chargement des paramètres du connecteur…", "xpack.triggersActionsUI.sections.actionForm.actionSectionsTitle": "Actions", "xpack.triggersActionsUI.sections.actionForm.addActionButtonLabel": "Ajouter une action", - "xpack.triggersActionsUI.sections.actionForm.deprecatedTooltipTitle": "Connecteur déclassé", "xpack.triggersActionsUI.sections.actionForm.getMoreConnectorsTitle": "Obtenir davantage de connecteurs", "xpack.triggersActionsUI.sections.actionForm.getMoreRuleTypesTitle": "Obtenir davantage de types de règles", "xpack.triggersActionsUI.sections.actionForm.incidentManagementSystemLabel": "Système de gestion des incidents", @@ -32474,17 +32472,6 @@ "xpack.triggersActionsUI.sections.actionTypeForm.actionErrorToolTip": "L’action contient des erreurs.", "xpack.triggersActionsUI.sections.actionTypeForm.actionRunWhenInActionGroup": "Exécuter quand", "xpack.triggersActionsUI.sections.actionTypeForm.addNewConnectorEmptyButton": "Ajouter un connecteur", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateCommentMethodText": "La méthode de création de commentaire est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateIncidentResponseKeyText": "La clé d’ID de cas pour la réponse de création de cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateMethodText": "La méthode de création de cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseCreatedKeyText": "La clé de date de création de la réponse d’obtention de cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseExternalTitleKeyText": "La clé de titre du cas externe pour la réponse d’obtention de cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseUpdatedKeyText": "La clé de date de mise à jour de la réponse d’obtention de cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentViewUrlKeyText": "L'URL de visualisation du cas est requise.", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredUpdateMethodText": "La méthode de mise à jour du cas est requise.", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredAuthUserNameText": "Le nom d'utilisateur est requis.", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredMethodText": "La méthode est requise.", "xpack.triggersActionsUI.sections.addConnectorForm.selectConnectorFlyoutTitle": "Sélectionner un connecteur", "xpack.triggersActionsUI.sections.addConnectorForm.updateSuccessNotificationText": "Création de \"{connectorName}\" effectuée", "xpack.triggersActionsUI.sections.addModalConnectorForm.cancelButtonLabel": "Annuler", @@ -32494,25 +32481,6 @@ "xpack.triggersActionsUI.sections.alertsTable.alertsFlyout.reason": "Raison", "xpack.triggersActionsUI.sections.alertsTable.column.actions": "Actions", "xpack.triggersActionsUI.sections.alertsTable.leadingControl.viewDetails": "Afficher les détails", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addBccButton": "Cci", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addCcButton": "Cc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.authenticationLabel": "Authentification", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientIdFieldLabel": "ID client", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientSecretTextFieldLabel": "Identifiant client secret", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.fromTextFieldLabel": "Expéditeur", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hasAuthSwitchLabel": "Demander une authentification pour ce serveur", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hostTextFieldLabel": "Hôte", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.messageTextAreaFieldLabel": "Message", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.passwordFieldLabel": "Mot de passe", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.portTextFieldLabel": "Port", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientBccTextFieldLabel": "Cci", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientCopyTextFieldLabel": "Cc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientTextFieldLabel": "À", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.secureSwitchLabel": "Sécurisé", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.serviceTextFieldLabel": "Service", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.subjectTextFieldLabel": "Objet", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.tenantIdFieldLabel": "ID locataire", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.userTextFieldLabel": "Nom d'utilisateur", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseCancelButtonText": "Annuler", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseConfirmButtonText": "Abandonner les modifications", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseMessage": "Vous ne pouvez pas récupérer de modifications non enregistrées.", @@ -32528,11 +32496,9 @@ "xpack.triggersActionsUI.sections.connectorAddInline.unableToLoadConnectorTitle'": "Impossible de charger le connecteur", "xpack.triggersActionsUI.sections.connectorAddInline.unauthorizedToCreateForEmptyConnectors": "Seuls les utilisateurs autorisés peuvent configurer un connecteur. Contactez votre administrateur.", "xpack.triggersActionsUI.sections.deprecatedTitleMessage": "(déclassé)", - "xpack.triggersActionsUI.sections.editConnectorForm.cancelButtonLabel": "Annuler", "xpack.triggersActionsUI.sections.editConnectorForm.descriptionText": "Ce connecteur est en lecture seule.", "xpack.triggersActionsUI.sections.editConnectorForm.flyoutPreconfiguredTitle": "Modifier un connecteur", "xpack.triggersActionsUI.sections.editConnectorForm.preconfiguredHelpLabel": "En savoir plus sur les connecteurs préconfigurés.", - "xpack.triggersActionsUI.sections.editConnectorForm.saveAndCloseButtonLabel": "Enregistrer et fermer", "xpack.triggersActionsUI.sections.editConnectorForm.saveButtonLabel": "Enregistrer", "xpack.triggersActionsUI.sections.editConnectorForm.tabText": "Configuration", "xpack.triggersActionsUI.sections.editConnectorForm.updateErrorNotificationText": "Impossible de mettre à jour un connecteur.", @@ -32563,7 +32529,6 @@ "xpack.triggersActionsUI.sections.ruleDetails.alertsList.ruleTypeExcessDurationMessage": "La durée dépasse le temps d'exécution attendu de la règle.", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.activeLabel": "Actif", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.allAlertsLabel": "Toutes les alertes", - "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.recentAlertHistoryTitle": "Historique récent des alertes", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.title": "Alertes", "xpack.triggersActionsUI.sections.ruleDetails.deleteRuleButtonLabel": "Supprimer la règle", "xpack.triggersActionsUI.sections.ruleDetails.disableRuleButtonLabel": "Désactiver", @@ -32704,7 +32669,6 @@ "xpack.triggersActionsUI.sections.rulesList.removeAllButton": "Tout supprimer", "xpack.triggersActionsUI.sections.rulesList.removeCancelButton": "Annuler", "xpack.triggersActionsUI.sections.rulesList.removeConfirmButton": "Tout supprimer", - "xpack.triggersActionsUI.sections.rulesList.resetDefaultIndexLabel": "Réinitialiser l'index par défaut", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDecrypting": "Une erreur s'est produite lors du déchiffrement de la règle.", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDisabled": "La règle n'a pas pu s'exécuter, car elle a été lancée après sa désactivation.", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonLicense": "Impossible d'exécuter la règle", diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 95f9d1a2494be..0aa5fa39b93e0 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -986,7 +986,6 @@ "dashboard.panel.copyToDashboard.goToDashboard": "コピーしてダッシュボードを開く", "dashboard.panel.copyToDashboard.newDashboardOptionLabel": "新規ダッシュボード", "dashboard.panel.copyToDashboard.title": "ダッシュボードにコピー", - "dashboard.panel.invalidData": "URL の無効なデータ", "dashboard.panel.LibraryNotification": "Visualize ライブラリ通知", "dashboard.panel.libraryNotification.ariaLabel": "ライブラリ情報を表示し、このパネルのリンクを解除します", "dashboard.panel.libraryNotification.toolTip": "このパネルを編集すると、他のダッシュボードに影響する場合があります。このパネルのみを変更するには、ライブラリからリンクを解除します。", @@ -6371,9 +6370,383 @@ "xpack.stackConnectors.xmatters.shouldNotHaveSecretsUrl": "usesBasicがtrueのときには、secretsUrlを指定しないでください", "xpack.stackConnectors.xmatters.shouldNotHaveUsernamePassword": "usesBasicがfalseのときには、ユーザー名とパスワードを指定しないでください", "xpack.stackConnectors.xmatters.title": "xMatters", + "xpack.stackConnectors.components.index.error.badIndexOverrideValue": "アラート履歴インデックスの先頭は\"{alertHistoryPrefix}\"でなければなりません。", + "xpack.stackConnectors.components.email.error.invalidEmail": "電子メールアドレス{email}が無効です。", + "xpack.stackConnectors.components.email.error.notAllowed": "電子メールアドレス{email}が許可されていません。", + "xpack.stackConnectors.components.index.preconfiguredIndexHelpText": "ドキュメントは{alertHistoryIndex}インデックスにインデックスされます。", + "xpack.stackConnectors.components.jira.unableToGetIssueMessage": "ID {id}の問題を取得できません", + "xpack.stackConnectors.components.pagerDuty.error.invalidTimestamp": "タイムスタンプは、{nowShortFormat}や{nowLongFormat}などの有効な日付でなければなりません。", + "xpack.stackConnectors.components.serviceNow.apiInfoError": "アプリケーション情報の取得を試みるときの受信ステータス:{status}", + "xpack.stackConnectors.components.serviceNow.appInstallationInfo": "{update} {create} ", + "xpack.stackConnectors.components.serviceNow.updateSuccessToastTitle": "{connectorName}コネクターが更新されました", + "xpack.stackConnectors.components.serviceNow.apiUrlHelpLabel": "任意のServiceNowインスタンスへの完全なURLを入力します。ない場合は、{instance}。", + "xpack.stackConnectors.components.serviceNow.appRunning": "更新を実行する前に、ServiceNowアプリストアからElasticアプリをインストールする必要があります。アプリをインストールするには、{visitLink}", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationMessage": "id {id}のアプリケーションフィールドを取得できません", + "xpack.stackConnectors.components.casesWebhook.commentsTextAreaFieldLabel": "追加のコメント", + "xpack.stackConnectors.components.casesWebhook.descriptionTextAreaFieldLabel": "説明", + "xpack.stackConnectors.components.casesWebhook.tagsFieldLabel": "タグ", + "xpack.stackConnectors.components.casesWebhook.titleFieldLabel": "概要(必須)", + "xpack.stackConnectors.components.casesWebhook.addHeaderButton": "追加", + "xpack.stackConnectors.components.casesWebhook.addVariable": "変数を追加", + "xpack.stackConnectors.components.casesWebhook.authenticationLabel": "認証", + "xpack.stackConnectors.components.casesWebhook.caseCommentDesc": "Kibanaケースコメント", + "xpack.stackConnectors.components.casesWebhook.caseDescriptionDesc": "Kibanaケース説明", + "xpack.stackConnectors.components.casesWebhook.caseTagsDesc": "Kibanaケースタグ", + "xpack.stackConnectors.components.casesWebhook.caseTitleDesc": "Kibanaケースタイトル", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonHelp": "コメントを作成するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonTextFieldLabel": "コメントオブジェクトを作成", + "xpack.stackConnectors.components.casesWebhook.createCommentMethodTextFieldLabel": "コメントメソッドを作成", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlHelp": "コメントをケースに追加するためのAPI URL。", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlTextFieldLabel": "コメントURLを作成", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonHelpText": "ケースを作成するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonTextFieldLabel": "ケースオブジェクトを作成", + "xpack.stackConnectors.components.casesWebhook.createIncidentMethodTextFieldLabel": "ケースメソッドを作成", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyHelpText": "外部ケースIDを含むケース対応の作成のJSONキー", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyTextFieldLabel": "ケース対応ケースキーを作成", + "xpack.stackConnectors.components.casesWebhook.createIncidentUrlTextFieldLabel": "ケースURLを作成", + "xpack.stackConnectors.components.casesWebhook.deleteHeaderButton": "削除", + "xpack.stackConnectors.components.casesWebhook.docLink": "Webフックの構成 - ケース管理コネクター。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentIncidentText": "コメントオブジェクトの作成は有効なJSONでなければなりません。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentUrlText": "コメントURLの作成はURL形式でなければなりません。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentText": "ケースオブジェクトの作成は必須であり、有効なJSONでなければなりません。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateUrlText": "ケースURLの作成は必須です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentUrlText": "ケースURLの取得は必須です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateIncidentText": "ケースオブジェクトの更新は必須であり、有効なJSONでなければなりません。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateUrlText": "ケースURLの更新は必須です。", + "xpack.stackConnectors.components.casesWebhook.externalIdDesc": "外部システムID", + "xpack.stackConnectors.components.casesWebhook.externalTitleDesc": "外部システムタイトル", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyHelp": "外部ケースタイトルを含むケース対応の取得のJSONキー", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyTextFieldLabel": "ケース対応の取得の外部タイトルキー", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlHelp": "外部システムからケース詳細JSONを取得するAPI URL。変数セレクターを使用して、外部システムIDをURLに追加します。", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlTextFieldLabel": "ケースURLを取得", + "xpack.stackConnectors.components.casesWebhook.hasAuthSwitchLabel": "この Web フックの認証が必要です", + "xpack.stackConnectors.components.casesWebhook.httpHeadersTitle": "使用中のヘッダー", + "xpack.stackConnectors.components.casesWebhook.jsonCodeEditorAriaLabel": "コードエディター", + "xpack.stackConnectors.components.casesWebhook.jsonFieldLabel": "JSON", + "xpack.stackConnectors.components.casesWebhook.keyTextFieldLabel": "キー", + "xpack.stackConnectors.components.casesWebhook.next": "次へ", + "xpack.stackConnectors.components.casesWebhook.passwordTextFieldLabel": "パスワード", + "xpack.stackConnectors.components.casesWebhook.previous": "前へ", + "xpack.stackConnectors.components.casesWebhook.selectMessageText": "ケース管理Webサービスにリクエストを送信します。", + "xpack.stackConnectors.components.casesWebhook.step1": "コネクターを設定", + "xpack.stackConnectors.components.casesWebhook.step2": "ケースを作成", + "xpack.stackConnectors.components.casesWebhook.step2Description": "外部システムでケースを作成するフィールドを設定します。必要なフィールドを判断するには、サービスのAPIドキュメントを確認してください", + "xpack.stackConnectors.components.casesWebhook.step3": "ケース情報を取得", + "xpack.stackConnectors.components.casesWebhook.step3Description": "外部システムでコメントをケースに追加するフィールドを設定します。一部のシステムでは、ケースでの更新の作成と同じメソッドの場合があります。必要なフィールドを判断するには、サービスのAPIドキュメントを確認してください。", + "xpack.stackConnectors.components.casesWebhook.step4": "コメントと更新", + "xpack.stackConnectors.components.casesWebhook.step4a": "ケースで更新を作成", + "xpack.stackConnectors.components.casesWebhook.step4aDescription": "外部システムでケースの更新を作成するフィールドを設定します。一部のシステムでは、ケースへのコメントの追加と同じメソッドの場合があります。", + "xpack.stackConnectors.components.casesWebhook.step4b": "ケースでコメントを追加", + "xpack.stackConnectors.components.casesWebhook.step4bDescription": "外部システムでコメントをケースに追加するフィールドを設定します。一部のシステムでは、ケースでの更新の作成と同じメソッドの場合があります。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonHelpl": "ケースを更新するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonTextFieldLabel": "ケースオブジェクトを更新", + "xpack.stackConnectors.components.casesWebhook.updateIncidentMethodTextFieldLabel": "ケースメソッドを更新", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlHelp": "ケースを更新するAPI URL。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlTextFieldLabel": "ケースURLを更新", + "xpack.stackConnectors.components.casesWebhook.userTextFieldLabel": "ユーザー名", + "xpack.stackConnectors.components.casesWebhook.valueTextFieldLabel": "値", + "xpack.stackConnectors.components.casesWebhook.viewHeadersSwitch": "HTTP ヘッダーを追加", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlHelp": "外部システムでケースを表示するURL。変数セレクターを使用して、外部システムIDまたは外部システムタイトルをURLに追加します。", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlTextFieldLabel": "外部ケース表示URL", + "xpack.stackConnectors.components.serviceNow.requiredShortDescTextField": "短い説明が必要です。", + "xpack.stackConnectors.components.email.exchangeForm.clientIdHelpLabel": "クライアントIDの構成", + "xpack.stackConnectors.components.email.exchangeForm.clientSecretHelpLabel": "クライアントシークレットの構成", + "xpack.stackConnectors.components.email.exchangeForm.tenantIdHelpLabel": "テナントIDの構成", + "xpack.stackConnectors.components.email.connectorTypeTitle": "メールに送信", + "xpack.stackConnectors.components.email.amazonSesServerTypeLabel": "Amazon SES", + "xpack.stackConnectors.components.email.configureAccountsHelpLabel": "電子メールアカウントの構成", + "xpack.stackConnectors.components.email.elasticCloudServerTypeLabel": "Elastic Cloud", + "xpack.stackConnectors.components.email.exchangeServerTypeLabel": "MS Exchange Server", + "xpack.stackConnectors.components.email.gmailServerTypeLabel": "Gmail", + "xpack.stackConnectors.components.email.otherServerTypeLabel": "その他", + "xpack.stackConnectors.components.email.outlookServerTypeLabel": "Outlook", + "xpack.stackConnectors.components.email.selectMessageText": "サーバーからメールを送信します。", + "xpack.stackConnectors.components.email.updateErrorNotificationText": "サービス構成を取得できません", + "xpack.stackConnectors.components.index.error.badIndexOverrideSuffix": "アラート履歴インデックスには有効なサフィックスを含める必要があります。", + "xpack.stackConnectors.components.email.error.invalidPortText": "ポートが無効です。", + "xpack.stackConnectors.components.email.error.requiredAuthUserNameText": "ユーザー名が必要です。", + "xpack.stackConnectors.components.email.error.requiredClientIdText": "クライアントIDは必須です。", + "xpack.stackConnectors.components.index.error.requiredDocumentJson": "ドキュメントが必要です。有効なJSONオブジェクトにしてください。", + "xpack.stackConnectors.components.email.error.requiredEntryText": "To、Cc、または Bcc のエントリーがありません。 1 つ以上のエントリーが必要です。", + "xpack.stackConnectors.components.email.error.requiredFromText": "送信元が必要です。", + "xpack.stackConnectors.components.email.error.requiredHostText": "ホストが必要です。", + "xpack.stackConnectors.components.email.error.requiredMessageText": "メッセージが必要です。", + "xpack.stackConnectors.components.email.error.requiredPortText": "ポートが必要です。", + "xpack.stackConnectors.components.serverLog.error.requiredServerLogMessageText": "メッセージが必要です。", + "xpack.stackConnectors.components.email.error.requiredServiceText": "サービスは必須です。", + "xpack.stackConnectors.components.email.error.requiredSubjectText": "件名が必要です。", + "xpack.stackConnectors.components.email.error.requiredTenantIdText": "テナントIDは必須です。", + "xpack.stackConnectors.components.webhook.error.requiredWebhookBodyText": "本文が必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredWebhookSummaryText": "タイトルが必要です。", + "xpack.stackConnectors.components.index.connectorTypeTitle": "データをインデックスする", + "xpack.stackConnectors.components.index.configureIndexHelpLabel": "インデックスコネクターを構成しています。", + "xpack.stackConnectors.components.index.connectorSectionTitle": "インデックスを書き出す", + "xpack.stackConnectors.components.index.definedateFieldTooltip": "この時間フィールドをドキュメントにインデックスが作成された時刻に設定します。", + "xpack.stackConnectors.components.index.defineTimeFieldLabel": "各ドキュメントの時刻フィールドを定義", + "xpack.stackConnectors.components.index.documentsFieldLabel": "インデックスするドキュメント", + "xpack.stackConnectors.components.index.error.notValidIndexText": "インデックスは有効ではありません。", + "xpack.stackConnectors.components.index.executionTimeFieldLabel": "時間フィールド", + "xpack.stackConnectors.components.index.howToBroadenSearchQueryDescription": "* で検索クエリの範囲を広げます。", + "xpack.stackConnectors.components.index.indexDocumentHelpLabel": "インデックスドキュメントの例。", + "xpack.stackConnectors.components.index.indicesToQueryLabel": "インデックス", + "xpack.stackConnectors.components.index.jsonDocAriaLabel": "コードエディター", + "xpack.stackConnectors.components.index.preconfiguredIndex": "Elasticsearchインデックス", + "xpack.stackConnectors.components.index.preconfiguredIndexDocLink": "ドキュメントを表示します。", + "xpack.stackConnectors.components.index.refreshLabel": "更新インデックス", + "xpack.stackConnectors.components.index.refreshTooltip": "影響を受けるシャードを更新し、この処理を検索できるようにします。", + "xpack.stackConnectors.components.index.selectMessageText": "データを Elasticsearch にインデックスしてください。", + "xpack.stackConnectors.components.jira.connectorTypeTitle": "Jira", + "xpack.stackConnectors.components.jira.apiTokenTextFieldLabel": "APIトークン", + "xpack.stackConnectors.components.jira.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.jira.commentsTextAreaFieldLabel": "追加のコメント", + "xpack.stackConnectors.components.jira.descriptionTextAreaFieldLabel": "説明", + "xpack.stackConnectors.components.jira.emailTextFieldLabel": "メールアドレス", + "xpack.stackConnectors.components.jira.impactSelectFieldLabel": "ラベル", + "xpack.stackConnectors.components.jira.labelsSpacesErrorMessage": "ラベルにはスペースを使用できません。", + "xpack.stackConnectors.components.jira.parentIssueSearchLabel": "親問題", + "xpack.stackConnectors.components.jira.projectKey": "プロジェクトキー", + "xpack.stackConnectors.components.jira.requiredSummaryTextField": "概要が必要です。", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxAriaLabel": "入力して検索", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxPlaceholder": "入力して検索", + "xpack.stackConnectors.components.jira.searchIssuesLoading": "読み込み中...", + "xpack.stackConnectors.components.jira.selectMessageText": "Jira でインシデントを作成します。", + "xpack.stackConnectors.components.jira.severitySelectFieldLabel": "優先度", + "xpack.stackConnectors.components.jira.summaryFieldLabel": "概要(必須)", + "xpack.stackConnectors.components.jira.unableToGetFieldsMessage": "フィールドを取得できません", + "xpack.stackConnectors.components.jira.unableToGetIssuesMessage": "問題を取得できません", + "xpack.stackConnectors.components.jira.unableToGetIssueTypesMessage": "問題タイプを取得できません", + "xpack.stackConnectors.components.jira.urgencySelectFieldLabel": "問題タイプ", + "xpack.stackConnectors.components.pagerDuty.connectorTypeTitle": "PagerDuty に送信", + "xpack.stackConnectors.components.pagerDuty.apiUrlInvalid": "無効なAPI URL", + "xpack.stackConnectors.components.pagerDuty.apiUrlTextFieldLabel": "API URL(任意)", + "xpack.stackConnectors.components.pagerDuty.classFieldLabel": "クラス(任意)", + "xpack.stackConnectors.components.pagerDuty.componentTextFieldLabel": "コンポーネント(任意)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextFieldLabel": "DedupKey(任意)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextRequiredFieldLabel": "DedupKey", + "xpack.stackConnectors.components.pagerDuty.error.requiredDedupKeyText": "インシデントを解決または確認するときには、DedupKeyが必要です。", + "xpack.stackConnectors.components.pagerDuty.error.requiredRoutingKeyText": "統合キー/ルーティングキーが必要です。", + "xpack.stackConnectors.components.pagerDuty.error.requiredSummaryText": "概要が必要です。", + "xpack.stackConnectors.components.pagerDuty.eventActionSelectFieldLabel": "イベントアクション", + "xpack.stackConnectors.components.pagerDuty.eventSelectAcknowledgeOptionLabel": "承認", + "xpack.stackConnectors.components.pagerDuty.eventSelectResolveOptionLabel": "解決", + "xpack.stackConnectors.components.pagerDuty.eventSelectTriggerOptionLabel": "トリガー", + "xpack.stackConnectors.components.pagerDuty.groupTextFieldLabel": "グループ(任意)", + "xpack.stackConnectors.components.pagerDuty.routingKeyNameHelpLabel": "PagerDuty アカウントを構成します", + "xpack.stackConnectors.components.pagerDuty.routingKeyTextFieldLabel": "統合キー", + "xpack.stackConnectors.components.pagerDuty.selectMessageText": "PagerDuty でイベントを送信します。", + "xpack.stackConnectors.components.pagerDuty.severitySelectCriticalOptionLabel": "重大", + "xpack.stackConnectors.components.pagerDuty.severitySelectErrorOptionLabel": "エラー", + "xpack.stackConnectors.components.pagerDuty.severitySelectFieldLabel": "重要度(任意)", + "xpack.stackConnectors.components.pagerDuty.severitySelectInfoOptionLabel": "情報", + "xpack.stackConnectors.components.pagerDuty.severitySelectWarningOptionLabel": "警告", + "xpack.stackConnectors.components.pagerDuty.sourceTextFieldLabel": "ソース(任意)", + "xpack.stackConnectors.components.pagerDuty.summaryFieldLabel": "まとめ", + "xpack.stackConnectors.components.pagerDuty.timestampTextFieldLabel": "タイムスタンプ(任意)", + "xpack.stackConnectors.components.resilient.connectorTypeTitle": "Resilient", + "xpack.stackConnectors.components.resilient.apiKeyId": "APIキーID", + "xpack.stackConnectors.components.resilient.apiKeySecret": "APIキーシークレット", + "xpack.stackConnectors.components.resilient.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.resilient.commentsTextAreaFieldLabel": "追加のコメント", + "xpack.stackConnectors.components.resilient.descriptionTextAreaFieldLabel": "説明", + "xpack.stackConnectors.components.resilient.nameFieldLabel": "名前(必須)", + "xpack.stackConnectors.components.resilient.orgId": "組織 ID", + "xpack.stackConnectors.components.resilient.requiredNameTextField": "名前が必要です。", + "xpack.stackConnectors.components.resilient.selectMessageText": "IBM Resilient でインシデントを作成します。", + "xpack.stackConnectors.components.resilient.severity": "深刻度", + "xpack.stackConnectors.components.resilient.unableToGetIncidentTypesMessage": "インシデントタイプを取得できません", + "xpack.stackConnectors.components.resilient.unableToGetSeverityMessage": "深刻度を取得できません", + "xpack.stackConnectors.components.resilient.urgencySelectFieldLabel": "インシデントタイプ", + "xpack.stackConnectors.components.serverLog.connectorTypeTitle": "サーバーログに送信", + "xpack.stackConnectors.components.serverLog.logLevelFieldLabel": "レベル", + "xpack.stackConnectors.components.serverLog.logMessageFieldLabel": "メッセージ", + "xpack.stackConnectors.components.serverLog.selectMessageText": "Kibana ログにメッセージを追加します。", + "xpack.stackConnectors.components.serviceNow.apiUrlTextFieldLabel": "ServiceNowインスタンスURL", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout": "Elastic ServiceNowアプリがインストールされていません", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.content": "ServiceNowアプリストアに移動し、アプリケーションをインストールしてください", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.errorMessage": "エラーメッセージ", + "xpack.stackConnectors.components.serviceNow.authenticationLabel": "認証", + "xpack.stackConnectors.components.serviceNow.cancelButtonText": "キャンセル", + "xpack.stackConnectors.components.serviceNow.categoryTitle": "カテゴリー", + "xpack.stackConnectors.components.serviceNow.clientIdTextFieldLabel": "クライアントID", + "xpack.stackConnectors.components.serviceNow.clientSecretTextFieldLabel": "クライアントシークレット", + "xpack.stackConnectors.components.serviceNow.commentsTextAreaFieldLabel": "追加のコメント", + "xpack.stackConnectors.components.serviceNow.confirmButtonText": "更新", + "xpack.stackConnectors.components.serviceNow.correlationDisplay": "相関関係表示(オプション)", + "xpack.stackConnectors.components.serviceNow.correlationID": "相関関係ID(オプション)", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutCreate": "または新規作成します。", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutMigrate": "このコネクターを更新します", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutTitle": "このコネクターは廃止予定です", + "xpack.stackConnectors.components.serviceNow.descriptionTextAreaFieldLabel": "説明", + "xpack.stackConnectors.components.serviceNow.eventClassTextAreaFieldLabel": "ソースインスタンス", + "xpack.stackConnectors.components.serviceNow.fetchErrorMsg": "取得できませんでした。ServiceNowインスタンスのURLまたはCORS公正を確認します。", + "xpack.stackConnectors.components.serviceNow.impactSelectFieldLabel": "インパクト", + "xpack.stackConnectors.components.serviceNow.installationCalloutTitle": "このコネクターを使用するには、まずServiceNowアプリストアからElasticアプリをインストールします。", + "xpack.stackConnectors.components.serviceNow.invalidApiUrlTextField": "URL が無効です。", + "xpack.stackConnectors.components.serviceNow.keyIdTextFieldLabel": "JWT VerifierキーID", + "xpack.stackConnectors.components.serviceNow.messageKeyTextAreaFieldLabel": "メッセージキー", + "xpack.stackConnectors.components.serviceNow.metricNameTextAreaFieldLabel": "メトリック名", + "xpack.stackConnectors.components.serviceNow.nodeTextAreaFieldLabel": "ノード", + "xpack.stackConnectors.components.serviceNow.passwordTextFieldLabel": "パスワード", + "xpack.stackConnectors.components.serviceNow.prioritySelectFieldLabel": "優先度", + "xpack.stackConnectors.components.serviceNow.privateKeyPassLabelHelpText": "これは、秘密鍵でパスワードを設定した場合にのみ必要です", + "xpack.stackConnectors.components.serviceNow.privateKeyPassTextFieldLabel": "秘密鍵パスワード", + "xpack.stackConnectors.components.serviceNow.privateKeyTextFieldLabel": "秘密鍵", + "xpack.stackConnectors.components.serviceNow.requiredClientIdTextField": "クライアントIDは必須です。", + "xpack.stackConnectors.components.serviceNow.requiredKeyIdTextField": "JWT VerifierキーIDは必須です。", + "xpack.stackConnectors.components.serviceNow.requiredPrivateKeyTextField": "秘密鍵は必須です。", + "xpack.stackConnectors.components.serviceNow.requiredSeverityTextField": "重要度は必須です。", + "xpack.stackConnectors.components.serviceNow.requiredUserIdentifierTextField": "ユーザーIDは必須です。", + "xpack.stackConnectors.components.serviceNow.requiredUsernameTextField": "ユーザー名が必要です。", + "xpack.stackConnectors.components.serviceNow.resourceTextAreaFieldLabel": "リソース", + "xpack.stackConnectors.components.serviceNow.setupDevInstance": "開発者インスタンスを設定", + "xpack.stackConnectors.components.serviceNow.severityRequiredSelectFieldLabel": "重要度(必須)", + "xpack.stackConnectors.components.serviceNow.severitySelectFieldLabel": "深刻度", + "xpack.stackConnectors.components.serviceNow.snInstanceLabel": "ServiceNowインスタンス", + "xpack.stackConnectors.components.serviceNow.sourceTextAreaFieldLabel": "送信元", + "xpack.stackConnectors.components.serviceNow.subcategoryTitle": "サブカテゴリー", + "xpack.stackConnectors.components.serviceNow.title": "インシデント", + "xpack.stackConnectors.components.serviceNow.titleFieldLabel": "短い説明(必須)", + "xpack.stackConnectors.components.serviceNow.typeTextAreaFieldLabel": "型", + "xpack.stackConnectors.components.serviceNow.unableToGetChoicesMessage": "選択肢を取得できません", + "xpack.stackConnectors.components.serviceNow.unknown": "不明", + "xpack.stackConnectors.components.serviceNow.updateCalloutText": "コネクターが更新されました。", + "xpack.stackConnectors.components.serviceNow.updateFormCredentialsTitle": "認証資格情報を入力", + "xpack.stackConnectors.components.serviceNow.updateFormInstallTitle": "Elastic ServiceNowアプリをインストール", + "xpack.stackConnectors.components.serviceNow.updateFormTitle": "ServiceNowコネクターを更新", + "xpack.stackConnectors.components.serviceNow.updateFormUrlTitle": "ServiceNowインスタンスURLを入力", + "xpack.stackConnectors.components.serviceNow.urgencySelectFieldLabel": "緊急", + "xpack.stackConnectors.components.serviceNow.useOAuth": "OAuth認証を使用", + "xpack.stackConnectors.components.serviceNow.userEmailTextFieldLabel": "ユーザーID", + "xpack.stackConnectors.components.serviceNow.usernameTextFieldLabel": "ユーザー名", + "xpack.stackConnectors.components.serviceNow.visitSNStore": "ServiceNowアプリストアにアクセス", + "xpack.stackConnectors.components.serviceNow.warningMessage": "このコネクターのすべてのインスタンスが更新され、元に戻せません。", + "xpack.stackConnectors.components.serviceNow.correlationIDHelpLabel": "インシデントを更新するID", + "xpack.stackConnectors.components.serviceNowITOM.connectorTypeTitle": "ServiceNow ITOM", + "xpack.stackConnectors.components.serviceNowITOM.event": "イベント", + "xpack.stackConnectors.components.serviceNowITOM.selectMessageText": "ServiceNow ITOMでイベントを作成します。", + "xpack.stackConnectors.components.serviceNowITSM.connectorTypeTitle": "ServiceNow ITSM", + "xpack.stackConnectors.components.serviceNowITSM.selectMessageText": "ServiceNow ITSMでインシデントを作成します。", + "xpack.stackConnectors.components.serviceNowSIR.connectorTypeTitle": "ServiceNow SecOps", + "xpack.stackConnectors.components.serviceNowSIR.selectMessageText": "ServiceNow SecOpsでインシデントを作成します。", + "xpack.stackConnectors.components.serviceNowSIR.title": "セキュリティインシデント", + "xpack.stackConnectors.components.serviceNowSIR.correlationIDHelpLabel": "インシデントを更新するID", + "xpack.stackConnectors.components.slack.connectorTypeTitle": "Slack に送信", + "xpack.stackConnectors.components.slack.error.invalidWebhookUrlText": "Web フック URL が無効です。", + "xpack.stackConnectors.components.slack.messageTextAreaFieldLabel": "メッセージ", + "xpack.stackConnectors.components.slack.selectMessageText": "Slack チャネルにメッセージを送信します。", + "xpack.stackConnectors.components.slack.webhookUrlHelpLabel": "Slack Web フック URL を作成", + "xpack.stackConnectors.components.slack.webhookUrlTextFieldLabel": "Web フック URL", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationFieldsMessage": "アプリケーションフィールドを取得できません", + "xpack.stackConnectors.components.swimlane.connectorTypeTitle": "Swimlaneレコードを作成", + "xpack.stackConnectors.components.swimlane.alertIdFieldLabel": "アラートID", + "xpack.stackConnectors.components.swimlane.apiTokenNameHelpLabel": "Swimlane APIトークンを指定", + "xpack.stackConnectors.components.swimlane.apiTokenTextFieldLabel": "APIトークン", + "xpack.stackConnectors.components.swimlane.apiUrlTextFieldLabel": "API Url", + "xpack.stackConnectors.components.swimlane.appIdTextFieldLabel": "アプリケーションID", + "xpack.stackConnectors.components.swimlane.caseIdFieldLabel": "ケースID", + "xpack.stackConnectors.components.swimlane.caseNameFieldLabel": "ケース名", + "xpack.stackConnectors.components.swimlane.commentsFieldLabel": "コメント", + "xpack.stackConnectors.components.swimlane.configureConnectionLabel": "API接続を構成", + "xpack.stackConnectors.components.swimlane.connectorType": "コネクタータイプ", + "xpack.stackConnectors.components.swimlane.descriptionFieldLabel": "説明", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningDesc": "このコネクターを選択できません。必要なアラートフィールドマッピングがありません。このコネクターを編集して、必要なフィールドマッピングを追加するか、タイプがアラートのコネクターを選択できます。", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningTitle": "このコネクターにはフィールドマッピングがありません。", + "xpack.stackConnectors.components.swimlane.error.requiredAlertID": "アラートIDは必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredAppIdText": "アプリIDは必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredCaseID": "ケースIDは必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredCaseName": "ケース名は必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredComments": "コメントは必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredDescription": "説明が必要です。", + "xpack.stackConnectors.components.swimlane.error.requiredRuleName": "ルール名は必須です。", + "xpack.stackConnectors.components.swimlane.error.requiredSeverity": "重要度は必須です。", + "xpack.stackConnectors.components.swimlane.invalidApiUrlTextField": "URL が無効です。", + "xpack.stackConnectors.components.swimlane.mappingTitleTextFieldLabel": "フィールドマッピングを構成", + "xpack.stackConnectors.components.swimlane.nextStep": "次へ", + "xpack.stackConnectors.components.swimlane.nextStepHelpText": "フィールドマッピングが構成されていない場合、Swimlaneコネクタータイプはすべてに設定されます。", + "xpack.stackConnectors.components.swimlane.prevStep": "戻る", + "xpack.stackConnectors.components.swimlane.ruleNameFieldLabel": "ルール名", + "xpack.stackConnectors.components.swimlane.selectMessageText": "Swimlaneでレコードを作成", + "xpack.stackConnectors.components.swimlane.severityFieldLabel": "深刻度", + "xpack.stackConnectors.components.teams.connectorTypeTitle": "メッセージを Microsoft Teams チャネルに送信します。", + "xpack.stackConnectors.components.teams.error.invalidWebhookUrlText": "Web フック URL が無効です。", + "xpack.stackConnectors.components.teams.error.requiredMessageText": "メッセージが必要です。", + "xpack.stackConnectors.components.teams.error.webhookUrlTextLabel": "Web フック URL", + "xpack.stackConnectors.components.teams.messageTextAreaFieldLabel": "メッセージ", + "xpack.stackConnectors.components.teams.selectMessageText": "メッセージを Microsoft Teams チャネルに送信します。", + "xpack.stackConnectors.components.teams.webhookUrlHelpLabel": "Microsoft Teams Web フック URL を作成", + "xpack.stackConnectors.components.webhook.connectorTypeTitle": "Web フックデータ", + "xpack.stackConnectors.components.webhook.addHeaderButtonLabel": "ヘッダーを追加", + "xpack.stackConnectors.components.webhook.authenticationLabel": "認証", + "xpack.stackConnectors.components.webhook.bodyCodeEditorAriaLabel": "コードエディター", + "xpack.stackConnectors.components.webhook.bodyFieldLabel": "本文", + "xpack.stackConnectors.components.webhook.error.invalidUrlTextField": "URL が無効です。", + "xpack.stackConnectors.components.webhook.hasAuthSwitchLabel": "この Web フックの認証が必要です", + "xpack.stackConnectors.components.webhook.headerKeyTextFieldLabel": "キー", + "xpack.stackConnectors.components.webhook.headerValueTextFieldLabel": "値", + "xpack.stackConnectors.components.webhook.methodTextFieldLabel": "メソド", + "xpack.stackConnectors.components.webhook.passwordTextFieldLabel": "パスワード", + "xpack.stackConnectors.components.webhook.removeHeaderIconLabel": "キー", + "xpack.stackConnectors.components.webhook.selectMessageText": "Web サービスにリクエストを送信してください。", + "xpack.stackConnectors.components.webhook.urlTextFieldLabel": "URL", + "xpack.stackConnectors.components.webhook.userTextFieldLabel": "ユーザー名", + "xpack.stackConnectors.components.webhook.viewHeadersSwitch": "HTTP ヘッダーを追加", + "xpack.stackConnectors.components.xmatters.connectorTypeTitle": "xMattersデータ", + "xpack.stackConnectors.components.xmatters.authenticationLabel": "認証", + "xpack.stackConnectors.components.xmatters.basicAuthButtonGroupLegend": "基本認証", + "xpack.stackConnectors.components.xmatters.basicAuthLabel": "基本認証", + "xpack.stackConnectors.components.xmatters.connectorSettingsLabel": "xMattersトリガーを設定するときに使用される認証方法を選択します。", + "xpack.stackConnectors.components.xmatters.error.invalidUrlTextField": "URL が無効です。", + "xpack.stackConnectors.components.xmatters.error.invalidUsernameTextField": "ユーザー名が無効です。", + "xpack.stackConnectors.components.xmatters.error.requiredUrlText": "URL が必要です。", + "xpack.stackConnectors.components.xmatters.initiationUrlHelpText": "完全なxMatters URLを含めます。", + "xpack.stackConnectors.components.xmatters.passwordTextFieldLabel": "パスワード", + "xpack.stackConnectors.components.xmatters.selectMessageText": "xMattersワークフローをトリガーします。", + "xpack.stackConnectors.components.xmatters.severity": "深刻度", + "xpack.stackConnectors.components.xmatters.severitySelectCriticalOptionLabel": "重大", + "xpack.stackConnectors.components.xmatters.severitySelectHighOptionLabel": "高", + "xpack.stackConnectors.components.xmatters.severitySelectLowOptionLabel": "低", + "xpack.stackConnectors.components.xmatters.severitySelectMediumOptionLabel": "中", + "xpack.stackConnectors.components.xmatters.severitySelectMinimalOptionLabel": "最小", + "xpack.stackConnectors.components.xmatters.tags": "タグ", + "xpack.stackConnectors.components.xmatters.urlAuthLabel": "URL認証", + "xpack.stackConnectors.components.xmatters.urlLabel": "開始URL", + "xpack.stackConnectors.components.xmatters.userCredsLabel": "ユーザー認証情報", + "xpack.stackConnectors.components.xmatters.userTextFieldLabel": "ユーザー名", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningDesc": "コメントを外部で共有するには、コネクターの[コメントURLを作成]および[コメントオブジェクトを作成]フィールドを構成します。", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningTitle": "ケースコメントを共有できません", + "xpack.stackConnectors.components.serviceNow.deprecatedTooltipTitle": "廃止予定のコネクター", + "xpack.stackConnectors.components.casesWebhook.error.requiredAuthUserNameText": "ユーザー名が必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentMethodText": "コメントメソッドを作成は必須です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentResponseKeyText": "ケース対応の作成ケースIDキーが必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateMethodText": "ケースメソッドの作成は必須です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseCreatedKeyText": "ケース対応の取得の作成日キーが必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseExternalTitleKeyText": "ケース対応の取得の外部タイトルキーが必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseUpdatedKeyText": "ケース対応の取得の更新日キーが必要です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentViewUrlKeyText": "ケースURLの表示は必須です。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateMethodText": "ケースメソッドの更新は必須です。", + "xpack.stackConnectors.components.webhook.error.requiredAuthUserNameText": "ユーザー名が必要です。", + "xpack.stackConnectors.components.webhook.error.requiredMethodText": "メソッドが必要です。", + "xpack.stackConnectors.components.email.addBccButton": "Bcc", + "xpack.stackConnectors.components.email.addCcButton": "Cc", + "xpack.stackConnectors.components.email.authenticationLabel": "認証", + "xpack.stackConnectors.components.email.clientIdFieldLabel": "クライアントID", + "xpack.stackConnectors.components.email.clientSecretTextFieldLabel": "クライアントシークレット", + "xpack.stackConnectors.components.email.fromTextFieldLabel": "送信元", + "xpack.stackConnectors.components.email.hasAuthSwitchLabel": "このサーバーの認証が必要です", + "xpack.stackConnectors.components.email.hostTextFieldLabel": "ホスト", + "xpack.stackConnectors.components.email.messageTextAreaFieldLabel": "メッセージ", + "xpack.stackConnectors.components.email.passwordFieldLabel": "パスワード", + "xpack.stackConnectors.components.email.portTextFieldLabel": "ポート", + "xpack.stackConnectors.components.email.recipientBccTextFieldLabel": "Bcc", + "xpack.stackConnectors.components.email.recipientCopyTextFieldLabel": "Cc", + "xpack.stackConnectors.components.email.recipientTextFieldLabel": "終了:", + "xpack.stackConnectors.components.email.secureSwitchLabel": "セキュア", + "xpack.stackConnectors.components.email.serviceTextFieldLabel": "サービス", + "xpack.stackConnectors.components.email.subjectTextFieldLabel": "件名", + "xpack.stackConnectors.components.email.tenantIdFieldLabel": "テナントID", + "xpack.stackConnectors.components.email.userTextFieldLabel": "ユーザー名", + "xpack.stackConnectors.components.index.resetDefaultIndexLabel": "デフォルトのインデックスをリセット", "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldCandidates": "{fieldCandidatesCount, plural, other {# 個のフィールド候補}}が特定されました。", - "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldValuePairs": "{fieldValuePairsCount, plural, other {# 個の重要なフィールド/値のペア}}が特定されました。", - "xpack.aiops.index.dataLoader.internalServerErrorMessage": "インデックス {index} のデータの読み込み中にエラーが発生。{message}。リクエストがタイムアウトした可能性があります。小さなサンプルサイズを使うか、時間範囲を狭めてみてください。", "xpack.aiops.index.dataViewNotBasedOnTimeSeriesNotificationTitle": "データビュー{dataViewTitle}は時系列に基づいていません", "xpack.aiops.index.errorLoadingDataMessage": "インデックス {index} のデータの読み込み中にエラーが発生。{message}。", "xpack.aiops.progressTitle": "進行状況:{progress}% — {progressMessage}", @@ -7156,7 +7529,6 @@ "xpack.apm.serviceGroups.selectServicesForm.preview": "プレビュー", "xpack.apm.serviceGroups.selectServicesForm.refresh": "更新", "xpack.apm.serviceGroups.selectServicesForm.saveGroup": "グループを保存", - "xpack.apm.serviceGroups.selectServicesForm.subtitle": "クエリを使用してこのグループのサービスを選択します。過去24時間以内にこのクエリと一致したサービスはグループに割り当てられます。", "xpack.apm.serviceGroups.selectServicesForm.title": "サービスを選択", "xpack.apm.serviceGroups.selectServicesList.environmentColumnLabel": "環境", "xpack.apm.serviceGroups.selectServicesList.nameColumnLabel": "名前", @@ -8899,7 +9271,6 @@ "xpack.cases.confirmDeleteCase.confirmQuestion": "{quantity, plural, =1 {このケース} other {これらのケース}}を削除すると、関連するすべてのケースデータが完全に削除され、外部インシデント管理システムにデータをプッシュできなくなります。続行していいですか?", "xpack.cases.confirmDeleteCase.deleteCase": "{quantity, plural, other {ケース}}を削除", "xpack.cases.confirmDeleteCase.deleteTitle": "「{caseTitle}」を削除", - "xpack.cases.confirmDeleteCase.selectedCases": "\"{quantity, plural, =1 {{title}} other {選択した{quantity}個のケース}}\"を削除", "xpack.cases.connecors.get.missingCaseConnectorErrorMessage": "オブジェクトタイプ「{id}」は登録されていません。", "xpack.cases.connecors.register.duplicateCaseConnectorErrorMessage": "オブジェクトタイプ「{id}」はすでに登録されています。", "xpack.cases.connectors.card.createCommentWarningDesc": "コメントを外部で共有するには、{connectorName}コネクターの[コメントURLを作成]および[コメントオブジェクトを作成]フィールドを構成します。", @@ -8909,7 +9280,6 @@ "xpack.cases.connectors.cases.externalIncidentUpdated": "({date}に{user}が更新)", "xpack.cases.connectors.jira.unableToGetIssueMessage": "ID {id}の問題を取得できません", "xpack.cases.containers.closedCases": "{totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases}件のケース}}をクローズしました", - "xpack.cases.containers.deletedCases": "{totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases}件のケース}}を削除しました", "xpack.cases.containers.markInProgressCases": "{totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases}件のケース}}を進行中に設定しました", "xpack.cases.containers.pushToExternalService": "{ serviceName }への送信が正常に完了しました", "xpack.cases.containers.reopenedCases": "{totalCases, plural, =1 {\"{caseTitle}\"} other {{totalCases}件のケース}}をオープンしました", @@ -8941,7 +9311,6 @@ "xpack.cases.caseTable.changeStatus": "ステータスの変更", "xpack.cases.caseTable.closed": "終了", "xpack.cases.caseTable.closedCases": "終了したケース", - "xpack.cases.caseTable.delete": "削除", "xpack.cases.caseTable.incidentSystem": "インシデント管理システム", "xpack.cases.caseTable.inProgressCases": "進行中のケース", "xpack.cases.caseTable.noCases.body": "ケースを作成するか、フィルターを編集します。", @@ -12496,9 +12865,7 @@ "xpack.fleet.unenrollAgents.forceDeleteMultipleTitle": "{count}個のエージェントを登録解除", "xpack.fleet.unenrollAgents.forceUnenrollCheckboxLabel": "{count, plural, other {エージェント}}を直ちに削除します。エージェントが最後のデータを送信するまで待機しない。", "xpack.fleet.unenrollAgents.forceUnenrollLegendText": "{count, plural, other {エージェント}}を強制的に登録解除", - "xpack.fleet.upgradeAgents.bulkResultErrorResultsSummary": "{count} {count, plural, other {個のエージェント}}が成功しませんでした", "xpack.fleet.upgradeAgents.hourLabel": "{option} {count, plural, other {時間}}", - "xpack.fleet.upgradeAgents.successSingleNotificationTitle": "{count}個のエージェントをアップグレードしています", "xpack.fleet.upgradeAgents.upgradeMultipleDescription": "このアクションにより、複数のエージェントがバージョン{version}にアップグレードされます。このアクションは元に戻せません。続行していいですか?", "xpack.fleet.upgradeAgents.upgradeSingleDescription": "このアクションにより、「{hostName}」で実行中のエージェントがバージョン{version}にアップグレードされます。このアクションは元に戻せません。続行していいですか?", "xpack.fleet.upgradeAgents.warningCallout": "ローリングアップグレードは、Elasticエージェントバージョン{version}以降でのみ使用できます", @@ -13401,7 +13768,6 @@ "xpack.fleet.unenrollAgents.unenrollFleetServerTitle": "このエージェントはFleetサーバーを実行しています", "xpack.fleet.updateAgentTags.errorNotificationTitle": "タグの更新が失敗しました", "xpack.fleet.updateAgentTags.successNotificationTitle": "タグが更新されました", - "xpack.fleet.upgradeAgents.bulkResultAllErrorsNotificationTitle": "{count, plural, other {{count}個のエージェント} =true {すべての選択されたエージェント}}のアップグレードエラー", "xpack.fleet.upgradeAgents.cancelButtonLabel": "キャンセル", "xpack.fleet.upgradeAgents.chooseVersionLabel": "バージョンのアップグレード", "xpack.fleet.upgradeAgents.confirmMultipleButtonLabel": "{count, plural, other {{count}個のエージェント} =true {すべての選択されたエージェント}}をアップグレード", @@ -13537,9 +13903,6 @@ "xpack.graph.icon.tachometer": "タコメーター", "xpack.graph.icon.user": "ユーザー", "xpack.graph.icon.users": "ユーザー", - "xpack.graph.inspect.requestTabTitle": "リクエスト", - "xpack.graph.inspect.responseTabTitle": "応答", - "xpack.graph.inspect.title": "検査", "xpack.graph.leaveWorkspace.confirmButtonLabel": "それでも移動", "xpack.graph.leaveWorkspace.confirmText": "今移動すると、保存されていない変更が失われます。", "xpack.graph.leaveWorkspace.modalTitle": "保存されていない変更", @@ -15100,8 +15463,6 @@ "xpack.infra.deprecations.tiebreakerAdjustIndexing": "インデックスを調整し、\"{field}\"をタイブレーカーとして使用します。", "xpack.infra.deprecations.timestampAdjustIndexing": "インデックスを調整し、\"{field}\"をタイムスタンプとして使用します。", "xpack.infra.homePage.toolbar.showingLastOneMinuteDataText": "指定期間のデータの最後の{duration}", - "xpack.infra.infrastructureMetricsExplorerPage.documentTitle": "{previousTitle} | メトリックエクスプローラー", - "xpack.infra.infrastructureSnapshotPage.documentTitle": "{previousTitle} | インベントリ", "xpack.infra.inventoryTimeline.header": "平均{metricLabel}", "xpack.infra.kibanaMetrics.cloudIdMissingErrorMessage": "{metricId} のモデルには cloudId が必要ですが、{nodeId} に cloudId が指定されていません。", "xpack.infra.kibanaMetrics.invalidInfraMetricErrorMessage": "{id} は有効な InfraMetric ではありません", @@ -15141,7 +15502,6 @@ "xpack.infra.logs.searchResultTooltip": "{bucketCount, plural, other {# 件のハイライトされたエントリー}}", "xpack.infra.logs.showingEntriesFromTimestamp": "{timestamp} 以降のエントリーを表示中", "xpack.infra.logs.showingEntriesUntilTimestamp": "{timestamp} までのエントリーを表示中", - "xpack.infra.logs.streamPage.documentTitle": "{previousTitle} | Stream", "xpack.infra.logs.viewInContext.logsFromContainerTitle": "表示されたログはコンテナー{container}から取得されました", "xpack.infra.logs.viewInContext.logsFromFileTitle": "表示されたログは、ファイル{file}およびホスト{host}から取得されました", "xpack.infra.logSourceConfiguration.invalidMessageFieldTypeErrorMessage": "{messageField}フィールドはテキストフィールドでなければなりません。", @@ -15149,8 +15509,7 @@ "xpack.infra.logSourceConfiguration.missingDataViewsLabel": "データビュー{indexPatternId}が見つかりません", "xpack.infra.logSourceConfiguration.missingMessageFieldErrorMessage": "データビューには{messageField}フィールドが必要です。", "xpack.infra.logSourceErrorPage.savedObjectNotFoundErrorMessage": "{savedObjectType}:{savedObjectId}が見つかりませんでした", - "xpack.infra.metricDetailPage.documentTitle": "インフラストラクチャ | メトリック | {name}", - "xpack.infra.metricDetailPage.documentTitleError": "{previousTitle} | おっと", + "xpack.infra.metricDetailPage.documentTitleError": "おっと", "xpack.infra.metrics.alertFlyout.alertPerRedundantFilterError": "このルールは想定未満の{matchedGroups}に対してアラートを通知できます。フィルタークエリには{groupCount, plural, one {このフィールド} other {これらのフィールド}}の完全一致が含まれるためです。詳細については、{filteringAndGroupingLink}を参照してください。", "xpack.infra.metrics.alertFlyout.ofExpression.helpTextDetail": "メトリックが見つからない場合は、{documentationLink}。", "xpack.infra.metrics.alerting.anomaly.summaryHigher": "{differential}x高い", @@ -15304,7 +15663,6 @@ "xpack.infra.header.logsTitle": "ログ", "xpack.infra.header.observabilityTitle": "Observability", "xpack.infra.hideHistory": "履歴を表示しない", - "xpack.infra.homePage.documentTitle": "メトリック", "xpack.infra.homePage.inventoryTabTitle": "インベントリ", "xpack.infra.homePage.metricsExplorerTabTitle": "メトリックエクスプローラー", "xpack.infra.homePage.noMetricsIndicesInstructionsActionLabel": "セットアップの手順を表示", @@ -17105,7 +17463,6 @@ "xpack.lens.configure.invalidReferenceLineDimension": "この基準線は存在しない軸に割り当てられています。この基準線を別の使用可能な軸に移動するか、削除することができます。", "xpack.lens.confirmModal.cancelButtonLabel": "キャンセル", "xpack.lens.customBucketContainer.dragToReorder": "ドラッグして並べ替え", - "xpack.lens.dataPanelWrapper.switchDatasource": "データソースに切り替える", "xpack.lens.datatable.addLayer": "ビジュアライゼーション", "xpack.lens.datatable.breakdownColumns": "列", "xpack.lens.datatable.breakdownColumns.description": "フィールドでメトリックを列に分割します。列数を少なくし、横スクロールを避けることをお勧めします。", @@ -25307,9 +25664,6 @@ "xpack.securitySolution.endpoint.resolver.relatedEventLimitTitle": "このリストには、{numberOfEntries} 件のプロセスイベントが含まれています。", "xpack.securitySolution.endpointPolicyStatus.revisionNumber": "rev. {revNumber}", "xpack.securitySolution.endpointResponseActions.actionError.errorMessage": "次の{ errorCount, plural, other {件のエラー}}が発生しました:", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessage": "次のエラーが発生しました:{error}", - "xpack.securitySolution.endpointResponseActions.killProcess.performApiErrorMessage": "次のエラーが発生しました:{error}", - "xpack.securitySolution.endpointResponseActions.suspendProcess.performApiErrorMessage": "次のエラーが発生しました:{error}", "xpack.securitySolution.event.reason.reasonRendererTitle": "イベントレンダラー:{eventRendererName} ", "xpack.securitySolution.eventDetails.nestedColumnCheckboxAriaLabel": "{field}フィールドはオブジェクトであり、列として追加できるネストされたフィールドに分解されます", "xpack.securitySolution.eventDetails.viewColumnCheckboxAriaLabel": "{field} 列を表示", @@ -25468,7 +25822,6 @@ "xpack.securitySolution.usersTable.rows": "{numRows} {numRows, plural, other {行}}", "xpack.securitySolution.usersTable.unit": "{totalCount, plural, other {ユーザー}}", "xpack.securitySolution.accessibility.tooltipWithKeyboardShortcut.pressTooltipLabel": "プレス", - "xpack.securitySolution.actionLogButton.label": "アクションログ", "xpack.securitySolution.actionsContextMenu.label": "開く", "xpack.securitySolution.administration.os.linux": "Linux", "xpack.securitySolution.administration.os.macos": "Mac", @@ -27243,7 +27596,6 @@ "xpack.securitySolution.effectedPolicySelect.assignmentSectionTitle": "割り当て", "xpack.securitySolution.effectedPolicySelect.viewPolicyLinkLabel": "ポリシーを表示", "xpack.securitySolution.emptyString.emptyStringDescription": "空の文字列", - "xpack.securitySolution.endpoint.actions.actionsLog": "アクションログを表示", "xpack.securitySolution.endpoint.actions.agentDetails": "エージェント詳細を表示", "xpack.securitySolution.endpoint.actions.agentPolicy": "エージェントポリシーを表示", "xpack.securitySolution.endpoint.actions.agentPolicyReassign": "エージェントポリシーを再割り当て", @@ -27711,7 +28063,6 @@ "xpack.securitySolution.endpointConsoleCommands.suspendProcess.commandArgAbout": "アクションに関するコメント", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.entityId.arg.comment": "一時停止するプロセスを表すエンティティID", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.pid.arg.comment": "一時停止するプロセスを表すPID", - "xpack.securitySolution.endpointDetails.activityLog": "アクションログ", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.endOfLog": "表示する情報がありません", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointIsolateAction": "要求を送信できませんでした。ホストの分離", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointReleaseAction": "要求を送信できませんでした。ホストのリリース", @@ -27732,8 +28083,6 @@ "xpack.securitySolution.endpointManagement.noPermissionsSubText": "この機能を使用するには、スーパーユーザーロールが必要です。スーパーユーザーロールがなく、ユーザーロールを編集する権限もない場合は、Kibana管理者に問い合わせてください。", "xpack.securitySolution.endpointManagemnet.noPermissionsText": "Elastic Security Administrationを使用するために必要なKibana権限がありません。", "xpack.securitySolution.endpointPolicyStatus.tooltipTitleLabel": "ポリシーが適用されました", - "xpack.securitySolution.endpointResponseActions.getProcesses.errorMessageTitle": "プロセスの取得アクションが失敗しました", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessageTitle": "プロセスの取得アクションの実行が失敗しました", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.command": "コマンド", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.enityId": "エンティティID", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.pid": "PID", @@ -31811,20 +32160,7 @@ "xpack.triggersActionsUI.actionVariables.legacyTagsLabel": "{variable}の導入により、これは廃止される予定です。", "xpack.triggersActionsUI.checkActionTypeEnabled.actionTypeDisabledByLicenseMessage": "このコネクターには {minimumLicenseRequired} ライセンスが必要です。", "xpack.triggersActionsUI.checkRuleTypeEnabled.ruleTypeDisabledByLicenseMessage": "このルールタイプには{minimumLicenseRequired}ライセンスが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.missingVariables": "必須の{variableCount, plural, other {個の変数}}が見つかりません:{variables}", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideValue": "アラート履歴インデックスの先頭は\"{alertHistoryPrefix}\"でなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidEmail": "電子メールアドレス{email}が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.notAllowed": "電子メールアドレス{email}が許可されていません。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexHelpText": "ドキュメントは{alertHistoryIndex}インデックスにインデックスされます。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueMessage": "ID {id}の問題を取得できません", "xpack.triggersActionsUI.components.builtinActionTypes.missingSecretsValuesLabel": "機密情報はインポートされません。次のフィールド{encryptedFieldsLength, plural, other {}}の値{encryptedFieldsLength, plural, other {}} {secretFieldsLabel}を入力してください。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.invalidTimestamp": "タイムスタンプは、{nowShortFormat}や{nowLongFormat}などの有効な日付でなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiInfoError": "アプリケーション情報の取得を試みるときの受信ステータス:{status}", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.appInstallationInfo": "{update} {create} ", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateSuccessToastTitle": "{connectorName}コネクターが更新されました", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.apiUrlHelpLabel": "任意のServiceNowインスタンスへの完全なURLを入力します。ない場合は、{instance}。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.serviceNowAppRunning": "更新を実行する前に、ServiceNowアプリストアからElasticアプリをインストールする必要があります。アプリをインストールするには、{visitLink}", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationMessage": "id {id}のアプリケーションフィールドを取得できません", "xpack.triggersActionsUI.components.buttonGroupField.error.requiredField": "{label}が必要です。", "xpack.triggersActionsUI.components.deleteSelectedIdsErrorNotification.descriptionText": "{numErrors, number} {numErrors, plural, one {{singleTitle}} other {{multipleTitle}}}を削除できませんでした", "xpack.triggersActionsUI.components.deleteSelectedIdsSuccessNotification.descriptionText": "{numSuccesses, number} {numSuccesses, plural, one {{singleTitle}} other {{multipleTitle}}}を削除しました", @@ -31979,340 +32315,6 @@ "xpack.triggersActionsUI.components.addMessageVariables.addRuleVariableTitle": "ルール変数を追加", "xpack.triggersActionsUI.components.addMessageVariables.addVariablePopoverButton": "変数を追加", "xpack.triggersActionsUI.components.alertTable.useFetchAlerts.errorMessageText": "アラート検索でエラーが発生しました", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.commentsTextAreaFieldLabel": "追加のコメント", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.descriptionTextAreaFieldLabel": "説明", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.tagsFieldLabel": "タグ", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.titleFieldLabel": "概要(必須)", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.actionTypeTitle": "Webフック - ケース管理データ", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addHeaderButton": "追加", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addVariable": "変数を追加", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.authenticationLabel": "認証", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseCommentDesc": "Kibanaケースコメント", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseDescriptionDesc": "Kibanaケース説明", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTagsDesc": "Kibanaケースタグ", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTitleDesc": "Kibanaケースタイトル", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonHelp": "コメントを作成するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonTextFieldLabel": "コメントオブジェクトを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentMethodTextFieldLabel": "コメントメソッドを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlHelp": "コメントをケースに追加するためのAPI URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlTextFieldLabel": "コメントURLを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonHelpText": "ケースを作成するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonTextFieldLabel": "ケースオブジェクトを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentMethodTextFieldLabel": "ケースメソッドを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyHelpText": "外部ケースIDを含むケース対応の作成のJSONキー", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyTextFieldLabel": "ケース対応ケースキーを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentUrlTextFieldLabel": "ケースURLを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.deleteHeaderButton": "削除", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.docLink": "Webフックの構成 - ケース管理コネクター。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentIncidentText": "コメントオブジェクトの作成は有効なJSONでなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentUrlText": "コメントURLの作成はURL形式でなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateIncidentText": "ケースオブジェクトの作成は必須であり、有効なJSONでなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateUrlText": "ケースURLの作成は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredGetIncidentUrlText": "ケースURLの取得は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateIncidentText": "ケースオブジェクトの更新は必須であり、有効なJSONでなければなりません。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateUrlText": "ケースURLの更新は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalIdDesc": "外部システムID", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalTitleDesc": "外部システムタイトル", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyHelp": "外部ケースタイトルを含むケース対応の取得のJSONキー", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyTextFieldLabel": "ケース対応の取得の外部タイトルキー", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlHelp": "外部システムからケース詳細JSONを取得するAPI URL。変数セレクターを使用して、外部システムIDをURLに追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlTextFieldLabel": "ケースURLを取得", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.hasAuthSwitchLabel": "この Web フックの認証が必要です", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.httpHeadersTitle": "使用中のヘッダー", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonCodeEditorAriaLabel": "コードエディター", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonFieldLabel": "JSON", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.keyTextFieldLabel": "キー", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.next": "次へ", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.passwordTextFieldLabel": "パスワード", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.previous": "前へ", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.selectMessageText": "ケース管理Webサービスにリクエストを送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step1": "コネクターを設定", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2": "ケースを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2Description": "外部システムでケースを作成するフィールドを設定します。必要なフィールドを判断するには、サービスのAPIドキュメントを確認してください", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3": "ケース情報を取得", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3Description": "外部システムでコメントをケースに追加するフィールドを設定します。一部のシステムでは、ケースでの更新の作成と同じメソッドの場合があります。必要なフィールドを判断するには、サービスのAPIドキュメントを確認してください。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4": "コメントと更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4a": "ケースで更新を作成", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4aDescription": "外部システムでケースの更新を作成するフィールドを設定します。一部のシステムでは、ケースへのコメントの追加と同じメソッドの場合があります。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4b": "ケースでコメントを追加", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4bDescription": "外部システムでコメントをケースに追加するフィールドを設定します。一部のシステムでは、ケースでの更新の作成と同じメソッドの場合があります。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonHelpl": "ケースを更新するJSONオブジェクト。変数セレクターを使用して、ケースデータをペイロードに追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonTextFieldLabel": "ケースオブジェクトを更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentMethodTextFieldLabel": "ケースメソッドを更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlHelp": "ケースを更新するAPI URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlTextFieldLabel": "ケースURLを更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.userTextFieldLabel": "ユーザー名", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.valueTextFieldLabel": "値", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewHeadersSwitch": "HTTP ヘッダーを追加", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlHelp": "外部システムでケースを表示するURL。変数セレクターを使用して、外部システムIDまたは外部システムタイトルをURLに追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlTextFieldLabel": "外部ケース表示URL", - "xpack.triggersActionsUI.components.builtinActionTypes.common.requiredShortDescTextField": "短い説明が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientIdHelpLabel": "クライアントIDの構成", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientSecretHelpLabel": "クライアントシークレットの構成", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.tenantIdHelpLabel": "テナントIDの構成", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.actionTypeTitle": "メールに送信", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.amazonSesServerTypeLabel": "Amazon SES", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.configureAccountsHelpLabel": "電子メールアカウントの構成", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.elasticCloudServerTypeLabel": "Elastic Cloud", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.exchangeServerTypeLabel": "MS Exchange Server", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.gmailServerTypeLabel": "Gmail", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.otherServerTypeLabel": "その他", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.outlookServerTypeLabel": "Outlook", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.selectMessageText": "サーバーからメールを送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.updateErrorNotificationText": "サービス構成を取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideSuffix": "アラート履歴インデックスには有効なサフィックスを含める必要があります。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidPortText": "ポートが無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredAuthUserNameText": "ユーザー名が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredClientIdText": "クライアントIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredDocumentJson": "ドキュメントが必要です。有効なJSONオブジェクトにしてください。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredEntryText": "To、Cc、または Bcc のエントリーがありません。 1 つ以上のエントリーが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredFromText": "送信元が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredHostText": "ホストが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredMessageText": "メッセージが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredPortText": "ポートが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServerLogMessageText": "メッセージが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServiceText": "サービスは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSlackMessageText": "メッセージが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSubjectText": "件名が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredTenantIdText": "テナントIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookBodyText": "本文が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookSummaryText": "タイトルが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.actionTypeTitle": "データをインデックスする", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.chooseLabel": "選択…", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.configureIndexHelpLabel": "インデックスコネクターを構成しています。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.connectorSectionTitle": "インデックスを書き出す", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.definedateFieldTooltip": "この時間フィールドをドキュメントにインデックスが作成された時刻に設定します。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.defineTimeFieldLabel": "各ドキュメントの時刻フィールドを定義", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel": "インデックスするドキュメント", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.error.notValidIndexText": "インデックスは有効ではありません。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.executionTimeFieldLabel": "時間フィールド", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.howToBroadenSearchQueryDescription": "* で検索クエリの範囲を広げます。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indexDocumentHelpLabel": "インデックスドキュメントの例。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesAndIndexPatternsLabel": "データビューに基づく", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesToQueryLabel": "インデックス", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel": "コードエディター", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndex": "Elasticsearchインデックス", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexDocLink": "ドキュメントを表示します。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshLabel": "更新インデックス", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshTooltip": "影響を受けるシャードを更新し、この処理を検索できるようにします。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.selectMessageText": "データを Elasticsearch にインデックスしてください。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.actionTypeTitle": "Jira", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiTokenTextFieldLabel": "APIトークン", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.commentsTextAreaFieldLabel": "追加のコメント", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.descriptionTextAreaFieldLabel": "説明", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.emailTextFieldLabel": "メールアドレス", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.impactSelectFieldLabel": "ラベル", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.labelsSpacesErrorMessage": "ラベルにはスペースを使用できません。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.parentIssueSearchLabel": "親問題", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.projectKey": "プロジェクトキー", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.requiredSummaryTextField": "概要が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxAriaLabel": "入力して検索", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxPlaceholder": "入力して検索", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesLoading": "読み込み中...", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.selectMessageText": "Jira でインシデントを作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.severitySelectFieldLabel": "優先度", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.summaryFieldLabel": "概要(必須)", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetFieldsMessage": "フィールドを取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssuesMessage": "問題を取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueTypesMessage": "問題タイプを取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.urgencySelectFieldLabel": "問題タイプ", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.actionTypeTitle": "PagerDuty に送信", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlInvalid": "無効なAPI URL", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlTextFieldLabel": "API URL(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.classFieldLabel": "クラス(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.componentTextFieldLabel": "コンポーネント(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextFieldLabel": "DedupKey(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextRequiredFieldLabel": "DedupKey", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredDedupKeyText": "インシデントを解決または確認するときには、DedupKeyが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredRoutingKeyText": "統合キー/ルーティングキーが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredSummaryText": "概要が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventActionSelectFieldLabel": "イベントアクション", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectAcknowledgeOptionLabel": "承認", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectResolveOptionLabel": "解決", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectTriggerOptionLabel": "トリガー", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.groupTextFieldLabel": "グループ(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyNameHelpLabel": "PagerDuty アカウントを構成します", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyTextFieldLabel": "統合キー", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.selectMessageText": "PagerDuty でイベントを送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectCriticalOptionLabel": "重大", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectErrorOptionLabel": "エラー", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectFieldLabel": "重要度(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectInfoOptionLabel": "情報", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectWarningOptionLabel": "警告", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.sourceTextFieldLabel": "ソース(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.summaryFieldLabel": "まとめ", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.timestampTextFieldLabel": "タイムスタンプ(任意)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.actionTypeTitle": "Resilient", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeyId": "APIキーID", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeySecret": "APIキーシークレット", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.commentsTextAreaFieldLabel": "追加のコメント", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.descriptionTextAreaFieldLabel": "説明", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.nameFieldLabel": "名前(必須)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.orgId": "組織 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredNameTextField": "名前が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.selectMessageText": "IBM Resilient でインシデントを作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.severity": "深刻度", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetIncidentTypesMessage": "インシデントタイプを取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetSeverityMessage": "深刻度を取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.urgencySelectFieldLabel": "インシデントタイプ", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.actionTypeTitle": "サーバーログに送信", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logLevelFieldLabel": "レベル", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logMessageFieldLabel": "メッセージ", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.selectMessageText": "Kibana ログにメッセージを追加します。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiUrlTextFieldLabel": "ServiceNowインスタンスURL", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout": "Elastic ServiceNowアプリがインストールされていません", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.content": "ServiceNowアプリストアに移動し、アプリケーションをインストールしてください", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.errorMessage": "エラーメッセージ", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.authenticationLabel": "認証", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.cancelButtonText": "キャンセル", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.categoryTitle": "カテゴリー", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientIdTextFieldLabel": "クライアントID", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientSecretTextFieldLabel": "クライアントシークレット", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.commentsTextAreaFieldLabel": "追加のコメント", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.confirmButtonText": "更新", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationDisplay": "相関関係表示(オプション)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationID": "相関関係ID(オプション)", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutCreate": "または新規作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutMigrate": "このコネクターを更新します", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutTitle": "このコネクターは廃止予定です", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.descriptionTextAreaFieldLabel": "説明", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.eventClassTextAreaFieldLabel": "ソースインスタンス", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.fetchErrorMsg": "取得できませんでした。ServiceNowインスタンスのURLまたはCORS公正を確認します。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.impactSelectFieldLabel": "インパクト", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.installationCalloutTitle": "このコネクターを使用するには、まずServiceNowアプリストアからElasticアプリをインストールします。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.invalidApiUrlTextField": "URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.keyIdTextFieldLabel": "JWT VerifierキーID", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.messageKeyTextAreaFieldLabel": "メッセージキー", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.metricNameTextAreaFieldLabel": "メトリック名", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.nodeTextAreaFieldLabel": "ノード", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.passwordTextFieldLabel": "パスワード", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.prioritySelectFieldLabel": "優先度", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassLabelHelpText": "これは、秘密鍵でパスワードを設定した場合にのみ必要です", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassTextFieldLabel": "秘密鍵パスワード", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyTextFieldLabel": "秘密鍵", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredClientIdTextField": "クライアントIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredKeyIdTextField": "JWT VerifierキーIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredPrivateKeyTextField": "秘密鍵は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredSeverityTextField": "重要度は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUserIdentifierTextField": "ユーザーIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUsernameTextField": "ユーザー名が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.resourceTextAreaFieldLabel": "リソース", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.setupDevInstance": "開発者インスタンスを設定", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severityRequiredSelectFieldLabel": "重要度(必須)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severitySelectFieldLabel": "深刻度", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.snInstanceLabel": "ServiceNowインスタンス", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.sourceTextAreaFieldLabel": "送信元", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.subcategoryTitle": "サブカテゴリー", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.title": "インシデント", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.titleFieldLabel": "短い説明(必須)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.typeTextAreaFieldLabel": "型", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unableToGetChoicesMessage": "選択肢を取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unknown": "不明", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateCalloutText": "コネクターが更新されました。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormCredentialsTitle": "認証資格情報を入力", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormInstallTitle": "Elastic ServiceNowアプリをインストール", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormTitle": "ServiceNowコネクターを更新", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormUrlTitle": "ServiceNowインスタンスURLを入力", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.urgencySelectFieldLabel": "緊急", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.useOAuth": "OAuth認証を使用", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.userEmailTextFieldLabel": "ユーザーID", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.usernameTextFieldLabel": "ユーザー名", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.visitSNStore": "ServiceNowアプリストアにアクセス", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.warningMessage": "このコネクターのすべてのインスタンスが更新され、元に戻せません。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.correlationIDHelpLabel": "インシデントを更新するID", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.actionTypeTitle": "ServiceNow ITOM", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowITOM.event": "イベント", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.selectMessageText": "ServiceNow ITOMでイベントを作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.actionTypeTitle": "ServiceNow ITSM", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.selectMessageText": "ServiceNow ITSMでインシデントを作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.actionTypeTitle": "ServiceNow SecOps", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.selectMessageText": "ServiceNow SecOpsでインシデントを作成します。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowSIR.title": "セキュリティインシデント", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIRAction.correlationIDHelpLabel": "インシデントを更新するID", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.actionTypeTitle": "Slack に送信", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.error.invalidWebhookUrlText": "Web フック URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.messageTextAreaFieldLabel": "メッセージ", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.selectMessageText": "Slack チャネルにメッセージを送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlHelpLabel": "Slack Web フック URL を作成", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlTextFieldLabel": "Web フック URL", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationFieldsMessage": "アプリケーションフィールドを取得できません", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.actionTypeTitle": "Swimlaneレコードを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.alertIdFieldLabel": "アラートID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenNameHelpLabel": "Swimlane APIトークンを指定", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenTextFieldLabel": "APIトークン", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiUrlTextFieldLabel": "API Url", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.appIdTextFieldLabel": "アプリケーションID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseIdFieldLabel": "ケースID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseNameFieldLabel": "ケース名", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.commentsFieldLabel": "コメント", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.configureConnectionLabel": "API接続を構成", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.connectorType": "コネクタータイプ", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.descriptionFieldLabel": "説明", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningDesc": "このコネクターを選択できません。必要なアラートフィールドマッピングがありません。このコネクターを編集して、必要なフィールドマッピングを追加するか、タイプがアラートのコネクターを選択できます。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningTitle": "このコネクターにはフィールドマッピングがありません。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAlertID": "アラートIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAppIdText": "アプリIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseID": "ケースIDは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseName": "ケース名は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredComments": "コメントは必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredDescription": "説明が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredRuleName": "ルール名は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredSeverity": "重要度は必須です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.invalidApiUrlTextField": "URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.mappingTitleTextFieldLabel": "フィールドマッピングを構成", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStep": "次へ", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStepHelpText": "フィールドマッピングが構成されていない場合、Swimlaneコネクタータイプはすべてに設定されます。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.prevStep": "戻る", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.ruleNameFieldLabel": "ルール名", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.selectMessageText": "Swimlaneでレコードを作成", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.severityFieldLabel": "深刻度", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.actionTypeTitle": "メッセージを Microsoft Teams チャネルに送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.invalidWebhookUrlText": "Web フック URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.requiredMessageText": "メッセージが必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.webhookUrlTextLabel": "Web フック URL", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.messageTextAreaFieldLabel": "メッセージ", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.selectMessageText": "メッセージを Microsoft Teams チャネルに送信します。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.webhookUrlHelpLabel": "Microsoft Teams Web フック URL を作成", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.actionTypeTitle": "Web フックデータ", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.addHeaderButtonLabel": "ヘッダーを追加", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.authenticationLabel": "認証", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyCodeEditorAriaLabel": "コードエディター", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyFieldLabel": "本文", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.error.invalidUrlTextField": "URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.hasAuthSwitchLabel": "この Web フックの認証が必要です", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerKeyTextFieldLabel": "キー", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerValueTextFieldLabel": "値", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.methodTextFieldLabel": "メソド", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.passwordTextFieldLabel": "パスワード", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.removeHeaderIconLabel": "キー", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.selectMessageText": "Web サービスにリクエストを送信してください。", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.urlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.userTextFieldLabel": "ユーザー名", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.viewHeadersSwitch": "HTTP ヘッダーを追加", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.actionTypeTitle": "xMattersデータ", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.authenticationLabel": "認証", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthButtonGroupLegend": "基本認証", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthLabel": "基本認証", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.connectorSettingsLabel": "xMattersトリガーを設定するときに使用される認証方法を選択します。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUrlTextField": "URL が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUsernameTextField": "ユーザー名が無効です。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.requiredUrlText": "URL が必要です。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.initiationUrlHelpText": "完全なxMatters URLを含めます。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.passwordTextFieldLabel": "パスワード", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.selectMessageText": "xMattersワークフローをトリガーします。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severity": "深刻度", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectCriticalOptionLabel": "重大", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectHighOptionLabel": "高", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectLowOptionLabel": "低", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMediumOptionLabel": "中", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMinimalOptionLabel": "最小", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.tags": "タグ", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlAuthLabel": "URL認証", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlLabel": "開始URL", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userCredsLabel": "ユーザー認証情報", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userTextFieldLabel": "ユーザー名", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorButtonLabel": "コネクターを作成", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyBody": "Kibanaで実行するメール、Slack、Elasticsearch、およびサードパーティサービスを構成します。", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyTitle": "初めてのコネクターを作成する", @@ -32334,8 +32336,6 @@ "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorMessage": "エディターが見つかりませんでした。ページを更新して再試行してください", "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorTitle": "メッセージ変数を追加できません", "xpack.triggersActionsUI.components.simpleConnectorForm.secrets.authenticationLabel": "認証", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningDesc": "コメントを外部で共有するには、コネクターの[コメントURLを作成]および[コメントオブジェクトを作成]フィールドを構成します。", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningTitle": "ケースコメントを共有できません", "xpack.triggersActionsUI.connectors.breadcrumbTitle": "コネクター", "xpack.triggersActionsUI.data.coreQueryParams.dateStartGTdateEndErrorMessage": "[dateStart]が[dateEnd]よりも大です", "xpack.triggersActionsUI.data.coreQueryParams.intervalRequiredErrorMessage": "[interval]:[dateStart]が[dateEnd]と等しくない場合に指定する必要があります", @@ -32396,7 +32396,6 @@ "xpack.triggersActionsUI.ruleSnoozeScheduler.saveSchedule": "スケジュールを保存", "xpack.triggersActionsUI.ruleSnoozeScheduler.timezoneLabel": "タイムゾーン", "xpack.triggersActionsUI.sections.actionConnectorAdd.backButtonLabel": "戻る", - "xpack.triggersActionsUI.sections.actionConnectorAdd.cancelButtonLabel": "キャンセル", "xpack.triggersActionsUI.sections.actionConnectorAdd.manageLicensePlanBannerLinkTitle": "ライセンスの管理", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveAndTestButtonLabel": "保存してテスト", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveButtonLabel": "保存", @@ -32409,7 +32408,6 @@ "xpack.triggersActionsUI.sections.actionConnectorForm.loadingConnectorSettingsDescription": "コネクター設定を読み込んでいます...", "xpack.triggersActionsUI.sections.actionForm.actionSectionsTitle": "アクション", "xpack.triggersActionsUI.sections.actionForm.addActionButtonLabel": "アクションの追加", - "xpack.triggersActionsUI.sections.actionForm.deprecatedTooltipTitle": "廃止予定のコネクター", "xpack.triggersActionsUI.sections.actionForm.getMoreConnectorsTitle": "その他のコネクターを取得", "xpack.triggersActionsUI.sections.actionForm.getMoreRuleTypesTitle": "その他のルールタイプを取得", "xpack.triggersActionsUI.sections.actionForm.incidentManagementSystemLabel": "インシデント管理システム", @@ -32448,17 +32446,6 @@ "xpack.triggersActionsUI.sections.actionTypeForm.actionErrorToolTip": "アクションにはエラーがあります。", "xpack.triggersActionsUI.sections.actionTypeForm.actionRunWhenInActionGroup": "次のときに実行", "xpack.triggersActionsUI.sections.actionTypeForm.addNewConnectorEmptyButton": "コネクターの追加", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredAuthUserNameText": "ユーザー名が必要です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateCommentMethodText": "コメントメソッドを作成は必須です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateIncidentResponseKeyText": "ケース対応の作成ケースIDキーが必要です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateMethodText": "ケースメソッドの作成は必須です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseCreatedKeyText": "ケース対応の取得の作成日キーが必要です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseExternalTitleKeyText": "ケース対応の取得の外部タイトルキーが必要です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseUpdatedKeyText": "ケース対応の取得の更新日キーが必要です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentViewUrlKeyText": "ケースURLの表示は必須です。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredUpdateMethodText": "ケースメソッドの更新は必須です。", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredAuthUserNameText": "ユーザー名が必要です。", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredMethodText": "メソッドが必要です。", "xpack.triggersActionsUI.sections.addConnectorForm.selectConnectorFlyoutTitle": "コネクターを選択", "xpack.triggersActionsUI.sections.addConnectorForm.updateSuccessNotificationText": "「{connectorName}」を作成しました", "xpack.triggersActionsUI.sections.addModalConnectorForm.cancelButtonLabel": "キャンセル", @@ -32468,25 +32455,6 @@ "xpack.triggersActionsUI.sections.alertsTable.alertsFlyout.reason": "理由", "xpack.triggersActionsUI.sections.alertsTable.column.actions": "アクション", "xpack.triggersActionsUI.sections.alertsTable.leadingControl.viewDetails": "詳細を表示", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addBccButton": "Bcc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addCcButton": "Cc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.authenticationLabel": "認証", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientIdFieldLabel": "クライアントID", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientSecretTextFieldLabel": "クライアントシークレット", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.fromTextFieldLabel": "送信元", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hasAuthSwitchLabel": "このサーバーの認証が必要です", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hostTextFieldLabel": "ホスト", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.messageTextAreaFieldLabel": "メッセージ", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.passwordFieldLabel": "パスワード", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.portTextFieldLabel": "ポート", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientBccTextFieldLabel": "Bcc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientCopyTextFieldLabel": "Cc", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientTextFieldLabel": "終了:", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.secureSwitchLabel": "セキュア", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.serviceTextFieldLabel": "サービス", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.subjectTextFieldLabel": "件名", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.tenantIdFieldLabel": "テナントID", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.userTextFieldLabel": "ユーザー名", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseCancelButtonText": "キャンセル", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseConfirmButtonText": "変更を破棄", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseMessage": "保存されていない変更は回復できません。", @@ -32502,11 +32470,9 @@ "xpack.triggersActionsUI.sections.connectorAddInline.unableToLoadConnectorTitle'": "コネクターを読み込めません", "xpack.triggersActionsUI.sections.connectorAddInline.unauthorizedToCreateForEmptyConnectors": "許可されたユーザーのみがコネクターを構成できます。管理者にお問い合わせください。", "xpack.triggersActionsUI.sections.deprecatedTitleMessage": "(非推奨)", - "xpack.triggersActionsUI.sections.editConnectorForm.cancelButtonLabel": "キャンセル", "xpack.triggersActionsUI.sections.editConnectorForm.descriptionText": "このコネクターは読み取り専用です。", "xpack.triggersActionsUI.sections.editConnectorForm.flyoutPreconfiguredTitle": "コネクターを編集", "xpack.triggersActionsUI.sections.editConnectorForm.preconfiguredHelpLabel": "あらかじめ構成されたコネクターの詳細をご覧ください。", - "xpack.triggersActionsUI.sections.editConnectorForm.saveAndCloseButtonLabel": "保存して閉じる", "xpack.triggersActionsUI.sections.editConnectorForm.saveButtonLabel": "保存", "xpack.triggersActionsUI.sections.editConnectorForm.tabText": "構成", "xpack.triggersActionsUI.sections.editConnectorForm.updateErrorNotificationText": "コネクターを更新できません。", @@ -32537,7 +32503,6 @@ "xpack.triggersActionsUI.sections.ruleDetails.alertsList.ruleTypeExcessDurationMessage": "期間がルールの想定実行時間を超えています。", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.activeLabel": "アクティブ", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.allAlertsLabel": "すべてのアラート", - "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.recentAlertHistoryTitle": "最近のアラート履歴", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.title": "アラート", "xpack.triggersActionsUI.sections.ruleDetails.deleteRuleButtonLabel": "ルールの削除", "xpack.triggersActionsUI.sections.ruleDetails.disableRuleButtonLabel": "無効にする", @@ -32678,7 +32643,6 @@ "xpack.triggersActionsUI.sections.rulesList.removeAllButton": "すべて削除", "xpack.triggersActionsUI.sections.rulesList.removeCancelButton": "キャンセル", "xpack.triggersActionsUI.sections.rulesList.removeConfirmButton": "すべて削除", - "xpack.triggersActionsUI.sections.rulesList.resetDefaultIndexLabel": "デフォルトのインデックスをリセット", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDecrypting": "ルールの復号中にエラーが発生しました。", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDisabled": "ルールを実行できませんでした。ルールは無効化された後に実行されました。", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonLicense": "ルールを実行できません", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3d8f0576aa13d..baf98e70b8dd0 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -988,7 +988,6 @@ "dashboard.panel.copyToDashboard.goToDashboard": "复制并前往仪表板", "dashboard.panel.copyToDashboard.newDashboardOptionLabel": "新仪表板", "dashboard.panel.copyToDashboard.title": "复制到仪表板", - "dashboard.panel.invalidData": "url 中的数据无效", "dashboard.panel.LibraryNotification": "可视化库通知", "dashboard.panel.libraryNotification.ariaLabel": "查看库信息并取消链接此面板", "dashboard.panel.libraryNotification.toolTip": "编辑此面板可能会影响其他仪表板。要仅更改此面板,请取消其与库的链接。", @@ -6378,6 +6377,383 @@ "xpack.stackConnectors.xmatters.shouldNotHaveSecretsUrl": "usesBasic 为 true 时不得提供 secretsUrl", "xpack.stackConnectors.xmatters.shouldNotHaveUsernamePassword": "usesBasic 为 false 时不得提供用户名和密码", "xpack.stackConnectors.xmatters.title": "xMatters", + "xpack.stackConnectors.components.casesWebhook.error.missingVariables": "缺少所需{variableCount, plural, other {变量}}:{variables}", + "xpack.stackConnectors.components.index.error.badIndexOverrideValue": "告警历史记录索引必须以“{alertHistoryPrefix}”开头。", + "xpack.stackConnectors.components.email.error.invalidEmail": "电子邮件地址 {email} 无效。", + "xpack.stackConnectors.components.email.error.notAllowed": "不允许使用电子邮件地址 {email}。", + "xpack.stackConnectors.components.index.preconfiguredIndexHelpText": "文档已索引到 {alertHistoryIndex} 索引中。", + "xpack.stackConnectors.components.jira.unableToGetIssueMessage": "无法获取 ID 为 {id} 的问题", + "xpack.stackConnectors.components.pagerDuty.error.invalidTimestamp": "时间戳必须是有效的日期,例如 {nowShortFormat} 或 {nowLongFormat}。", + "xpack.stackConnectors.components.serviceNow.apiInfoError": "尝试获取应用程序信息时收到的状态:{status}", + "xpack.stackConnectors.components.serviceNow.appInstallationInfo": "{update} {create} ", + "xpack.stackConnectors.components.serviceNow.updateSuccessToastTitle": "{connectorName} 连接器已更新", + "xpack.stackConnectors.components.serviceNow.apiUrlHelpLabel": "提供所需 ServiceNow 实例的完整 URL。如果没有,{instance}。", + "xpack.stackConnectors.components.serviceNow.appRunning": "在运行更新之前,必须从 ServiceNow 应用商店安装 Elastic 应用。{visitLink} 以安装该应用", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationMessage": "无法获取 ID 为 {id} 的应用程序", + "xpack.stackConnectors.components.casesWebhook.commentsTextAreaFieldLabel": "其他注释", + "xpack.stackConnectors.components.casesWebhook.descriptionTextAreaFieldLabel": "描述", + "xpack.stackConnectors.components.casesWebhook.tagsFieldLabel": "标签", + "xpack.stackConnectors.components.casesWebhook.titleFieldLabel": "摘要(必填)", + "xpack.stackConnectors.components.casesWebhook.addHeaderButton": "添加", + "xpack.stackConnectors.components.casesWebhook.addVariable": "添加变量", + "xpack.stackConnectors.components.casesWebhook.authenticationLabel": "身份验证", + "xpack.stackConnectors.components.casesWebhook.caseCommentDesc": "Kibana 案例注释", + "xpack.stackConnectors.components.casesWebhook.caseDescriptionDesc": "Kibana 案例描述", + "xpack.stackConnectors.components.casesWebhook.caseTagsDesc": "Kibana 案例标签", + "xpack.stackConnectors.components.casesWebhook.caseTitleDesc": "Kibana 案例标题", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonHelp": "用于创建注释的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", + "xpack.stackConnectors.components.casesWebhook.createCommentJsonTextFieldLabel": "创建注释对象", + "xpack.stackConnectors.components.casesWebhook.createCommentMethodTextFieldLabel": "创建注释方法", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlHelp": "用于添加注释到案例的 API URL。", + "xpack.stackConnectors.components.casesWebhook.createCommentUrlTextFieldLabel": "创建注释 URL", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonHelpText": "用于创建案例的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", + "xpack.stackConnectors.components.casesWebhook.createIncidentJsonTextFieldLabel": "创建案例对象", + "xpack.stackConnectors.components.casesWebhook.createIncidentMethodTextFieldLabel": "创建案例方法", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyHelpText": "创建案例响应中包含外部案例 ID 的 JSON 键", + "xpack.stackConnectors.components.casesWebhook.createIncidentResponseKeyTextFieldLabel": "创建案例响应案例键", + "xpack.stackConnectors.components.casesWebhook.createIncidentUrlTextFieldLabel": "创建案例 URL", + "xpack.stackConnectors.components.casesWebhook.deleteHeaderButton": "删除", + "xpack.stackConnectors.components.casesWebhook.docLink": "正在配置 Webhook - 案例管理连接器。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentIncidentText": "创建注释对象必须为有效 JSON。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentUrlText": "创建注释 URL 必须为 URL 格式。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentText": "“创建案例对象”必填并且必须为有效 JSON。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateUrlText": "“创建案例 URL”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentUrlText": "“获取案例 URL”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateIncidentText": "“更新案例对象”必填并且必须为有效 JSON。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateUrlText": "“更新案例 URL”必填。", + "xpack.stackConnectors.components.casesWebhook.externalIdDesc": "外部系统 ID", + "xpack.stackConnectors.components.casesWebhook.externalTitleDesc": "外部系统标题", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyHelp": "获取案例响应中包含外部案例标题的 JSON 键", + "xpack.stackConnectors.components.casesWebhook.getIncidentResponseExternalTitleKeyTextFieldLabel": "获取案例响应外部标题键", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlHelp": "用于从外部系统中获取案例详情 JSON 的 API URL。使用变量选择器添加外部系统 ID 到 URL。", + "xpack.stackConnectors.components.casesWebhook.getIncidentUrlTextFieldLabel": "获取案例 URL", + "xpack.stackConnectors.components.casesWebhook.hasAuthSwitchLabel": "此 Webhook 需要身份验证", + "xpack.stackConnectors.components.casesWebhook.httpHeadersTitle": "在用的标头", + "xpack.stackConnectors.components.casesWebhook.jsonCodeEditorAriaLabel": "代码编辑器", + "xpack.stackConnectors.components.casesWebhook.jsonFieldLabel": "JSON", + "xpack.stackConnectors.components.casesWebhook.keyTextFieldLabel": "钥匙", + "xpack.stackConnectors.components.casesWebhook.next": "下一步", + "xpack.stackConnectors.components.casesWebhook.passwordTextFieldLabel": "密码", + "xpack.stackConnectors.components.casesWebhook.previous": "上一步", + "xpack.stackConnectors.components.casesWebhook.selectMessageText": "发送请求到案例管理 Web 服务。", + "xpack.stackConnectors.components.casesWebhook.step1": "设置连接器", + "xpack.stackConnectors.components.casesWebhook.step2": "创建案例", + "xpack.stackConnectors.components.casesWebhook.step2Description": "设置字段以在外部系统中创建案例。查阅您服务的 API 文档以了解需要哪些字段", + "xpack.stackConnectors.components.casesWebhook.step3": "获取案例信息", + "xpack.stackConnectors.components.casesWebhook.step3Description": "设置字段以在外部系统中添加案例注释。对于某些系统,这可能采取与在案例中创建更新相同的方法。查阅您服务的 API 文档以了解需要哪些字段。", + "xpack.stackConnectors.components.casesWebhook.step4": "注释和更新", + "xpack.stackConnectors.components.casesWebhook.step4a": "在案例中创建更新", + "xpack.stackConnectors.components.casesWebhook.step4aDescription": "设置字段以在外部系统中创建案例更新。对于某些系统,这可能采取与添加案例注释相同的方法。", + "xpack.stackConnectors.components.casesWebhook.step4b": "在案例中添加注释", + "xpack.stackConnectors.components.casesWebhook.step4bDescription": "设置字段以在外部系统中添加案例注释。对于某些系统,这可能采取与在案例中创建更新相同的方法。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonHelpl": "用于更新案例的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentJsonTextFieldLabel": "更新案例对象", + "xpack.stackConnectors.components.casesWebhook.updateIncidentMethodTextFieldLabel": "更新案例方法", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlHelp": "用于更新案例的 API URL。", + "xpack.stackConnectors.components.casesWebhook.updateIncidentUrlTextFieldLabel": "更新案例 URL", + "xpack.stackConnectors.components.casesWebhook.userTextFieldLabel": "用户名", + "xpack.stackConnectors.components.casesWebhook.valueTextFieldLabel": "值", + "xpack.stackConnectors.components.casesWebhook.viewHeadersSwitch": "添加 HTTP 标头", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlHelp": "用于查看外部系统中的案例的 URL。使用变量选择器添加外部系统 ID 或外部系统标题到 URL。", + "xpack.stackConnectors.components.casesWebhook.viewIncidentUrlTextFieldLabel": "外部案例查看 URL", + "xpack.stackConnectors.components.serviceNow.requiredShortDescTextField": "“简短描述”必填。", + "xpack.stackConnectors.components.email.exchangeForm.clientIdHelpLabel": "配置客户端 ID", + "xpack.stackConnectors.components.email.exchangeForm.clientSecretHelpLabel": "配置客户端密钥", + "xpack.stackConnectors.components.email.exchangeForm.tenantIdHelpLabel": "配置租户 ID", + "xpack.stackConnectors.components.email.connectorTypeTitle": "发送到电子邮件", + "xpack.stackConnectors.components.email.amazonSesServerTypeLabel": "Amazon SES", + "xpack.stackConnectors.components.email.configureAccountsHelpLabel": "配置电子邮件帐户", + "xpack.stackConnectors.components.email.elasticCloudServerTypeLabel": "Elastic Cloud", + "xpack.stackConnectors.components.email.exchangeServerTypeLabel": "MS Exchange Server", + "xpack.stackConnectors.components.email.gmailServerTypeLabel": "Gmail", + "xpack.stackConnectors.components.email.otherServerTypeLabel": "其他", + "xpack.stackConnectors.components.email.outlookServerTypeLabel": "Outlook", + "xpack.stackConnectors.components.email.selectMessageText": "从您的服务器发送电子邮件。", + "xpack.stackConnectors.components.email.updateErrorNotificationText": "无法获取服务配置", + "xpack.stackConnectors.components.index.error.badIndexOverrideSuffix": "告警历史记录索引必须包含有效的后缀。", + "xpack.stackConnectors.components.email.error.invalidPortText": "端口无效。", + "xpack.stackConnectors.components.email.error.requiredAuthUserNameText": "“用户名”必填。", + "xpack.stackConnectors.components.email.error.requiredClientIdText": "“客户端 ID”必填。", + "xpack.stackConnectors.components.index.error.requiredDocumentJson": "“文档”必填,并且应为有效的 JSON 对象。", + "xpack.stackConnectors.components.email.error.requiredEntryText": "未输入收件人、抄送、密送。 至少需要输入一个。", + "xpack.stackConnectors.components.email.error.requiredFromText": "“发送者”必填。", + "xpack.stackConnectors.components.email.error.requiredHostText": "“主机”必填。", + "xpack.stackConnectors.components.email.error.requiredMessageText": "“消息”必填。", + "xpack.stackConnectors.components.email.error.requiredPortText": "“端口”必填。", + "xpack.stackConnectors.components.serverLog.error.requiredServerLogMessageText": "“消息”必填。", + "xpack.stackConnectors.components.email.error.requiredServiceText": "“服务”必填。", + "xpack.stackConnectors.components.email.error.requiredSubjectText": "“主题”必填。", + "xpack.stackConnectors.components.email.error.requiredTenantIdText": "“租户 ID”必填。", + "xpack.stackConnectors.components.webhook.error.requiredWebhookBodyText": "“正文”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredWebhookSummaryText": "“标题”必填。", + "xpack.stackConnectors.components.index.connectorTypeTitle": "索引数据", + "xpack.stackConnectors.components.index.configureIndexHelpLabel": "配置索引连接器。", + "xpack.stackConnectors.components.index.connectorSectionTitle": "写入到索引", + "xpack.stackConnectors.components.index.definedateFieldTooltip": "将此时间字段设置为索引文档的时间。", + "xpack.stackConnectors.components.index.defineTimeFieldLabel": "为每个文档定义时间字段", + "xpack.stackConnectors.components.index.documentsFieldLabel": "要索引的文档", + "xpack.stackConnectors.components.index.error.notValidIndexText": "索引无效。", + "xpack.stackConnectors.components.index.executionTimeFieldLabel": "时间字段", + "xpack.stackConnectors.components.index.howToBroadenSearchQueryDescription": "使用 * 可扩大您的查询范围。", + "xpack.stackConnectors.components.index.indexDocumentHelpLabel": "索引文档示例。", + "xpack.stackConnectors.components.index.indicesToQueryLabel": "索引", + "xpack.stackConnectors.components.index.jsonDocAriaLabel": "代码编辑器", + "xpack.stackConnectors.components.index.preconfiguredIndex": "Elasticsearch 索引", + "xpack.stackConnectors.components.index.preconfiguredIndexDocLink": "查看文档。", + "xpack.stackConnectors.components.index.refreshLabel": "刷新索引", + "xpack.stackConnectors.components.index.refreshTooltip": "刷新影响的分片以使此操作对搜索可见。", + "xpack.stackConnectors.components.index.selectMessageText": "将数据索引到 Elasticsearch 中。", + "xpack.stackConnectors.components.jira.connectorTypeTitle": "Jira", + "xpack.stackConnectors.components.jira.apiTokenTextFieldLabel": "API 令牌", + "xpack.stackConnectors.components.jira.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.jira.commentsTextAreaFieldLabel": "其他注释", + "xpack.stackConnectors.components.jira.descriptionTextAreaFieldLabel": "描述", + "xpack.stackConnectors.components.jira.emailTextFieldLabel": "电子邮件地址", + "xpack.stackConnectors.components.jira.impactSelectFieldLabel": "标签", + "xpack.stackConnectors.components.jira.labelsSpacesErrorMessage": "标签不能包含空格。", + "xpack.stackConnectors.components.jira.parentIssueSearchLabel": "父问题", + "xpack.stackConnectors.components.jira.projectKey": "项目键", + "xpack.stackConnectors.components.jira.requiredSummaryTextField": "“摘要”必填。", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxAriaLabel": "键入内容进行搜索", + "xpack.stackConnectors.components.jira.searchIssuesComboBoxPlaceholder": "键入内容进行搜索", + "xpack.stackConnectors.components.jira.searchIssuesLoading": "正在加载……", + "xpack.stackConnectors.components.jira.selectMessageText": "在 Jira 创建事件。", + "xpack.stackConnectors.components.jira.severitySelectFieldLabel": "优先级", + "xpack.stackConnectors.components.jira.summaryFieldLabel": "摘要(必填)", + "xpack.stackConnectors.components.jira.unableToGetFieldsMessage": "无法获取字段", + "xpack.stackConnectors.components.jira.unableToGetIssuesMessage": "无法获取问题", + "xpack.stackConnectors.components.jira.unableToGetIssueTypesMessage": "无法获取问题类型", + "xpack.stackConnectors.components.jira.urgencySelectFieldLabel": "问题类型", + "xpack.stackConnectors.components.pagerDuty.connectorTypeTitle": "发送到 PagerDuty", + "xpack.stackConnectors.components.pagerDuty.apiUrlInvalid": "API URL 无效", + "xpack.stackConnectors.components.pagerDuty.apiUrlTextFieldLabel": "API URL(可选)", + "xpack.stackConnectors.components.pagerDuty.classFieldLabel": "类(可选)", + "xpack.stackConnectors.components.pagerDuty.componentTextFieldLabel": "组件(可选)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextFieldLabel": "DedupKey(可选)", + "xpack.stackConnectors.components.pagerDuty.dedupKeyTextRequiredFieldLabel": "DedupKey", + "xpack.stackConnectors.components.pagerDuty.error.requiredDedupKeyText": "解决或确认事件时需要 DedupKey。", + "xpack.stackConnectors.components.pagerDuty.error.requiredRoutingKeyText": "需要集成密钥/路由密钥。", + "xpack.stackConnectors.components.pagerDuty.error.requiredSummaryText": "“摘要”必填。", + "xpack.stackConnectors.components.pagerDuty.eventActionSelectFieldLabel": "事件操作", + "xpack.stackConnectors.components.pagerDuty.eventSelectAcknowledgeOptionLabel": "确认", + "xpack.stackConnectors.components.pagerDuty.eventSelectResolveOptionLabel": "解决", + "xpack.stackConnectors.components.pagerDuty.eventSelectTriggerOptionLabel": "触发", + "xpack.stackConnectors.components.pagerDuty.groupTextFieldLabel": "组(可选)", + "xpack.stackConnectors.components.pagerDuty.routingKeyNameHelpLabel": "配置 PagerDuty 帐户", + "xpack.stackConnectors.components.pagerDuty.routingKeyTextFieldLabel": "集成密钥", + "xpack.stackConnectors.components.pagerDuty.selectMessageText": "在 PagerDuty 中发送事件。", + "xpack.stackConnectors.components.pagerDuty.severitySelectCriticalOptionLabel": "紧急", + "xpack.stackConnectors.components.pagerDuty.severitySelectErrorOptionLabel": "错误", + "xpack.stackConnectors.components.pagerDuty.severitySelectFieldLabel": "严重性(可选)", + "xpack.stackConnectors.components.pagerDuty.severitySelectInfoOptionLabel": "信息", + "xpack.stackConnectors.components.pagerDuty.severitySelectWarningOptionLabel": "警告", + "xpack.stackConnectors.components.pagerDuty.sourceTextFieldLabel": "源(可选)", + "xpack.stackConnectors.components.pagerDuty.summaryFieldLabel": "摘要", + "xpack.stackConnectors.components.pagerDuty.timestampTextFieldLabel": "时间戳(可选)", + "xpack.stackConnectors.components.resilient.connectorTypeTitle": "Resilient", + "xpack.stackConnectors.components.resilient.apiKeyId": "API 密钥 ID", + "xpack.stackConnectors.components.resilient.apiKeySecret": "API 密钥密码", + "xpack.stackConnectors.components.resilient.apiUrlTextFieldLabel": "URL", + "xpack.stackConnectors.components.resilient.commentsTextAreaFieldLabel": "其他注释", + "xpack.stackConnectors.components.resilient.descriptionTextAreaFieldLabel": "描述", + "xpack.stackConnectors.components.resilient.nameFieldLabel": "名称(必填)", + "xpack.stackConnectors.components.resilient.orgId": "组织 ID", + "xpack.stackConnectors.components.resilient.requiredNameTextField": "“名称”必填。", + "xpack.stackConnectors.components.resilient.selectMessageText": "在 IBM Resilient 中创建事件。", + "xpack.stackConnectors.components.resilient.severity": "严重性", + "xpack.stackConnectors.components.resilient.unableToGetIncidentTypesMessage": "无法获取事件类型", + "xpack.stackConnectors.components.resilient.unableToGetSeverityMessage": "无法获取严重性", + "xpack.stackConnectors.components.resilient.urgencySelectFieldLabel": "事件类型", + "xpack.stackConnectors.components.serverLog.connectorTypeTitle": "发送到服务器日志", + "xpack.stackConnectors.components.serverLog.logLevelFieldLabel": "级别", + "xpack.stackConnectors.components.serverLog.logMessageFieldLabel": "消息", + "xpack.stackConnectors.components.serverLog.selectMessageText": "将消息添加到 Kibana 日志。", + "xpack.stackConnectors.components.serviceNow.apiUrlTextFieldLabel": "ServiceNow 实例 URL", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout": "未安装 Elastic ServiceNow 应用", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.content": "请前往 ServiceNow 应用商店并安装该应用程序", + "xpack.stackConnectors.components.serviceNow.applicationRequiredCallout.errorMessage": "错误消息", + "xpack.stackConnectors.components.serviceNow.authenticationLabel": "身份验证", + "xpack.stackConnectors.components.serviceNow.cancelButtonText": "取消", + "xpack.stackConnectors.components.serviceNow.categoryTitle": "类别", + "xpack.stackConnectors.components.serviceNow.clientIdTextFieldLabel": "客户端 ID", + "xpack.stackConnectors.components.serviceNow.clientSecretTextFieldLabel": "客户端密钥", + "xpack.stackConnectors.components.serviceNow.commentsTextAreaFieldLabel": "其他注释", + "xpack.stackConnectors.components.serviceNow.confirmButtonText": "更新", + "xpack.stackConnectors.components.serviceNow.correlationDisplay": "相关性显示(可选)", + "xpack.stackConnectors.components.serviceNow.correlationID": "相关性 ID(可选)", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutCreate": "或新建一个。", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutMigrate": "更新此连接器,", + "xpack.stackConnectors.components.serviceNow.deprecatedCalloutTitle": "此连接器类型已过时", + "xpack.stackConnectors.components.serviceNow.descriptionTextAreaFieldLabel": "描述", + "xpack.stackConnectors.components.serviceNow.eventClassTextAreaFieldLabel": "源实例", + "xpack.stackConnectors.components.serviceNow.fetchErrorMsg": "无法提取。检查 ServiceNow 实例的 URL 或 CORS 配置。", + "xpack.stackConnectors.components.serviceNow.impactSelectFieldLabel": "影响", + "xpack.stackConnectors.components.serviceNow.installationCalloutTitle": "要使用此连接器,请先从 ServiceNow 应用商店安装 Elastic 应用。", + "xpack.stackConnectors.components.serviceNow.invalidApiUrlTextField": "URL 无效。", + "xpack.stackConnectors.components.serviceNow.keyIdTextFieldLabel": "JWT Verifier 密钥 ID", + "xpack.stackConnectors.components.serviceNow.messageKeyTextAreaFieldLabel": "消息密钥", + "xpack.stackConnectors.components.serviceNow.metricNameTextAreaFieldLabel": "指标名称", + "xpack.stackConnectors.components.serviceNow.nodeTextAreaFieldLabel": "节点", + "xpack.stackConnectors.components.serviceNow.passwordTextFieldLabel": "密码", + "xpack.stackConnectors.components.serviceNow.prioritySelectFieldLabel": "优先级", + "xpack.stackConnectors.components.serviceNow.privateKeyPassLabelHelpText": "仅在设置了私钥密码时才需要此项", + "xpack.stackConnectors.components.serviceNow.privateKeyPassTextFieldLabel": "私钥密码", + "xpack.stackConnectors.components.serviceNow.privateKeyTextFieldLabel": "私钥", + "xpack.stackConnectors.components.serviceNow.requiredClientIdTextField": "“客户端 ID”必填。", + "xpack.stackConnectors.components.serviceNow.requiredKeyIdTextField": "JWT Verifier 密钥 ID 必填。", + "xpack.stackConnectors.components.serviceNow.requiredPrivateKeyTextField": "“私钥”必填。", + "xpack.stackConnectors.components.serviceNow.requiredSeverityTextField": "“严重性”必填。", + "xpack.stackConnectors.components.serviceNow.requiredUserIdentifierTextField": "“用户标识符”必填。", + "xpack.stackConnectors.components.serviceNow.requiredUsernameTextField": "“用户名”必填。", + "xpack.stackConnectors.components.serviceNow.resourceTextAreaFieldLabel": "资源", + "xpack.stackConnectors.components.serviceNow.setupDevInstance": "设置开发者实例", + "xpack.stackConnectors.components.serviceNow.severityRequiredSelectFieldLabel": "严重性(必需)", + "xpack.stackConnectors.components.serviceNow.severitySelectFieldLabel": "严重性", + "xpack.stackConnectors.components.serviceNow.snInstanceLabel": "ServiceNow 实例", + "xpack.stackConnectors.components.serviceNow.sourceTextAreaFieldLabel": "源", + "xpack.stackConnectors.components.serviceNow.subcategoryTitle": "子类别", + "xpack.stackConnectors.components.serviceNow.title": "事件", + "xpack.stackConnectors.components.serviceNow.titleFieldLabel": "简短描述(必填)", + "xpack.stackConnectors.components.serviceNow.typeTextAreaFieldLabel": "类型", + "xpack.stackConnectors.components.serviceNow.unableToGetChoicesMessage": "无法获取选项", + "xpack.stackConnectors.components.serviceNow.unknown": "未知", + "xpack.stackConnectors.components.serviceNow.updateCalloutText": "连接器已更新。", + "xpack.stackConnectors.components.serviceNow.updateFormCredentialsTitle": "提供身份验证凭据", + "xpack.stackConnectors.components.serviceNow.updateFormInstallTitle": "安装 Elastic ServiceNow 应用", + "xpack.stackConnectors.components.serviceNow.updateFormTitle": "更新 ServiceNow 连接器", + "xpack.stackConnectors.components.serviceNow.updateFormUrlTitle": "输入 ServiceNow 实例 URL", + "xpack.stackConnectors.components.serviceNow.urgencySelectFieldLabel": "紧急性", + "xpack.stackConnectors.components.serviceNow.useOAuth": "使用 OAuth 身份验证", + "xpack.stackConnectors.components.serviceNow.userEmailTextFieldLabel": "用户标识符", + "xpack.stackConnectors.components.serviceNow.usernameTextFieldLabel": "用户名", + "xpack.stackConnectors.components.serviceNow.visitSNStore": "访问 ServiceNow 应用商店", + "xpack.stackConnectors.components.serviceNow.warningMessage": "这会更新此连接器的所有实例并且无法恢复。", + "xpack.stackConnectors.components.serviceNow.correlationIDHelpLabel": "用于更新事件的标识符", + "xpack.stackConnectors.components.serviceNowITOM.connectorTypeTitle": "ServiceNow ITOM", + "xpack.stackConnectors.components.serviceNowITOM.event": "事件", + "xpack.stackConnectors.components.serviceNowITOM.selectMessageText": "在 ServiceNow ITOM 中创建事件。", + "xpack.stackConnectors.components.serviceNowITSM.connectorTypeTitle": "ServiceNow ITSM", + "xpack.stackConnectors.components.serviceNowITSM.selectMessageText": "在 ServiceNow ITSM 中创建事件。", + "xpack.stackConnectors.components.serviceNowSIR.connectorTypeTitle": "ServiceNow SecOps", + "xpack.stackConnectors.components.serviceNowSIR.selectMessageText": "在 ServiceNow SecOps 中创建事件。", + "xpack.stackConnectors.components.serviceNowSIR.title": "安全事件", + "xpack.stackConnectors.components.serviceNowSIR.correlationIDHelpLabel": "用于更新事件的标识符", + "xpack.stackConnectors.components.slack.connectorTypeTitle": "发送到 Slack", + "xpack.stackConnectors.components.slack.error.invalidWebhookUrlText": "Webhook URL 无效。", + "xpack.stackConnectors.components.slack.messageTextAreaFieldLabel": "消息", + "xpack.stackConnectors.components.slack.selectMessageText": "向 Slack 频道或用户发送消息。", + "xpack.stackConnectors.components.slack.webhookUrlHelpLabel": "创建 Slack webhook URL", + "xpack.stackConnectors.components.slack.webhookUrlTextFieldLabel": "Webhook URL", + "xpack.stackConnectors.components.swimlane.unableToGetApplicationFieldsMessage": "无法获取应用程序字段", + "xpack.stackConnectors.components.swimlane.connectorTypeTitle": "创建泳道记录", + "xpack.stackConnectors.components.swimlane.alertIdFieldLabel": "告警 ID", + "xpack.stackConnectors.components.swimlane.apiTokenNameHelpLabel": "提供泳道 API 令牌", + "xpack.stackConnectors.components.swimlane.apiTokenTextFieldLabel": "API 令牌", + "xpack.stackConnectors.components.swimlane.apiUrlTextFieldLabel": "API URL", + "xpack.stackConnectors.components.swimlane.appIdTextFieldLabel": "应用程序 ID", + "xpack.stackConnectors.components.swimlane.caseIdFieldLabel": "案例 ID", + "xpack.stackConnectors.components.swimlane.caseNameFieldLabel": "案例名称", + "xpack.stackConnectors.components.swimlane.commentsFieldLabel": "注释", + "xpack.stackConnectors.components.swimlane.configureConnectionLabel": "配置 API 连接", + "xpack.stackConnectors.components.swimlane.connectorType": "连接器类型", + "xpack.stackConnectors.components.swimlane.descriptionFieldLabel": "描述", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningDesc": "无法选择此连接器,因为其缺失所需的告警字段映射。您可以编辑此连接器以添加所需的字段映射或选择告警类型的连接器。", + "xpack.stackConnectors.components.swimlane.emptyMappingWarningTitle": "此连接器缺失字段映射", + "xpack.stackConnectors.components.swimlane.error.requiredAlertID": "“告警 ID”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredAppIdText": "“应用 ID”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredCaseID": "“案例 ID”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredCaseName": "“案例名称”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredComments": "“注释”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredDescription": "“描述”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredRuleName": "“规则名称”必填。", + "xpack.stackConnectors.components.swimlane.error.requiredSeverity": "“严重性”必填。", + "xpack.stackConnectors.components.swimlane.invalidApiUrlTextField": "URL 无效。", + "xpack.stackConnectors.components.swimlane.mappingTitleTextFieldLabel": "配置字段映射", + "xpack.stackConnectors.components.swimlane.nextStep": "下一步", + "xpack.stackConnectors.components.swimlane.nextStepHelpText": "如果未配置字段映射,泳道连接器类型将设置为 all。", + "xpack.stackConnectors.components.swimlane.prevStep": "返回", + "xpack.stackConnectors.components.swimlane.ruleNameFieldLabel": "规则名称", + "xpack.stackConnectors.components.swimlane.selectMessageText": "在泳道中创建记录", + "xpack.stackConnectors.components.swimlane.severityFieldLabel": "严重性", + "xpack.stackConnectors.components.teams.connectorTypeTitle": "向 Microsoft Teams 频道发送消息。", + "xpack.stackConnectors.components.teams.error.invalidWebhookUrlText": "Webhook URL 无效。", + "xpack.stackConnectors.components.teams.error.requiredMessageText": "“消息”必填。", + "xpack.stackConnectors.components.teams.error.webhookUrlTextLabel": "Webhook URL", + "xpack.stackConnectors.components.teams.messageTextAreaFieldLabel": "消息", + "xpack.stackConnectors.components.teams.selectMessageText": "向 Microsoft Teams 频道发送消息。", + "xpack.stackConnectors.components.teams.webhookUrlHelpLabel": "创建 Microsoft Teams Webhook URL", + "xpack.stackConnectors.components.webhook.connectorTypeTitle": "Webhook 数据", + "xpack.stackConnectors.components.webhook.addHeaderButtonLabel": "添加标头", + "xpack.stackConnectors.components.webhook.authenticationLabel": "身份验证", + "xpack.stackConnectors.components.webhook.bodyCodeEditorAriaLabel": "代码编辑器", + "xpack.stackConnectors.components.webhook.bodyFieldLabel": "正文", + "xpack.stackConnectors.components.webhook.error.invalidUrlTextField": "URL 无效。", + "xpack.stackConnectors.components.webhook.hasAuthSwitchLabel": "此 Webhook 需要身份验证", + "xpack.stackConnectors.components.webhook.headerKeyTextFieldLabel": "钥匙", + "xpack.stackConnectors.components.webhook.headerValueTextFieldLabel": "值", + "xpack.stackConnectors.components.webhook.methodTextFieldLabel": "方法", + "xpack.stackConnectors.components.webhook.passwordTextFieldLabel": "密码", + "xpack.stackConnectors.components.webhook.removeHeaderIconLabel": "钥匙", + "xpack.stackConnectors.components.webhook.selectMessageText": "将请求发送到 Web 服务。", + "xpack.stackConnectors.components.webhook.urlTextFieldLabel": "URL", + "xpack.stackConnectors.components.webhook.userTextFieldLabel": "用户名", + "xpack.stackConnectors.components.webhook.viewHeadersSwitch": "添加 HTTP 标头", + "xpack.stackConnectors.components.xmatters.connectorTypeTitle": "xMatters 数据", + "xpack.stackConnectors.components.xmatters.authenticationLabel": "身份验证", + "xpack.stackConnectors.components.xmatters.basicAuthButtonGroupLegend": "基本身份验证", + "xpack.stackConnectors.components.xmatters.basicAuthLabel": "基本身份验证", + "xpack.stackConnectors.components.xmatters.connectorSettingsLabel": "选择在设置 xMatters 触发器时使用的身份验证方法。", + "xpack.stackConnectors.components.xmatters.error.invalidUrlTextField": "URL 无效。", + "xpack.stackConnectors.components.xmatters.error.invalidUsernameTextField": "用户名无效。", + "xpack.stackConnectors.components.xmatters.error.requiredUrlText": "“URL”必填。", + "xpack.stackConnectors.components.xmatters.initiationUrlHelpText": "包括完整 xMatters url。", + "xpack.stackConnectors.components.xmatters.passwordTextFieldLabel": "密码", + "xpack.stackConnectors.components.xmatters.selectMessageText": "触发 xMatters 工作流。", + "xpack.stackConnectors.components.xmatters.severity": "严重性", + "xpack.stackConnectors.components.xmatters.severitySelectCriticalOptionLabel": "紧急", + "xpack.stackConnectors.components.xmatters.severitySelectHighOptionLabel": "高", + "xpack.stackConnectors.components.xmatters.severitySelectLowOptionLabel": "低", + "xpack.stackConnectors.components.xmatters.severitySelectMediumOptionLabel": "中", + "xpack.stackConnectors.components.xmatters.severitySelectMinimalOptionLabel": "最小", + "xpack.stackConnectors.components.xmatters.tags": "标签", + "xpack.stackConnectors.components.xmatters.urlAuthLabel": "URL 身份验证", + "xpack.stackConnectors.components.xmatters.urlLabel": "发起 URL", + "xpack.stackConnectors.components.xmatters.userCredsLabel": "用户凭据", + "xpack.stackConnectors.components.xmatters.userTextFieldLabel": "用户名", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningDesc": "为连接器配置“创建注释 URL”和“创建注释对象”字段以在外部共享注释。", + "xpack.stackConnectors.components.casesWebhook.createCommentWarningTitle": "无法共享案例注释", + "xpack.stackConnectors.components.serviceNow.deprecatedTooltipTitle": "过时连接器", + "xpack.stackConnectors.components.casesWebhook.error.requiredAuthUserNameText": "“用户名”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateCommentMethodText": "“创建注释方法”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateIncidentResponseKeyText": "“创建案例响应案例 ID 键”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredCreateMethodText": "“创建案例方法”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseCreatedKeyText": "“获取案例响应创建日期键”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseExternalTitleKeyText": "“获取案例响应外部案例标题键”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentResponseUpdatedKeyText": "“获取案例响应更新日期键”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredGetIncidentViewUrlKeyText": "“查看案例 URL”必填。", + "xpack.stackConnectors.components.casesWebhook.error.requiredUpdateMethodText": "“更新案例方法”必填。", + "xpack.stackConnectors.components.webhook.error.requiredAuthUserNameText": "“用户名”必填。", + "xpack.stackConnectors.components.webhook.error.requiredMethodText": "“方法”必填", + "xpack.stackConnectors.components.email.addBccButton": "密送", + "xpack.stackConnectors.components.email.addCcButton": "抄送", + "xpack.stackConnectors.components.email.authenticationLabel": "身份验证", + "xpack.stackConnectors.components.email.clientIdFieldLabel": "客户端 ID", + "xpack.stackConnectors.components.email.clientSecretTextFieldLabel": "客户端密钥", + "xpack.stackConnectors.components.email.fromTextFieldLabel": "发送者", + "xpack.stackConnectors.components.email.hasAuthSwitchLabel": "需要对此服务器进行身份验证", + "xpack.stackConnectors.components.email.hostTextFieldLabel": "主机", + "xpack.stackConnectors.components.email.messageTextAreaFieldLabel": "消息", + "xpack.stackConnectors.components.email.passwordFieldLabel": "密码", + "xpack.stackConnectors.components.email.portTextFieldLabel": "端口", + "xpack.stackConnectors.components.email.recipientBccTextFieldLabel": "密送", + "xpack.stackConnectors.components.email.recipientCopyTextFieldLabel": "抄送", + "xpack.stackConnectors.components.email.recipientTextFieldLabel": "至", + "xpack.stackConnectors.components.email.secureSwitchLabel": "安全", + "xpack.stackConnectors.components.email.serviceTextFieldLabel": "服务", + "xpack.stackConnectors.components.email.subjectTextFieldLabel": "主题", + "xpack.stackConnectors.components.email.tenantIdFieldLabel": "租户 ID", + "xpack.stackConnectors.components.email.userTextFieldLabel": "用户名", + "xpack.stackConnectors.components.index.resetDefaultIndexLabel": "重置默认索引", "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldCandidates": "已识别 {fieldCandidatesCount, plural, other {# 个字段候选项}}。", "xpack.aiops.explainLogRateSpikes.loadingState.identifiedFieldValuePairs": "已识别 {fieldValuePairsCount, plural, other {# 个重要的字段/值对}}。", "xpack.aiops.index.dataLoader.internalServerErrorMessage": "加载索引 {index} 中的数据时出错。{message}。请求可能已超时。请尝试使用较小的样例大小或缩小时间范围。", @@ -7170,7 +7546,6 @@ "xpack.apm.serviceGroups.selectServicesForm.preview": "预览", "xpack.apm.serviceGroups.selectServicesForm.refresh": "刷新", "xpack.apm.serviceGroups.selectServicesForm.saveGroup": "保存组", - "xpack.apm.serviceGroups.selectServicesForm.subtitle": "使用查询为该组选择服务。过去 24 小时内与此查询匹配的服务将分配给该组。", "xpack.apm.serviceGroups.selectServicesForm.title": "选择服务", "xpack.apm.serviceGroups.selectServicesList.environmentColumnLabel": "环境", "xpack.apm.serviceGroups.selectServicesList.nameColumnLabel": "名称", @@ -8914,7 +9289,6 @@ "xpack.cases.confirmDeleteCase.confirmQuestion": "删除{quantity, plural, =1 {此案例} other {这些案例}}即会永久移除所有相关案例数据,而且您将无法再将数据推送到外部事件管理系统。是否确定要继续?", "xpack.cases.confirmDeleteCase.deleteCase": "删除{quantity, plural, other {案例}}", "xpack.cases.confirmDeleteCase.deleteTitle": "删除“{caseTitle}”", - "xpack.cases.confirmDeleteCase.selectedCases": "删除“{quantity, plural, =1 {{title}} other {选定的 {quantity} 个案例}}”", "xpack.cases.connecors.get.missingCaseConnectorErrorMessage": "对象类型“{id}”未注册。", "xpack.cases.connecors.register.duplicateCaseConnectorErrorMessage": "已注册对象类型“{id}”。", "xpack.cases.connectors.card.createCommentWarningDesc": "为 {connectorName} 连接器配置“创建注释 URL”和“创建注释对象”字段以在外部共享注释。", @@ -8924,7 +9298,6 @@ "xpack.cases.connectors.cases.externalIncidentUpdated": "(由 {user} 于 {date}更新)", "xpack.cases.connectors.jira.unableToGetIssueMessage": "无法获取 ID 为 {id} 的问题", "xpack.cases.containers.closedCases": "已关闭{totalCases, plural, =1 {“{caseTitle}”} other { {totalCases} 个案例}}", - "xpack.cases.containers.deletedCases": "已删除{totalCases, plural, =1 {“{caseTitle}”} other { {totalCases} 个案例}}", "xpack.cases.containers.markInProgressCases": "已将{totalCases, plural, =1 {“{caseTitle}”} other { {totalCases} 个案例}}标记为进行中", "xpack.cases.containers.pushToExternalService": "已成功发送到 { serviceName }", "xpack.cases.containers.reopenedCases": "已打开{totalCases, plural, =1 {“{caseTitle}”} other { {totalCases} 个案例}}", @@ -8956,7 +9329,6 @@ "xpack.cases.caseTable.changeStatus": "更改状态", "xpack.cases.caseTable.closed": "已关闭", "xpack.cases.caseTable.closedCases": "已关闭案例", - "xpack.cases.caseTable.delete": "删除", "xpack.cases.caseTable.incidentSystem": "事件管理系统", "xpack.cases.caseTable.inProgressCases": "进行中的案例", "xpack.cases.caseTable.noCases.body": "创建案例或编辑筛选。", @@ -12513,9 +12885,7 @@ "xpack.fleet.unenrollAgents.forceDeleteMultipleTitle": "取消注册 {count} 个代理", "xpack.fleet.unenrollAgents.forceUnenrollCheckboxLabel": "立即移除{count, plural, other {代理}}。不用等待代理发送任何最终数据。", "xpack.fleet.unenrollAgents.forceUnenrollLegendText": "强制取消注册{count, plural, other {代理}}", - "xpack.fleet.upgradeAgents.bulkResultErrorResultsSummary": "{count} 个{count, plural, other {代理}}未成功", "xpack.fleet.upgradeAgents.hourLabel": "{option} {count, plural, other {小时}}", - "xpack.fleet.upgradeAgents.successSingleNotificationTitle": "正在升级 {count} 个代理", "xpack.fleet.upgradeAgents.upgradeMultipleDescription": "此操作会将多个代理升级到版本 {version}。此操作无法撤消。是否确定要继续?", "xpack.fleet.upgradeAgents.upgradeSingleDescription": "此操作会将“{hostName}”上运行的代理升级到版本 {version}。此操作无法撤消。是否确定要继续?", "xpack.fleet.upgradeAgents.warningCallout": "滚动升级仅适用于 Elastic 代理版本 {version} 及更高版本", @@ -13418,7 +13788,6 @@ "xpack.fleet.unenrollAgents.unenrollFleetServerTitle": "此代理正在运行 Fleet 服务器", "xpack.fleet.updateAgentTags.errorNotificationTitle": "标签更新失败", "xpack.fleet.updateAgentTags.successNotificationTitle": "标签已更新", - "xpack.fleet.upgradeAgents.bulkResultAllErrorsNotificationTitle": "升级{count, plural, one {代理} other { {count} 个代理} =true {所有选定代理}}时出错", "xpack.fleet.upgradeAgents.cancelButtonLabel": "取消", "xpack.fleet.upgradeAgents.chooseVersionLabel": "升级版本", "xpack.fleet.upgradeAgents.confirmMultipleButtonLabel": "升级{count, plural, one {代理} other { {count} 个代理} =true {所有选定代理}}", @@ -13554,9 +13923,6 @@ "xpack.graph.icon.tachometer": "转速表", "xpack.graph.icon.user": "用户", "xpack.graph.icon.users": "用户", - "xpack.graph.inspect.requestTabTitle": "请求", - "xpack.graph.inspect.responseTabTitle": "响应", - "xpack.graph.inspect.title": "检查", "xpack.graph.leaveWorkspace.confirmButtonLabel": "离开", "xpack.graph.leaveWorkspace.confirmText": "如果现在离开,将丢失未保存的更改。", "xpack.graph.leaveWorkspace.modalTitle": "未保存的更改", @@ -15117,8 +15483,6 @@ "xpack.infra.deprecations.tiebreakerAdjustIndexing": "调整索引以将“{field}”用作决胜属性。", "xpack.infra.deprecations.timestampAdjustIndexing": "调整索引以将“{field}”用作时间戳。", "xpack.infra.homePage.toolbar.showingLastOneMinuteDataText": "选定时间过去 {duration}的数据", - "xpack.infra.infrastructureMetricsExplorerPage.documentTitle": "{previousTitle} | 指标浏览器", - "xpack.infra.infrastructureSnapshotPage.documentTitle": "{previousTitle} | 库存", "xpack.infra.inventoryTimeline.header": "平均值 {metricLabel}", "xpack.infra.kibanaMetrics.cloudIdMissingErrorMessage": "{metricId} 的模型需要云 ID,但没有为 {nodeId} 提供。", "xpack.infra.kibanaMetrics.invalidInfraMetricErrorMessage": "{id} 不是有效的 InfraMetric", @@ -15158,7 +15522,6 @@ "xpack.infra.logs.searchResultTooltip": "{bucketCount, plural, other {# 个高亮条目}}", "xpack.infra.logs.showingEntriesFromTimestamp": "正在显示自 {timestamp} 起的条目", "xpack.infra.logs.showingEntriesUntilTimestamp": "正在显示截止于 {timestamp} 的条目", - "xpack.infra.logs.streamPage.documentTitle": "{previousTitle} | 流式传输", "xpack.infra.logs.viewInContext.logsFromContainerTitle": "显示的日志来自容器 {container}", "xpack.infra.logs.viewInContext.logsFromFileTitle": "显示的日志来自文件 {file} 和主机 {host}", "xpack.infra.logSourceConfiguration.invalidMessageFieldTypeErrorMessage": "{messageField} 字段必须是文本字段。", @@ -15167,8 +15530,7 @@ "xpack.infra.logSourceConfiguration.missingDataViewsLabel": "缺少数据视图 {indexPatternId}", "xpack.infra.logSourceConfiguration.missingMessageFieldErrorMessage": "数据视图必须包含 {messageField} 字段。", "xpack.infra.logSourceErrorPage.savedObjectNotFoundErrorMessage": "无法找到该{savedObjectType}:{savedObjectId}", - "xpack.infra.metricDetailPage.documentTitle": "Infrastructure | 指标 | {name}", - "xpack.infra.metricDetailPage.documentTitleError": "{previousTitle} | 啊哦", + "xpack.infra.metricDetailPage.documentTitleError": "啊哦", "xpack.infra.metrics.alertFlyout.alertPerRedundantFilterError": "此规则可能针对低于预期的 {matchedGroups} 告警,因为筛选查询包含{groupCount, plural, one {此字段} other {这些字段}}的匹配项。有关更多信息,请参阅 {filteringAndGroupingLink}。", "xpack.infra.metrics.alertFlyout.ofExpression.helpTextDetail": "找不到指标?{documentationLink}。", "xpack.infra.metrics.alerting.anomaly.summaryHigher": "高 {differential} 倍", @@ -15322,7 +15684,6 @@ "xpack.infra.header.logsTitle": "日志", "xpack.infra.header.observabilityTitle": "Observability", "xpack.infra.hideHistory": "隐藏历史记录", - "xpack.infra.homePage.documentTitle": "指标", "xpack.infra.homePage.inventoryTabTitle": "库存", "xpack.infra.homePage.metricsExplorerTabTitle": "指标浏览器", "xpack.infra.homePage.noMetricsIndicesInstructionsActionLabel": "查看设置说明", @@ -17127,7 +17488,6 @@ "xpack.lens.configure.invalidReferenceLineDimension": "此参考线分配给了不再存在的轴。您可以将此参考线移到其他可用的轴,或将其移除。", "xpack.lens.confirmModal.cancelButtonLabel": "取消", "xpack.lens.customBucketContainer.dragToReorder": "拖动以重新排序", - "xpack.lens.dataPanelWrapper.switchDatasource": "切换到数据源", "xpack.lens.datatable.addLayer": "可视化", "xpack.lens.datatable.breakdownColumns": "列", "xpack.lens.datatable.breakdownColumns.description": "按字段拆分指标列。建议减少列数目以避免水平滚动。", @@ -25338,9 +25698,6 @@ "xpack.securitySolution.endpoint.resolver.relatedEventLimitTitle": "此列表包括 {numberOfEntries} 个进程事件。", "xpack.securitySolution.endpointPolicyStatus.revisionNumber": "修订版 {revNumber}", "xpack.securitySolution.endpointResponseActions.actionError.errorMessage": "遇到以下{ errorCount, plural, other {错误}}:", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessage": "遇到以下错误:{error}", - "xpack.securitySolution.endpointResponseActions.killProcess.performApiErrorMessage": "遇到以下错误:{error}", - "xpack.securitySolution.endpointResponseActions.suspendProcess.performApiErrorMessage": "遇到以下错误:{error}", "xpack.securitySolution.event.reason.reasonRendererTitle": "事件渲染器:{eventRendererName} ", "xpack.securitySolution.eventDetails.nestedColumnCheckboxAriaLabel": "{field} 字段是对象,并分解为可以添加为列的嵌套字段", "xpack.securitySolution.eventDetails.viewColumnCheckboxAriaLabel": "查看 {field} 列", @@ -25499,7 +25856,6 @@ "xpack.securitySolution.usersTable.rows": "{numRows} {numRows, plural, other {行}}", "xpack.securitySolution.usersTable.unit": "{totalCount, plural, other {个用户}}", "xpack.securitySolution.accessibility.tooltipWithKeyboardShortcut.pressTooltipLabel": "按", - "xpack.securitySolution.actionLogButton.label": "操作日志", "xpack.securitySolution.actionsContextMenu.label": "打开", "xpack.securitySolution.administration.os.linux": "Linux", "xpack.securitySolution.administration.os.macos": "Mac", @@ -27274,7 +27630,6 @@ "xpack.securitySolution.effectedPolicySelect.assignmentSectionTitle": "分配", "xpack.securitySolution.effectedPolicySelect.viewPolicyLinkLabel": "查看策略", "xpack.securitySolution.emptyString.emptyStringDescription": "空字符串", - "xpack.securitySolution.endpoint.actions.actionsLog": "查看操作日志", "xpack.securitySolution.endpoint.actions.agentDetails": "查看代理详情", "xpack.securitySolution.endpoint.actions.agentPolicy": "查看代理策略", "xpack.securitySolution.endpoint.actions.agentPolicyReassign": "重新分配代理策略", @@ -27742,7 +28097,6 @@ "xpack.securitySolution.endpointConsoleCommands.suspendProcess.commandArgAbout": "此操作将伴随一条注释", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.entityId.arg.comment": "表示要挂起的进程的实体 ID", "xpack.securitySolution.endpointConsoleCommands.suspendProcess.pid.arg.comment": "表示要挂起的进程的 PID", - "xpack.securitySolution.endpointDetails.activityLog": "操作日志", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.endOfLog": "没有更多要显示的内容", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointIsolateAction": "无法提交请求:隔离主机", "xpack.securitySolution.endpointDetails.activityLog.logEntry.action.failedEndpointReleaseAction": "无法提交请求:释放主机", @@ -27763,8 +28117,6 @@ "xpack.securitySolution.endpointManagement.noPermissionsSubText": "您必须具有超级用户角色才能使用此功能。如果您不具有超级用户角色,且无权编辑用户角色,请与 Kibana 管理员联系。", "xpack.securitySolution.endpointManagemnet.noPermissionsText": "您没有所需的 Kibana 权限,无法使用 Elastic Security 管理", "xpack.securitySolution.endpointPolicyStatus.tooltipTitleLabel": "已应用策略", - "xpack.securitySolution.endpointResponseActions.getProcesses.errorMessageTitle": "获取进程操作失败", - "xpack.securitySolution.endpointResponseActions.getProcesses.performApiErrorMessageTitle": "执行获取进程操作失败", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.command": "命令", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.enityId": "实体 ID", "xpack.securitySolution.endpointResponseActions.getProcesses.table.header.pid": "PID", @@ -31844,20 +32196,7 @@ "xpack.triggersActionsUI.actionVariables.legacyTagsLabel": "其已弃用,将由 {variable} 替代。", "xpack.triggersActionsUI.checkActionTypeEnabled.actionTypeDisabledByLicenseMessage": "此连接器需要{minimumLicenseRequired}许可证。", "xpack.triggersActionsUI.checkRuleTypeEnabled.ruleTypeDisabledByLicenseMessage": "此规则类型需要{minimumLicenseRequired}许可证。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.missingVariables": "缺少所需{variableCount, plural, other {变量}}:{variables}", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideValue": "告警历史记录索引必须以“{alertHistoryPrefix}”开头。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidEmail": "电子邮件地址 {email} 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.notAllowed": "不允许使用电子邮件地址 {email}。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexHelpText": "文档已索引到 {alertHistoryIndex} 索引中。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueMessage": "无法获取 ID 为 {id} 的问题", "xpack.triggersActionsUI.components.builtinActionTypes.missingSecretsValuesLabel": "未导入敏感信息。请为以下字段{encryptedFieldsLength, plural, other {}} {secretFieldsLabel}输入值{encryptedFieldsLength, plural, other {}}。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.invalidTimestamp": "时间戳必须是有效的日期,例如 {nowShortFormat} 或 {nowLongFormat}。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiInfoError": "尝试获取应用程序信息时收到的状态:{status}", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.appInstallationInfo": "{update} {create} ", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateSuccessToastTitle": "{connectorName} 连接器已更新", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.apiUrlHelpLabel": "提供所需 ServiceNow 实例的完整 URL。如果没有,{instance}。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.serviceNowAppRunning": "在运行更新之前,必须从 ServiceNow 应用商店安装 Elastic 应用。{visitLink} 以安装该应用", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationMessage": "无法获取 ID 为 {id} 的应用程序", "xpack.triggersActionsUI.components.buttonGroupField.error.requiredField": "{label} 必填。", "xpack.triggersActionsUI.components.deleteSelectedIdsErrorNotification.descriptionText": "无法删除 {numErrors, number} 个{numErrors, plural, one {{singleTitle}} other {{multipleTitle}}}", "xpack.triggersActionsUI.components.passwordField.error.requiredNameText": "{label} 必填。", @@ -32013,340 +32352,6 @@ "xpack.triggersActionsUI.components.addMessageVariables.addRuleVariableTitle": "添加规则变量", "xpack.triggersActionsUI.components.addMessageVariables.addVariablePopoverButton": "添加变量", "xpack.triggersActionsUI.components.alertTable.useFetchAlerts.errorMessageText": "搜索告警时发生错误", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.commentsTextAreaFieldLabel": "其他注释", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.descriptionTextAreaFieldLabel": "描述", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.tagsFieldLabel": "标签", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhook.titleFieldLabel": "摘要(必填)", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.actionTypeTitle": "Webhook - 案例管理数据", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addHeaderButton": "添加", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addVariable": "添加变量", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseCommentDesc": "Kibana 案例注释", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseDescriptionDesc": "Kibana 案例描述", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTagsDesc": "Kibana 案例标签", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTitleDesc": "Kibana 案例标题", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonHelp": "用于创建注释的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonTextFieldLabel": "创建注释对象", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentMethodTextFieldLabel": "创建注释方法", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlHelp": "用于添加注释到案例的 API URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlTextFieldLabel": "创建注释 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonHelpText": "用于创建案例的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonTextFieldLabel": "创建案例对象", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentMethodTextFieldLabel": "创建案例方法", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyHelpText": "创建案例响应中包含外部案例 ID 的 JSON 键", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyTextFieldLabel": "创建案例响应案例键", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentUrlTextFieldLabel": "创建案例 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.deleteHeaderButton": "删除", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.docLink": "正在配置 Webhook - 案例管理连接器。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentIncidentText": "创建注释对象必须为有效 JSON。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentUrlText": "创建注释 URL 必须为 URL 格式。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateIncidentText": "“创建案例对象”必填并且必须为有效 JSON。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateUrlText": "“创建案例 URL”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredGetIncidentUrlText": "“获取案例 URL”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateIncidentText": "“更新案例对象”必填并且必须为有效 JSON。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateUrlText": "“更新案例 URL”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalIdDesc": "外部系统 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalTitleDesc": "外部系统标题", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyHelp": "获取案例响应中包含外部案例标题的 JSON 键", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyTextFieldLabel": "获取案例响应外部标题键", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlHelp": "用于从外部系统中获取案例详情 JSON 的 API URL。使用变量选择器添加外部系统 ID 到 URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlTextFieldLabel": "获取案例 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.hasAuthSwitchLabel": "此 Webhook 需要身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.httpHeadersTitle": "在用的标头", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonCodeEditorAriaLabel": "代码编辑器", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonFieldLabel": "JSON", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.keyTextFieldLabel": "钥匙", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.next": "下一步", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.passwordTextFieldLabel": "密码", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.previous": "上一步", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.selectMessageText": "发送请求到案例管理 Web 服务。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step1": "设置连接器", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2": "创建案例", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2Description": "设置字段以在外部系统中创建案例。查阅您服务的 API 文档以了解需要哪些字段", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3": "获取案例信息", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3Description": "设置字段以在外部系统中添加案例注释。对于某些系统,这可能采取与在案例中创建更新相同的方法。查阅您服务的 API 文档以了解需要哪些字段。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4": "注释和更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4a": "在案例中创建更新", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4aDescription": "设置字段以在外部系统中创建案例更新。对于某些系统,这可能采取与添加案例注释相同的方法。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4b": "在案例中添加注释", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4bDescription": "设置字段以在外部系统中添加案例注释。对于某些系统,这可能采取与在案例中创建更新相同的方法。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonHelpl": "用于更新案例的 JSON 对象。使用变量选择器将案例数据添加到有效负载。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonTextFieldLabel": "更新案例对象", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentMethodTextFieldLabel": "更新案例方法", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlHelp": "用于更新案例的 API URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlTextFieldLabel": "更新案例 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.userTextFieldLabel": "用户名", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.valueTextFieldLabel": "值", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewHeadersSwitch": "添加 HTTP 标头", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlHelp": "用于查看外部系统中的案例的 URL。使用变量选择器添加外部系统 ID 或外部系统标题到 URL。", - "xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlTextFieldLabel": "外部案例查看 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.common.requiredShortDescTextField": "“简短描述”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientIdHelpLabel": "配置客户端 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.clientSecretHelpLabel": "配置客户端密钥", - "xpack.triggersActionsUI.components.builtinActionTypes.email.exchangeForm.tenantIdHelpLabel": "配置租户 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.actionTypeTitle": "发送到电子邮件", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.amazonSesServerTypeLabel": "Amazon SES", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.configureAccountsHelpLabel": "配置电子邮件帐户", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.elasticCloudServerTypeLabel": "Elastic Cloud", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.exchangeServerTypeLabel": "MS Exchange Server", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.gmailServerTypeLabel": "Gmail", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.otherServerTypeLabel": "其他", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.outlookServerTypeLabel": "Outlook", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.selectMessageText": "从您的服务器发送电子邮件。", - "xpack.triggersActionsUI.components.builtinActionTypes.emailAction.updateErrorNotificationText": "无法获取服务配置", - "xpack.triggersActionsUI.components.builtinActionTypes.error.badIndexOverrideSuffix": "告警历史记录索引必须包含有效的后缀。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.invalidPortText": "端口无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredAuthUserNameText": "“用户名”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredClientIdText": "“客户端 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredDocumentJson": "“文档”必填,并且应为有效的 JSON 对象。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredEntryText": "未输入收件人、抄送、密送。 至少需要输入一个。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredFromText": "“发送者”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredHostText": "“主机”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredMessageText": "“消息”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredPortText": "“端口”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServerLogMessageText": "“消息”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredServiceText": "“服务”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSlackMessageText": "“消息”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredSubjectText": "“主题”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredTenantIdText": "“租户 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookBodyText": "“正文”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookSummaryText": "“标题”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.actionTypeTitle": "索引数据", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.chooseLabel": "选择……", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.configureIndexHelpLabel": "配置索引连接器。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.connectorSectionTitle": "写入到索引", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.definedateFieldTooltip": "将此时间字段设置为索引文档的时间。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.defineTimeFieldLabel": "为每个文档定义时间字段", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel": "要索引的文档", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.error.notValidIndexText": "索引无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.executionTimeFieldLabel": "时间字段", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.howToBroadenSearchQueryDescription": "使用 * 可扩大您的查询范围。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indexDocumentHelpLabel": "索引文档示例。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesAndIndexPatternsLabel": "基于您的数据视图", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.indicesToQueryLabel": "索引", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel": "代码编辑器", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndex": "Elasticsearch 索引", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.preconfiguredIndexDocLink": "查看文档。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshLabel": "刷新索引", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.refreshTooltip": "刷新影响的分片以使此操作对搜索可见。", - "xpack.triggersActionsUI.components.builtinActionTypes.indexAction.selectMessageText": "将数据索引到 Elasticsearch 中。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.actionTypeTitle": "Jira", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiTokenTextFieldLabel": "API 令牌", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.commentsTextAreaFieldLabel": "其他注释", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.descriptionTextAreaFieldLabel": "描述", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.emailTextFieldLabel": "电子邮件地址", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.impactSelectFieldLabel": "标签", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.labelsSpacesErrorMessage": "标签不能包含空格。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.parentIssueSearchLabel": "父问题", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.projectKey": "项目键", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.requiredSummaryTextField": "“摘要”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxAriaLabel": "键入内容进行搜索", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesComboBoxPlaceholder": "键入内容进行搜索", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.searchIssuesLoading": "正在加载……", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.selectMessageText": "在 Jira 创建事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.severitySelectFieldLabel": "优先级", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.summaryFieldLabel": "摘要(必填)", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetFieldsMessage": "无法获取字段", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssuesMessage": "无法获取问题", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.unableToGetIssueTypesMessage": "无法获取问题类型", - "xpack.triggersActionsUI.components.builtinActionTypes.jira.urgencySelectFieldLabel": "问题类型", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.actionTypeTitle": "发送到 PagerDuty", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlInvalid": "API URL 无效", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.apiUrlTextFieldLabel": "API URL(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.classFieldLabel": "类(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.componentTextFieldLabel": "组件(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextFieldLabel": "DedupKey(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextRequiredFieldLabel": "DedupKey", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredDedupKeyText": "解决或确认事件时需要 DedupKey。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredRoutingKeyText": "需要集成密钥/路由密钥。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredSummaryText": "“摘要”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventActionSelectFieldLabel": "事件操作", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectAcknowledgeOptionLabel": "确认", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectResolveOptionLabel": "解决", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.eventSelectTriggerOptionLabel": "触发", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.groupTextFieldLabel": "组(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyNameHelpLabel": "配置 PagerDuty 帐户", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.routingKeyTextFieldLabel": "集成密钥", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.selectMessageText": "在 PagerDuty 中发送事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectCriticalOptionLabel": "紧急", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectErrorOptionLabel": "错误", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectFieldLabel": "严重性(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectInfoOptionLabel": "信息", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.severitySelectWarningOptionLabel": "警告", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.sourceTextFieldLabel": "源(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.summaryFieldLabel": "摘要", - "xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.timestampTextFieldLabel": "时间戳(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.actionTypeTitle": "Resilient", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeyId": "API 密钥 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeySecret": "API 密钥密码", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiUrlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.commentsTextAreaFieldLabel": "其他注释", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.descriptionTextAreaFieldLabel": "描述", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.nameFieldLabel": "名称(必填)", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.orgId": "组织 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredNameTextField": "“名称”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.selectMessageText": "在 IBM Resilient 中创建事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.severity": "严重性", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetIncidentTypesMessage": "无法获取事件类型", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetSeverityMessage": "无法获取严重性", - "xpack.triggersActionsUI.components.builtinActionTypes.resilient.urgencySelectFieldLabel": "事件类型", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.actionTypeTitle": "发送到服务器日志", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logLevelFieldLabel": "级别", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.logMessageFieldLabel": "消息", - "xpack.triggersActionsUI.components.builtinActionTypes.serverLogAction.selectMessageText": "将消息添加到 Kibana 日志。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.apiUrlTextFieldLabel": "ServiceNow 实例 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout": "未安装 Elastic ServiceNow 应用", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.content": "请前往 ServiceNow 应用商店并安装该应用程序", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.applicationRequiredCallout.errorMessage": "错误消息", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.cancelButtonText": "取消", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.categoryTitle": "类别", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientIdTextFieldLabel": "客户端 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.clientSecretTextFieldLabel": "客户端密钥", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.commentsTextAreaFieldLabel": "其他注释", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.confirmButtonText": "更新", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationDisplay": "相关性显示(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.correlationID": "相关性 ID(可选)", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutCreate": "或新建一个。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutMigrate": "更新此连接器,", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.deprecatedCalloutTitle": "此连接器类型已过时", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.descriptionTextAreaFieldLabel": "描述", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.eventClassTextAreaFieldLabel": "源实例", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.fetchErrorMsg": "无法提取。检查 ServiceNow 实例的 URL 或 CORS 配置。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.impactSelectFieldLabel": "影响", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.installationCalloutTitle": "要使用此连接器,请先从 ServiceNow 应用商店安装 Elastic 应用。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.invalidApiUrlTextField": "URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.keyIdTextFieldLabel": "JWT Verifier 密钥 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.messageKeyTextAreaFieldLabel": "消息密钥", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.metricNameTextAreaFieldLabel": "指标名称", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.nodeTextAreaFieldLabel": "节点", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.passwordTextFieldLabel": "密码", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.prioritySelectFieldLabel": "优先级", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassLabelHelpText": "仅在设置了私钥密码时才需要此项", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyPassTextFieldLabel": "私钥密码", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.privateKeyTextFieldLabel": "私钥", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredClientIdTextField": "“客户端 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredKeyIdTextField": "JWT Verifier 密钥 ID 必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredPrivateKeyTextField": "“私钥”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredSeverityTextField": "“严重性”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUserIdentifierTextField": "“用户标识符”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.requiredUsernameTextField": "“用户名”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.resourceTextAreaFieldLabel": "资源", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.setupDevInstance": "设置开发者实例", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severityRequiredSelectFieldLabel": "严重性(必需)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.severitySelectFieldLabel": "严重性", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.snInstanceLabel": "ServiceNow 实例", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.sourceTextAreaFieldLabel": "源", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.subcategoryTitle": "子类别", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.title": "事件", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.titleFieldLabel": "简短描述(必填)", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.typeTextAreaFieldLabel": "类型", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unableToGetChoicesMessage": "无法获取选项", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.unknown": "未知", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.updateCalloutText": "连接器已更新。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormCredentialsTitle": "提供身份验证凭据", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormInstallTitle": "安装 Elastic ServiceNow 应用", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormTitle": "更新 ServiceNow 连接器", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.updateFormUrlTitle": "输入 ServiceNow 实例 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.urgencySelectFieldLabel": "紧急性", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.useOAuth": "使用 OAuth 身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.userEmailTextFieldLabel": "用户标识符", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.usernameTextFieldLabel": "用户名", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenow.visitSNStore": "访问 ServiceNow 应用商店", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNow.warningMessage": "这会更新此连接器的所有实例并且无法恢复。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowAction.correlationIDHelpLabel": "用于更新事件的标识符", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.actionTypeTitle": "ServiceNow ITOM", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowITOM.event": "事件", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITOM.selectMessageText": "在 ServiceNow ITOM 中创建事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.actionTypeTitle": "ServiceNow ITSM", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowITSM.selectMessageText": "在 ServiceNow ITSM 中创建事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.actionTypeTitle": "ServiceNow SecOps", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIR.selectMessageText": "在 ServiceNow SecOps 中创建事件。", - "xpack.triggersActionsUI.components.builtinActionTypes.servicenowSIR.title": "安全事件", - "xpack.triggersActionsUI.components.builtinActionTypes.serviceNowSIRAction.correlationIDHelpLabel": "用于更新事件的标识符", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.actionTypeTitle": "发送到 Slack", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.error.invalidWebhookUrlText": "Webhook URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.messageTextAreaFieldLabel": "消息", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.selectMessageText": "向 Slack 频道或用户发送消息。", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlHelpLabel": "创建 Slack webhook URL", - "xpack.triggersActionsUI.components.builtinActionTypes.slackAction.webhookUrlTextFieldLabel": "Webhook URL", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlane.unableToGetApplicationFieldsMessage": "无法获取应用程序字段", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.actionTypeTitle": "创建泳道记录", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.alertIdFieldLabel": "告警 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenNameHelpLabel": "提供泳道 API 令牌", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiTokenTextFieldLabel": "API 令牌", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.apiUrlTextFieldLabel": "API URL", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.appIdTextFieldLabel": "应用程序 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseIdFieldLabel": "案例 ID", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.caseNameFieldLabel": "案例名称", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.commentsFieldLabel": "注释", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.configureConnectionLabel": "配置 API 连接", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.connectorType": "连接器类型", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.descriptionFieldLabel": "描述", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningDesc": "无法选择此连接器,因为其缺失所需的告警字段映射。您可以编辑此连接器以添加所需的字段映射或选择告警类型的连接器。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.emptyMappingWarningTitle": "此连接器缺失字段映射", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAlertID": "“告警 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredAppIdText": "“应用 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseID": "“案例 ID”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredCaseName": "“案例名称”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredComments": "“注释”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredDescription": "“描述”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredRuleName": "“规则名称”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.error.requiredSeverity": "“严重性”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.invalidApiUrlTextField": "URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.mappingTitleTextFieldLabel": "配置字段映射", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStep": "下一步", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.nextStepHelpText": "如果未配置字段映射,泳道连接器类型将设置为 all。", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.prevStep": "返回", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.ruleNameFieldLabel": "规则名称", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.selectMessageText": "在泳道中创建记录", - "xpack.triggersActionsUI.components.builtinActionTypes.swimlaneAction.severityFieldLabel": "严重性", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.actionTypeTitle": "向 Microsoft Teams 频道发送消息。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.invalidWebhookUrlText": "Webhook URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.requiredMessageText": "“消息”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.error.webhookUrlTextLabel": "Webhook URL", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.messageTextAreaFieldLabel": "消息", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.selectMessageText": "向 Microsoft Teams 频道发送消息。", - "xpack.triggersActionsUI.components.builtinActionTypes.teamsAction.webhookUrlHelpLabel": "创建 Microsoft Teams Webhook URL", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.actionTypeTitle": "Webhook 数据", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.addHeaderButtonLabel": "添加标头", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyCodeEditorAriaLabel": "代码编辑器", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.bodyFieldLabel": "正文", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.error.invalidUrlTextField": "URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.hasAuthSwitchLabel": "此 Webhook 需要身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerKeyTextFieldLabel": "钥匙", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.headerValueTextFieldLabel": "值", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.methodTextFieldLabel": "方法", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.passwordTextFieldLabel": "密码", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.removeHeaderIconLabel": "钥匙", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.selectMessageText": "将请求发送到 Web 服务。", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.urlTextFieldLabel": "URL", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.userTextFieldLabel": "用户名", - "xpack.triggersActionsUI.components.builtinActionTypes.webhookAction.viewHeadersSwitch": "添加 HTTP 标头", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.actionTypeTitle": "xMatters 数据", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthButtonGroupLegend": "基本身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.basicAuthLabel": "基本身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.connectorSettingsLabel": "选择在设置 xMatters 触发器时使用的身份验证方法。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUrlTextField": "URL 无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.invalidUsernameTextField": "用户名无效。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.error.requiredUrlText": "“URL”必填。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.initiationUrlHelpText": "包括完整 xMatters url。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.passwordTextFieldLabel": "密码", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.selectMessageText": "触发 xMatters 工作流。", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severity": "严重性", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectCriticalOptionLabel": "紧急", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectHighOptionLabel": "高", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectLowOptionLabel": "低", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMediumOptionLabel": "中", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.severitySelectMinimalOptionLabel": "最小", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.tags": "标签", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlAuthLabel": "URL 身份验证", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.urlLabel": "发起 URL", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userCredsLabel": "用户凭据", - "xpack.triggersActionsUI.components.builtinActionTypes.xmattersAction.userTextFieldLabel": "用户名", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorButtonLabel": "创建连接器", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyBody": "配置电子邮件、Slack、Elasticsearch,以及 Kibana 运行的第三方服务。", "xpack.triggersActionsUI.components.emptyConnectorsPrompt.addConnectorEmptyTitle": "创建您的首个连接器", @@ -32368,8 +32373,6 @@ "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorMessage": "找不到编辑器,请刷新页面并重试", "xpack.triggersActionsUI.components.jsonEditorWithMessageVariable.noEditorErrorTitle": "无法添加消息变量", "xpack.triggersActionsUI.components.simpleConnectorForm.secrets.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningDesc": "为连接器配置“创建注释 URL”和“创建注释对象”字段以在外部共享注释。", - "xpack.triggersActionsUI.components.textAreaWithMessageVariable.createCommentWarningTitle": "无法共享案例注释", "xpack.triggersActionsUI.connectors.breadcrumbTitle": "连接器", "xpack.triggersActionsUI.data.coreQueryParams.dateStartGTdateEndErrorMessage": "[dateStart]:晚于 [dateEnd]", "xpack.triggersActionsUI.data.coreQueryParams.intervalRequiredErrorMessage": "[interval]:如果 [dateStart] 不等于 [dateEnd],则必须指定", @@ -32430,7 +32433,6 @@ "xpack.triggersActionsUI.ruleSnoozeScheduler.saveSchedule": "保存计划", "xpack.triggersActionsUI.ruleSnoozeScheduler.timezoneLabel": "时区", "xpack.triggersActionsUI.sections.actionConnectorAdd.backButtonLabel": "返回", - "xpack.triggersActionsUI.sections.actionConnectorAdd.cancelButtonLabel": "取消", "xpack.triggersActionsUI.sections.actionConnectorAdd.manageLicensePlanBannerLinkTitle": "管理许可证", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveAndTestButtonLabel": "保存并测试", "xpack.triggersActionsUI.sections.actionConnectorAdd.saveButtonLabel": "保存", @@ -32443,7 +32445,6 @@ "xpack.triggersActionsUI.sections.actionConnectorForm.loadingConnectorSettingsDescription": "正在加载连接器设置……", "xpack.triggersActionsUI.sections.actionForm.actionSectionsTitle": "操作", "xpack.triggersActionsUI.sections.actionForm.addActionButtonLabel": "添加操作", - "xpack.triggersActionsUI.sections.actionForm.deprecatedTooltipTitle": "过时连接器", "xpack.triggersActionsUI.sections.actionForm.getMoreConnectorsTitle": "获取更多连接器", "xpack.triggersActionsUI.sections.actionForm.getMoreRuleTypesTitle": "获取更多规则类型", "xpack.triggersActionsUI.sections.actionForm.incidentManagementSystemLabel": "事件管理系统", @@ -32482,17 +32483,6 @@ "xpack.triggersActionsUI.sections.actionTypeForm.actionErrorToolTip": "操作包含错误。", "xpack.triggersActionsUI.sections.actionTypeForm.actionRunWhenInActionGroup": "运行条件", "xpack.triggersActionsUI.sections.actionTypeForm.addNewConnectorEmptyButton": "添加连接器", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredAuthUserNameText": "“用户名”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateCommentMethodText": "“创建注释方法”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateIncidentResponseKeyText": "“创建案例响应案例 ID 键”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateMethodText": "“创建案例方法”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseCreatedKeyText": "“获取案例响应创建日期键”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseExternalTitleKeyText": "“获取案例响应外部案例标题键”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseUpdatedKeyText": "“获取案例响应更新日期键”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentViewUrlKeyText": "“查看案例 URL”必填。", - "xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredUpdateMethodText": "“更新案例方法”必填。", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredAuthUserNameText": "“用户名”必填。", - "xpack.triggersActionsUI.sections.addAction.webhookAction.error.requiredMethodText": "“方法”必填", "xpack.triggersActionsUI.sections.addConnectorForm.selectConnectorFlyoutTitle": "选择连接器", "xpack.triggersActionsUI.sections.addConnectorForm.updateSuccessNotificationText": "已创建“{connectorName}”", "xpack.triggersActionsUI.sections.addModalConnectorForm.cancelButtonLabel": "取消", @@ -32502,25 +32492,6 @@ "xpack.triggersActionsUI.sections.alertsTable.alertsFlyout.reason": "原因", "xpack.triggersActionsUI.sections.alertsTable.column.actions": "操作", "xpack.triggersActionsUI.sections.alertsTable.leadingControl.viewDetails": "查看详情", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addBccButton": "密送", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.addCcButton": "抄送", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.authenticationLabel": "身份验证", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientIdFieldLabel": "客户端 ID", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.clientSecretTextFieldLabel": "客户端密钥", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.fromTextFieldLabel": "发送者", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hasAuthSwitchLabel": "需要对此服务器进行身份验证", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.hostTextFieldLabel": "主机", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.messageTextAreaFieldLabel": "消息", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.passwordFieldLabel": "密码", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.portTextFieldLabel": "端口", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientBccTextFieldLabel": "密送", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientCopyTextFieldLabel": "抄送", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.recipientTextFieldLabel": "至", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.secureSwitchLabel": "安全", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.serviceTextFieldLabel": "服务", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.subjectTextFieldLabel": "主题", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.tenantIdFieldLabel": "租户 ID", - "xpack.triggersActionsUI.sections.builtinActionTypes.emailAction.userTextFieldLabel": "用户名", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseCancelButtonText": "取消", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseConfirmButtonText": "放弃更改", "xpack.triggersActionsUI.sections.confirmRuleClose.confirmRuleCloseMessage": "您无法恢复未保存更改。", @@ -32536,11 +32507,9 @@ "xpack.triggersActionsUI.sections.connectorAddInline.unableToLoadConnectorTitle'": "无法加载连接器", "xpack.triggersActionsUI.sections.connectorAddInline.unauthorizedToCreateForEmptyConnectors": "只有获得授权的用户才能配置连接器。请联系您的管理员。", "xpack.triggersActionsUI.sections.deprecatedTitleMessage": "(已过时)", - "xpack.triggersActionsUI.sections.editConnectorForm.cancelButtonLabel": "取消", "xpack.triggersActionsUI.sections.editConnectorForm.descriptionText": "此连接器为只读。", "xpack.triggersActionsUI.sections.editConnectorForm.flyoutPreconfiguredTitle": "编辑连接器", "xpack.triggersActionsUI.sections.editConnectorForm.preconfiguredHelpLabel": "详细了解预配置的连接器。", - "xpack.triggersActionsUI.sections.editConnectorForm.saveAndCloseButtonLabel": "保存并关闭", "xpack.triggersActionsUI.sections.editConnectorForm.saveButtonLabel": "保存", "xpack.triggersActionsUI.sections.editConnectorForm.tabText": "配置", "xpack.triggersActionsUI.sections.editConnectorForm.updateErrorNotificationText": "无法更新连接器。", @@ -32571,7 +32540,6 @@ "xpack.triggersActionsUI.sections.ruleDetails.alertsList.ruleTypeExcessDurationMessage": "持续时间超出了规则的预期运行时间。", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.activeLabel": "活动", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.allAlertsLabel": "所有告警", - "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.recentAlertHistoryTitle": "最近告警历史记录", "xpack.triggersActionsUI.sections.ruleDetails.alertsSummary.title": "告警", "xpack.triggersActionsUI.sections.ruleDetails.deleteRuleButtonLabel": "删除规则", "xpack.triggersActionsUI.sections.ruleDetails.disableRuleButtonLabel": "禁用", @@ -32712,7 +32680,6 @@ "xpack.triggersActionsUI.sections.rulesList.removeAllButton": "全部删除", "xpack.triggersActionsUI.sections.rulesList.removeCancelButton": "取消", "xpack.triggersActionsUI.sections.rulesList.removeConfirmButton": "全部删除", - "xpack.triggersActionsUI.sections.rulesList.resetDefaultIndexLabel": "重置默认索引", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDecrypting": "解密规则时发生错误。", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonDisabled": "无法执行规则,因为在规则禁用之后已运行。", "xpack.triggersActionsUI.sections.rulesList.ruleErrorReasonLicense": "无法运行规则", diff --git a/x-pack/plugins/triggers_actions_ui/.storybook/main.js b/x-pack/plugins/triggers_actions_ui/.storybook/main.js new file mode 100644 index 0000000000000..86b48c32f103e --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/.storybook/main.js @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = require('@kbn/storybook').defaultConfig; diff --git a/x-pack/plugins/triggers_actions_ui/.storybook/preview.js b/x-pack/plugins/triggers_actions_ui/.storybook/preview.js new file mode 100644 index 0000000000000..3200746243d47 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/.storybook/preview.js @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiThemeProviderDecorator } from '@kbn/kibana-react-plugin/common'; + +export const decorators = [EuiThemeProviderDecorator]; diff --git a/x-pack/plugins/triggers_actions_ui/README.md b/x-pack/plugins/triggers_actions_ui/README.md index 999b7b00a13aa..0643a7d266a88 100644 --- a/x-pack/plugins/triggers_actions_ui/README.md +++ b/x-pack/plugins/triggers_actions_ui/README.md @@ -917,13 +917,13 @@ export function getActionType(): ActionTypeModel { id: '.email', iconClass: 'email', selectMessage: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.selectMessageText', + 'xpack.stackConnectors.components.email.selectMessageText', { defaultMessage: 'Send email from your server.', } ), actionTypeTitle: i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.emailAction.actionTypeTitle', + 'xpack.stackConnectors.components.email.connectorTypeTitle', { defaultMessage: 'Send to email', } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/translations.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/translations.ts deleted file mode 100644 index 785840477af68..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/translations.ts +++ /dev/null @@ -1,510 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { i18n } from '@kbn/i18n'; - -export const CREATE_URL_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateUrlText', - { - defaultMessage: 'Create case URL is required.', - } -); -export const CREATE_INCIDENT_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateIncidentText', - { - defaultMessage: 'Create case object is required and must be valid JSON.', - } -); - -export const CREATE_METHOD_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateMethodText', - { - defaultMessage: 'Create case method is required.', - } -); - -export const CREATE_RESPONSE_KEY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateIncidentResponseKeyText', - { - defaultMessage: 'Create case response case id key is required.', - } -); - -export const UPDATE_URL_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateUrlText', - { - defaultMessage: 'Update case URL is required.', - } -); -export const UPDATE_INCIDENT_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredUpdateIncidentText', - { - defaultMessage: 'Update case object is required and must be valid JSON.', - } -); - -export const UPDATE_METHOD_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredUpdateMethodText', - { - defaultMessage: 'Update case method is required.', - } -); - -export const CREATE_COMMENT_URL_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentUrlText', - { - defaultMessage: 'Create comment URL must be URL format.', - } -); -export const CREATE_COMMENT_MESSAGE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredCreateCommentIncidentText', - { - defaultMessage: 'Create comment object must be valid JSON.', - } -); - -export const CREATE_COMMENT_METHOD_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredCreateCommentMethodText', - { - defaultMessage: 'Create comment method is required.', - } -); - -export const GET_INCIDENT_URL_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.requiredGetIncidentUrlText', - { - defaultMessage: 'Get case URL is required.', - } -); -export const GET_RESPONSE_EXTERNAL_TITLE_KEY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseExternalTitleKeyText', - { - defaultMessage: 'Get case response external case title key is re quired.', - } -); -export const GET_RESPONSE_EXTERNAL_CREATED_KEY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseCreatedKeyText', - { - defaultMessage: 'Get case response created date key is required.', - } -); -export const GET_RESPONSE_EXTERNAL_UPDATED_KEY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentResponseUpdatedKeyText', - { - defaultMessage: 'Get case response updated date key is required.', - } -); -export const GET_INCIDENT_VIEW_URL_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredGetIncidentViewUrlKeyText', - { - defaultMessage: 'View case URL is required.', - } -); - -export const MISSING_VARIABLES = (variables: string[]) => - i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.error.missingVariables', - { - defaultMessage: - 'Missing required {variableCount, plural, one {variable} other {variables}}: {variables}', - values: { variableCount: variables.length, variables: variables.join(', ') }, - } - ); - -export const USERNAME_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.sections.addAction.casesWebhookAction.error.requiredAuthUserNameText', - { - defaultMessage: 'Username is required.', - } -); - -export const SUMMARY_REQUIRED = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.error.requiredWebhookSummaryText', - { - defaultMessage: 'Title is required.', - } -); - -export const KEY_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.keyTextFieldLabel', - { - defaultMessage: 'Key', - } -); - -export const VALUE_LABEL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.valueTextFieldLabel', - { - defaultMessage: 'Value', - } -); - -export const ADD_BUTTON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addHeaderButton', - { - defaultMessage: 'Add', - } -); - -export const DELETE_BUTTON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.deleteHeaderButton', - { - defaultMessage: 'Delete', - description: 'Delete HTTP header', - } -); - -export const CREATE_INCIDENT_METHOD = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentMethodTextFieldLabel', - { - defaultMessage: 'Create Case Method', - } -); - -export const CREATE_INCIDENT_URL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentUrlTextFieldLabel', - { - defaultMessage: 'Create Case URL', - } -); - -export const CREATE_INCIDENT_JSON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonTextFieldLabel', - { - defaultMessage: 'Create Case Object', - } -); - -export const CREATE_INCIDENT_JSON_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentJsonHelpText', - { - defaultMessage: - 'JSON object to create case. Use the variable selector to add Cases data to the payload.', - } -); - -export const JSON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonFieldLabel', - { - defaultMessage: 'JSON', - } -); -export const CODE_EDITOR = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.jsonCodeEditorAriaLabel', - { - defaultMessage: 'Code editor', - } -); - -export const CREATE_INCIDENT_RESPONSE_KEY = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyTextFieldLabel', - { - defaultMessage: 'Create Case Response Case Key', - } -); - -export const CREATE_INCIDENT_RESPONSE_KEY_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createIncidentResponseKeyHelpText', - { - defaultMessage: 'JSON key in create case response that contains the external case id', - } -); - -export const ADD_CASES_VARIABLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.addVariable', - { - defaultMessage: 'Add variable', - } -); - -export const GET_INCIDENT_URL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlTextFieldLabel', - { - defaultMessage: 'Get Case URL', - } -); -export const GET_INCIDENT_URL_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentUrlHelp', - { - defaultMessage: - 'API URL to GET case details JSON from external system. Use the variable selector to add external system id to the url.', - } -); - -export const GET_INCIDENT_TITLE_KEY = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyTextFieldLabel', - { - defaultMessage: 'Get Case Response External Title Key', - } -); -export const GET_INCIDENT_TITLE_KEY_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.getIncidentResponseExternalTitleKeyHelp', - { - defaultMessage: 'JSON key in get case response that contains the external case title', - } -); - -export const EXTERNAL_INCIDENT_VIEW_URL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlTextFieldLabel', - { - defaultMessage: 'External Case View URL', - } -); -export const EXTERNAL_INCIDENT_VIEW_URL_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewIncidentUrlHelp', - { - defaultMessage: - 'URL to view case in external system. Use the variable selector to add external system id or external system title to the url.', - } -); - -export const UPDATE_INCIDENT_METHOD = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentMethodTextFieldLabel', - { - defaultMessage: 'Update Case Method', - } -); - -export const UPDATE_INCIDENT_URL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlTextFieldLabel', - { - defaultMessage: 'Update Case URL', - } -); -export const UPDATE_INCIDENT_URL_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentUrlHelp', - { - defaultMessage: 'API URL to update case.', - } -); - -export const UPDATE_INCIDENT_JSON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonTextFieldLabel', - { - defaultMessage: 'Update Case Object', - } -); -export const UPDATE_INCIDENT_JSON_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.updateIncidentJsonHelpl', - { - defaultMessage: - 'JSON object to update case. Use the variable selector to add Cases data to the payload.', - } -); - -export const CREATE_COMMENT_METHOD = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentMethodTextFieldLabel', - { - defaultMessage: 'Create Comment Method', - } -); -export const CREATE_COMMENT_URL = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlTextFieldLabel', - { - defaultMessage: 'Create Comment URL', - } -); - -export const CREATE_COMMENT_URL_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentUrlHelp', - { - defaultMessage: 'API URL to add comment to case.', - } -); - -export const CREATE_COMMENT_JSON = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonTextFieldLabel', - { - defaultMessage: 'Create Comment Object', - } -); -export const CREATE_COMMENT_JSON_HELP = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.createCommentJsonHelp', - { - defaultMessage: - 'JSON object to create a comment. Use the variable selector to add Cases data to the payload.', - } -); - -export const HAS_AUTH = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.hasAuthSwitchLabel', - { - defaultMessage: 'Require authentication for this webhook', - } -); - -export const USERNAME = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.userTextFieldLabel', - { - defaultMessage: 'Username', - } -); - -export const PASSWORD = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.passwordTextFieldLabel', - { - defaultMessage: 'Password', - } -); - -export const HEADERS_SWITCH = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.viewHeadersSwitch', - { - defaultMessage: 'Add HTTP header', - } -); - -export const HEADERS_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.httpHeadersTitle', - { - defaultMessage: 'Headers in use', - } -); - -export const AUTH_TITLE = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.authenticationLabel', - { - defaultMessage: 'Authentication', - } -); - -export const STEP_1 = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step1', - { - defaultMessage: 'Set up connector', - } -); - -export const STEP_2 = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2', - { - defaultMessage: 'Create case', - } -); - -export const STEP_2_DESCRIPTION = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step2Description', - { - defaultMessage: - 'Set fields to create the case in the external system. Check your service’s API documentation to understand what fields are required', - } -); - -export const STEP_3 = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3', - { - defaultMessage: 'Get case information', - } -); - -export const STEP_3_DESCRIPTION = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step3Description', - { - defaultMessage: - 'Set fields to add comments to the case in external system. For some systems, this may be the same method as creating updates in cases. Check your service’s API documentation to understand what fields are required.', - } -); - -export const STEP_4 = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4', - { - defaultMessage: 'Comments and updates', - } -); - -export const STEP_4A = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4a', - { - defaultMessage: 'Create update in case', - } -); - -export const STEP_4A_DESCRIPTION = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4aDescription', - { - defaultMessage: - 'Set fields to create updates to the case in external system. For some systems, this may be the same method as adding comments to cases.', - } -); - -export const STEP_4B = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4b', - { - defaultMessage: 'Add comment in case', - } -); - -export const STEP_4B_DESCRIPTION = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.step4bDescription', - { - defaultMessage: - 'Set fields to add comments to the case in external system. For some systems, this may be the same method as creating updates in cases.', - } -); - -export const NEXT = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.next', - { - defaultMessage: 'Next', - } -); - -export const PREVIOUS = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.previous', - { - defaultMessage: 'Previous', - } -); - -export const CASE_TITLE_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTitleDesc', - { - defaultMessage: 'Kibana case title', - } -); - -export const CASE_DESCRIPTION_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseDescriptionDesc', - { - defaultMessage: 'Kibana case description', - } -); - -export const CASE_TAGS_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseTagsDesc', - { - defaultMessage: 'Kibana case tags', - } -); - -export const CASE_COMMENT_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.caseCommentDesc', - { - defaultMessage: 'Kibana case comment', - } -); - -export const EXTERNAL_ID_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalIdDesc', - { - defaultMessage: 'External system id', - } -); - -export const EXTERNAL_TITLE_DESC = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.externalTitleDesc', - { - defaultMessage: 'External system title', - } -); - -export const DOC_LINK = i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.casesWebhookAction.docLink', - { - defaultMessage: 'Configuring Webhook - Case Management connector.', - } -); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.test.tsx deleted file mode 100644 index 45169e0fcb032..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/cases_webhook/webhook.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.cases-webhook'; -let actionTypeModel: ActionTypeModel; - -beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('logoWebhook'); - }); -}); - -describe('webhook action params validation', () => { - test('action params validation succeeds when action params is valid', async () => { - const actionParams = { - subActionParams: { incident: { title: 'some title {{test}}' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { 'subActionParams.incident.title': [] }, - }); - }); - - test('params validation fails when body is not valid', async () => { - const actionParams = { - subActionParams: { incident: { title: '' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - 'subActionParams.incident.title': ['Title is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/index.ts deleted file mode 100644 index e5e5da50eca0b..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/index.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ValidatedEmail, ValidateEmailAddressesOptions } from '@kbn/actions-plugin/common'; -import { getServerLogActionType } from './server_log'; -import { getSlackActionType } from './slack'; -import { getEmailActionType } from './email'; -import { getIndexActionType } from './es_index'; -import { getPagerDutyActionType } from './pagerduty'; -import { getSwimlaneActionType } from './swimlane'; -import { getCasesWebhookActionType } from './cases_webhook'; -import { getWebhookActionType } from './webhook'; -import { getXmattersActionType } from './xmatters'; -import { TypeRegistry } from '../../type_registry'; -import { ActionTypeModel } from '../../../types'; -import { - getServiceNowITSMActionType, - getServiceNowSIRActionType, - getServiceNowITOMActionType, -} from './servicenow'; -import { getJiraActionType } from './jira'; -import { getResilientActionType } from './resilient'; -import { getTeamsActionType } from './teams'; - -export interface RegistrationServices { - validateEmailAddresses: ( - addresses: string[], - options?: ValidateEmailAddressesOptions - ) => ValidatedEmail[]; -} - -export function registerBuiltInActionTypes({ - actionTypeRegistry, - services, -}: { - actionTypeRegistry: TypeRegistry; - services: RegistrationServices; -}) { - actionTypeRegistry.register(getServerLogActionType()); - actionTypeRegistry.register(getSlackActionType()); - actionTypeRegistry.register(getEmailActionType(services)); - actionTypeRegistry.register(getIndexActionType()); - actionTypeRegistry.register(getPagerDutyActionType()); - actionTypeRegistry.register(getSwimlaneActionType()); - actionTypeRegistry.register(getCasesWebhookActionType()); - actionTypeRegistry.register(getWebhookActionType()); - actionTypeRegistry.register(getXmattersActionType()); - actionTypeRegistry.register(getServiceNowITSMActionType()); - actionTypeRegistry.register(getServiceNowITOMActionType()); - actionTypeRegistry.register(getServiceNowSIRActionType()); - actionTypeRegistry.register(getJiraActionType()); - actionTypeRegistry.register(getResilientActionType()); - actionTypeRegistry.register(getTeamsActionType()); -} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/index.ts deleted file mode 100644 index 3db3aeaaaa66c..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getPagerDutyActionType } from './pagerduty'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts deleted file mode 100644 index 2794a63d4a8b0..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getResilientActionType } from './resilient'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx deleted file mode 100644 index c46bcd6a02c71..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.resilient'; -let actionTypeModel: ActionTypeModel; - -beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - }); -}); - -describe('resilient action params validation', () => { - test('action params validation succeeds when action params is valid', async () => { - const actionParams = { - subActionParams: { incident: { name: 'some title {{test}}' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { 'subActionParams.incident.name': [] }, - }); - }); - - test('params validation fails when body is not valid', async () => { - const actionParams = { - subActionParams: { incident: { name: '' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - 'subActionParams.incident.name': ['Name is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/index.ts deleted file mode 100644 index 0edbef22ee9cb..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getServerLogActionType } from './server_log'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.test.tsx deleted file mode 100644 index 098c65f294560..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log.test.tsx +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.server-log'; -let actionTypeModel: ActionTypeModel; - -beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('logsApp'); - }); -}); - -describe('action params validation', () => { - test('action params validation succeeds when action params is valid', async () => { - const actionParams = { - message: 'test message', - level: 'trace', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { message: [] }, - }); - }); - - test('params validation fails when message is not valid', async () => { - const actionParams = { - message: '', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - message: ['Message is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.test.tsx deleted file mode 100644 index 9e786a189ec42..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const SERVICENOW_ITSM_ACTION_TYPE_ID = '.servicenow'; -const SERVICENOW_SIR_ACTION_TYPE_ID = '.servicenow-sir'; -const SERVICENOW_ITOM_ACTION_TYPE_ID = '.servicenow-itom'; -let actionTypeRegistry: TypeRegistry; - -beforeAll(() => { - actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); -}); - -describe('actionTypeRegistry.get() works', () => { - [ - SERVICENOW_ITSM_ACTION_TYPE_ID, - SERVICENOW_SIR_ACTION_TYPE_ID, - SERVICENOW_ITOM_ACTION_TYPE_ID, - ].forEach((id) => { - test(`${id}: action type static data is as expected`, () => { - const actionTypeModel = actionTypeRegistry.get(id); - expect(actionTypeModel.id).toEqual(id); - }); - }); -}); - -describe('servicenow action params validation', () => { - [SERVICENOW_ITSM_ACTION_TYPE_ID, SERVICENOW_SIR_ACTION_TYPE_ID].forEach((id) => { - test(`${id}: action params validation succeeds when action params is valid`, async () => { - const actionTypeModel = actionTypeRegistry.get(id); - const actionParams = { - subActionParams: { incident: { short_description: 'some title {{test}}' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { ['subActionParams.incident.short_description']: [] }, - }); - }); - - test(`${id}: params validation fails when short_description is not valid`, async () => { - const actionTypeModel = actionTypeRegistry.get(id); - const actionParams = { - subActionParams: { incident: { short_description: '' }, comments: [] }, - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - ['subActionParams.incident.short_description']: ['Short description is required.'], - }, - }); - }); - }); - - test(`${SERVICENOW_ITOM_ACTION_TYPE_ID}: action params validation succeeds when action params is valid`, async () => { - const actionTypeModel = actionTypeRegistry.get(SERVICENOW_ITOM_ACTION_TYPE_ID); - const actionParams = { subActionParams: { severity: 'Critical' } }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { ['severity']: [] }, - }); - }); - - test(`${SERVICENOW_ITOM_ACTION_TYPE_ID}: params validation fails when severity is not valid`, async () => { - const actionTypeModel = actionTypeRegistry.get(SERVICENOW_ITOM_ACTION_TYPE_ID); - const actionParams = { subActionParams: { severity: null } }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { ['severity']: ['Severity is required.'] }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.test.tsx deleted file mode 100644 index 45689fbd50264..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.slack'; -let actionTypeModel: ActionTypeModel; - -beforeAll(async () => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('logoSlack'); - }); -}); - -describe('slack action params validation', () => { - test('if action params validation succeeds when action params is valid', async () => { - const actionParams = { - message: 'message {test}', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { message: [] }, - }); - }); - - test('params validation fails when message is not valid', async () => { - const actionParams = { - message: '', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - message: ['Message is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/index.ts deleted file mode 100644 index 39a57e1bccb61..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/swimlane/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getSwimlaneActionType } from './swimlane'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/index.ts deleted file mode 100644 index 84af06ff53bfc..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getTeamsActionType } from './teams'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.test.tsx deleted file mode 100644 index e08853abf9c12..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/teams/teams.test.tsx +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.teams'; -let actionTypeModel: ActionTypeModel; - -beforeAll(async () => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - }); -}); - -describe('teams action params validation', () => { - test('if action params validation succeeds when action params is valid', async () => { - const actionParams = { - message: 'message {test}', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { message: [] }, - }); - }); - - test('params validation fails when message is not valid', async () => { - const actionParams = { - message: '', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - message: ['Message is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.test.tsx deleted file mode 100644 index dfc3aae39586d..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.webhook'; -let actionTypeModel: ActionTypeModel; - -beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.iconClass).toEqual('logoWebhook'); - }); -}); - -describe('webhook action params validation', () => { - test('action params validation succeeds when action params is valid', async () => { - const actionParams = { - body: 'message {test}', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { body: [] }, - }); - }); - - test('params validation fails when body is not valid', async () => { - const actionParams = { - body: '', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { - body: ['Body is required.'], - }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/index.ts deleted file mode 100644 index 54bc4fd06acd4..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { getActionType as getXmattersActionType } from './xmatters'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.test.tsx deleted file mode 100644 index 980fa90caf4bb..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/xmatters/xmatters.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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { TypeRegistry } from '../../../type_registry'; -import { registerBuiltInActionTypes } from '..'; -import { ActionTypeModel } from '../../../../types'; -import { registrationServicesMock } from '../../../../mocks'; - -const ACTION_TYPE_ID = '.xmatters'; -let actionTypeModel: ActionTypeModel; - -beforeAll(() => { - const actionTypeRegistry = new TypeRegistry(); - registerBuiltInActionTypes({ actionTypeRegistry, services: registrationServicesMock }); - const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); - if (getResult !== null) { - actionTypeModel = getResult; - } -}); - -describe('actionTypeRegistry.get() works', () => { - test('action type static data is as expected', () => { - expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); - expect(actionTypeModel.actionTypeTitle).toEqual('xMatters data'); - }); -}); - -describe('xmatters action params validation', () => { - test('action params validation succeeds when action params is valid', async () => { - const actionParams = { - alertActionGroupName: 'Small t-shirt', - signalId: 'c9437cab-6a5b-45e8-bc8a-f4a8af440e97', - ruleName: 'Test xMatters', - date: '2022-01-18T19:01:08.818Z', - severity: 'high', - spaceId: 'default', - tags: 'test1, test2', - }; - - expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { alertActionGroupName: [], signalId: [] }, - }); - }); -}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/index.ts new file mode 100644 index 0000000000000..3bc994313093b --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/index.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { JsonEditorWithMessageVariables } from './json_editor_with_message_variables'; +export { HiddenField } from './hidden_field'; +export { PasswordField } from './password_field'; +export { TextFieldWithMessageVariables } from './text_field_with_message_variables'; +export { TextAreaWithMessageVariables } from './text_area_with_message_variables'; +export { SimpleConnectorForm } from './simple_connector_form'; +export type { ConfigFieldSchema, SecretsFieldSchema } from './simple_connector_form'; +export { ButtonGroupField } from './button_group_field'; +export { JsonFieldWrapper } from './json_field_wrapper'; +export { MustacheTextFieldWrapper } from './mustache_text_field_wrapper'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.test.tsx index 62745a6eb0995..36b3bf2cb153e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/simple_connector_form.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { act, render, RenderResult } from '@testing-library/react'; -import { FormTestProvider } from './builtin_action_types/test_utils'; +import { FormTestProvider } from './test_utils'; import { ConfigFieldSchema, SecretsFieldSchema, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/test_utils.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/test_utils.tsx new file mode 100644 index 0000000000000..39cff673908bd --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/test_utils.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback } from 'react'; +import { of } from 'rxjs'; +import { I18nProvider } from '@kbn/i18n-react'; +import { EuiButton } from '@elastic/eui'; +import { Form, useForm, FormData } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { render as reactRender, RenderOptions, RenderResult } from '@testing-library/react'; +import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public'; + +import { ConnectorServices } from '../../types'; +import { TriggersAndActionsUiServices } from '../..'; +import { createStartServicesMock } from '../../common/lib/kibana/kibana_react.mock'; +import { ConnectorProvider } from '../context/connector_context'; + +interface FormTestProviderProps { + children: React.ReactNode; + defaultValue?: Record; + onSubmit?: ({ data, isValid }: { data: FormData; isValid: boolean }) => Promise; + connectorServices?: ConnectorServices; +} + +const FormTestProviderComponent: React.FC = ({ + children, + defaultValue, + onSubmit, + connectorServices = { validateEmailAddresses: jest.fn() }, +}) => { + const { form } = useForm({ defaultValue }); + const { submit } = form; + + const onClick = useCallback(async () => { + const res = await submit(); + if (onSubmit) { + onSubmit(res); + } + }, [onSubmit, submit]); + + return ( + + +
    {children}
    + +
    +
    + ); +}; + +FormTestProviderComponent.displayName = 'FormTestProvider'; +export const FormTestProvider = React.memo(FormTestProviderComponent); + +type UiRender = (ui: React.ReactElement, options?: RenderOptions) => RenderResult; +export interface AppMockRenderer { + render: UiRender; + coreStart: TriggersAndActionsUiServices; +} + +export const createAppMockRenderer = (): AppMockRenderer => { + const services = createStartServicesMock(); + const theme$ = of({ darkMode: false }); + + const AppWrapper: React.FC<{ children: React.ReactElement }> = ({ children }) => ( + + + {children} + + + ); + AppWrapper.displayName = 'AppWrapper'; + const render: UiRender = (ui, options) => { + return reactRender(ui, { + wrapper: AppWrapper, + ...options, + }); + }; + return { + coreStart: services, + render, + }; +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/update_api_key_modal_confirmation.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/update_api_key_modal_confirmation.tsx index 0c6f3edaf3b89..c3072c123ff82 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/update_api_key_modal_confirmation.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/update_api_key_modal_confirmation.tsx @@ -6,6 +6,7 @@ */ import { EuiConfirmModal } from '@elastic/eui'; +import { KueryNode } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import React, { useEffect, useState, useMemo } from 'react'; import { HttpSetup } from '@kbn/core/public'; @@ -25,7 +26,7 @@ export const UpdateApiKeyModalConfirmation = ({ }: { onCancel: () => void; idsToUpdate: string[]; - idsToUpdateFilter?: string; + idsToUpdateFilter?: KueryNode | null | undefined; numberOfSelectedRules?: number; apiUpdateApiKeyCall: ({ ids, @@ -33,7 +34,7 @@ export const UpdateApiKeyModalConfirmation = ({ filter, }: { ids?: string[]; - filter?: string; + filter?: KueryNode | null | undefined; http: HttpSetup; }) => Promise; setIsLoadingState: (isLoading: boolean) => void; @@ -50,7 +51,7 @@ export const UpdateApiKeyModalConfirmation = ({ const { showToast } = useBulkEditResponse({ onSearchPopulate }); useEffect(() => { - if (idsToUpdateFilter) { + if (typeof idsToUpdateFilter !== 'undefined') { setUpdateModalVisibility(true); } else { setUpdateModalVisibility(idsToUpdate.length > 0); @@ -58,7 +59,7 @@ export const UpdateApiKeyModalConfirmation = ({ }, [idsToUpdate, idsToUpdateFilter]); const numberOfIdsToUpdate = useMemo(() => { - if (idsToUpdateFilter) { + if (typeof idsToUpdateFilter !== 'undefined') { return numberOfSelectedRules; } return idsToUpdate.length; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/constants/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/constants/index.ts index 113d274c7aeb9..19d3b038c6350 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/constants/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/constants/index.ts @@ -12,7 +12,6 @@ export { INTERNAL_BASE_ALERTING_API_PATH, } from '@kbn/alerting-plugin/common'; export { BASE_ACTION_API_PATH, INTERNAL_BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common'; -export { INTERNAL_BASE_STACK_CONNECTORS_API_PATH } from '@kbn/stack-connectors-plugin/common'; export type Section = 'connectors' | 'rules' | 'alerts' | 'logs'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.test.tsx new file mode 100644 index 0000000000000..07bf3516fbdef --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.test.tsx @@ -0,0 +1,147 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook, act } from '@testing-library/react-hooks'; +import { useBulkEditSelect } from './use_bulk_edit_select'; +import { RuleTableItem } from '../../types'; + +const items = [ + { + id: '1', + isEditable: true, + }, + { + id: '2', + isEditable: true, + }, + { + id: '3', + isEditable: true, + }, + { + id: '4', + isEditable: true, + }, +] as RuleTableItem[]; + +describe('useBulkEditSelectTest', () => { + it('getFilter should return null when nothing is selected', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + }) + ); + + expect(result.current.getFilter()).toEqual(null); + }); + + it('getFilter should return rule list filter when nothing is selected', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + tagsFilter: ['test: 123'], + searchText: 'rules*', + }) + ); + + expect(result.current.getFilter()?.arguments.length).toEqual(2); + }); + + it('getFilter should return rule list filter when something is selected', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + tagsFilter: ['test: 123'], + searchText: 'rules*', + }) + ); + + act(() => { + result.current.onSelectRow(items[0]); + }); + + expect(result.current.getFilter()?.arguments.length).toEqual(2); + expect([...result.current.selectedIds]).toEqual([items[0].id]); + }); + + it('getFilter should return null when selecting all', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + }) + ); + + act(() => { + result.current.onSelectAll(); + }); + + expect(result.current.getFilter()).toEqual(null); + }); + + it('getFilter should return rule list filter when selecting all with excluded ids', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + }) + ); + + act(() => { + result.current.onSelectAll(); + result.current.onSelectRow(items[0]); + }); + + expect(result.current.getFilter()?.arguments.length).toEqual(1); + }); + + it('getFilter should return rule list filter when selecting all', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + tagsFilter: ['test: 123'], + searchText: 'rules*', + }) + ); + + act(() => { + result.current.onSelectAll(); + }); + + expect(result.current.getFilter()?.arguments.length).toEqual(2); + }); + + it('getFilter should return rule list filter and exclude ids when selecting all with excluded ids', async () => { + const { result } = renderHook(() => + useBulkEditSelect({ + items, + totalItemCount: 4, + tagsFilter: ['test: 123'], + searchText: 'rules*', + }) + ); + + act(() => { + result.current.onSelectAll(); + result.current.onSelectRow(items[0]); + }); + + expect(result.current.getFilter()?.arguments.length).toEqual(2); + expect(result.current.getFilter()?.arguments[1].arguments[0].arguments).toEqual([ + expect.objectContaining({ + value: 'alert.id', + }), + expect.objectContaining({ + value: 'alert:1', + }), + ]); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.tsx b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.tsx index 20950d35b0264..31c248ae1254e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_bulk_edit_select.tsx @@ -5,7 +5,9 @@ * 2.0. */ import { useReducer, useMemo, useCallback } from 'react'; -import { RuleTableItem } from '../../types'; +import { fromKueryExpression, nodeBuilder } from '@kbn/es-query'; +import { mapFiltersToKueryNode } from '../lib/rule_api/map_filters_to_kuery_node'; +import { RuleTableItem, RuleStatus } from '../../types'; interface BulkEditSelectionState { selectedIds: Set; @@ -71,9 +73,26 @@ const reducer = (state: BulkEditSelectionState, action: Action) => { interface UseBulkEditSelectProps { totalItemCount: number; items: RuleTableItem[]; + typesFilter?: string[]; + actionTypesFilter?: string[]; + tagsFilter?: string[]; + ruleExecutionStatusesFilter?: string[]; + ruleStatusesFilter?: RuleStatus[]; + searchText?: string; } -export function useBulkEditSelect({ totalItemCount = 0, items = [] }: UseBulkEditSelectProps) { +export function useBulkEditSelect(props: UseBulkEditSelectProps) { + const { + totalItemCount = 0, + items = [], + typesFilter, + actionTypesFilter, + tagsFilter, + ruleExecutionStatusesFilter, + ruleStatusesFilter, + searchText, + } = props; + const [state, dispatch] = useReducer(reducer, initialState); const itemIds = useMemo(() => { @@ -161,18 +180,54 @@ export function useBulkEditSelect({ totalItemCount = 0, items = [] }: UseBulkEdi dispatch({ type: ActionTypes.CLEAR_SELECTION }); }, []); + const getFilterKueryNode = useCallback( + (idsToExclude?: string[]) => { + const ruleFilterKueryNode = mapFiltersToKueryNode({ + typesFilter, + actionTypesFilter, + tagsFilter, + ruleExecutionStatusesFilter, + ruleStatusesFilter, + searchText, + }); + + if (idsToExclude && idsToExclude.length) { + const excludeFilter = fromKueryExpression( + `NOT (${idsToExclude.map((id) => `alert.id: "alert:${id}"`).join(' or ')})` + ); + if (ruleFilterKueryNode) { + return nodeBuilder.and([ruleFilterKueryNode, excludeFilter]); + } + return excludeFilter; + } + + return ruleFilterKueryNode; + }, + [ + typesFilter, + actionTypesFilter, + tagsFilter, + ruleExecutionStatusesFilter, + ruleStatusesFilter, + searchText, + ] + ); + const getFilter = useCallback(() => { const { selectedIds, isAllSelected } = state; const idsArray = [...selectedIds]; if (isAllSelected) { + // Select all but nothing is selected to exclude if (idsArray.length === 0) { - return 'alert.id: *'; + return getFilterKueryNode(); } - return `NOT (${idsArray.map((id) => `alert.id: "alert:${id}"`).join(' or ')})`; + // Select all, exclude certain alerts + return getFilterKueryNode(idsArray); } - return ''; - }, [state]); + + return getFilterKueryNode(); + }, [state, getFilterKueryNode]); return useMemo(() => { return { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.test.ts index 293c1e992ac18..03be9f6b9bd5a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.test.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.test.ts @@ -8,7 +8,7 @@ import { ALERTS_FEATURE_ID } from '@kbn/alerting-plugin/common'; import { renderHook } from '@testing-library/react-hooks'; import { useKibana } from '../../common/lib/kibana'; -import { mockAggsResponse, mockChartData } from '../mock/rule_details/alert_summary'; +import { mockAggsResponse } from '../mock/rule_details/alert_summary'; import { useLoadRuleAlertsAggs } from './use_load_rule_alerts_aggregations'; jest.mock('../../common/lib/kibana'); @@ -21,7 +21,7 @@ describe('useLoadRuleAlertsAggs', () => { useKibanaMock().services.http.get = jest.fn().mockResolvedValue({ index_name: ['mock_index'] }); }); - it('should return the expected chart data from the Elasticsearch Aggs. query', async () => { + it('should return the expected data from the Elasticsearch Aggs. query', async () => { const { result, waitForNextUpdate } = renderHook(() => useLoadRuleAlertsAggs({ features: ALERTS_FEATURE_ID, @@ -31,18 +31,15 @@ describe('useLoadRuleAlertsAggs', () => { expect(result.current).toEqual({ isLoadingRuleAlertsAggs: true, ruleAlertsAggs: { active: 0, recovered: 0 }, - alertsChartData: [], }); await waitForNextUpdate(); - const { ruleAlertsAggs, errorRuleAlertsAggs, alertsChartData } = result.current; + const { ruleAlertsAggs, errorRuleAlertsAggs } = result.current; expect(ruleAlertsAggs).toEqual({ active: 1, recovered: 7, }); - expect(alertsChartData).toEqual(mockChartData()); expect(errorRuleAlertsAggs).toBeFalsy(); - expect(alertsChartData.length).toEqual(33); }); it('should have the correct query body sent to Elasticsearch', async () => { @@ -55,7 +52,7 @@ describe('useLoadRuleAlertsAggs', () => { ); await waitForNextUpdate(); - const body = `{"index":"mock_index","size":0,"query":{"bool":{"must":[{"term":{"kibana.alert.rule.uuid":"${ruleId}"}},{"range":{"@timestamp":{"gte":"now-30d","lt":"now"}}},{"bool":{"should":[{"term":{"kibana.alert.status":"active"}},{"term":{"kibana.alert.status":"recovered"}}]}}]}},"aggs":{"total":{"filters":{"filters":{"totalActiveAlerts":{"term":{"kibana.alert.status":"active"}},"totalRecoveredAlerts":{"term":{"kibana.alert.status":"recovered"}}}}},"statusPerDay":{"date_histogram":{"field":"@timestamp","fixed_interval":"1d","extended_bounds":{"min":"now-30d","max":"now"}},"aggs":{"alertStatus":{"terms":{"field":"kibana.alert.status"}}}}}}`; + const body = `{"index":"mock_index","size":0,"query":{"bool":{"must":[{"term":{"kibana.alert.rule.uuid":"${ruleId}"}},{"range":{"@timestamp":{"gte":"now-30d","lt":"now"}}},{"bool":{"should":[{"term":{"kibana.alert.status":"active"}},{"term":{"kibana.alert.status":"recovered"}}]}}]}},"aggs":{"total":{"filters":{"filters":{"totalActiveAlerts":{"term":{"kibana.alert.status":"active"}},"totalRecoveredAlerts":{"term":{"kibana.alert.status":"recovered"}}}}}}}`; expect(useKibanaMock().services.http.post).toHaveBeenCalledWith( '/internal/rac/alerts/find', diff --git a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.ts b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.ts index c938b0b2cc13f..3df1722abc006 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/hooks/use_load_rule_alerts_aggregations.ts @@ -10,7 +10,6 @@ import { AsApiContract } from '@kbn/actions-plugin/common'; import { HttpSetup } from '@kbn/core/public'; import { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common/constants'; import { useKibana } from '../../common/lib/kibana'; -import { AlertChartData } from '../sections/rule_details/components/alert_summary'; interface UseLoadRuleAlertsAggs { features: string; @@ -29,7 +28,6 @@ interface LoadRuleAlertsAggs { recovered: number; }; errorRuleAlertsAggs?: string; - alertsChartData: AlertChartData[]; } interface IndexName { index: string; @@ -40,7 +38,6 @@ export function useLoadRuleAlertsAggs({ features, ruleId }: UseLoadRuleAlertsAgg const [ruleAlertsAggs, setRuleAlertsAggs] = useState({ isLoadingRuleAlertsAggs: true, ruleAlertsAggs: { active: 0, recovered: 0 }, - alertsChartData: [], }); const isCancelledRef = useRef(false); const abortCtrlRef = useRef(new AbortController()); @@ -54,7 +51,7 @@ export function useLoadRuleAlertsAggs({ features, ruleId }: UseLoadRuleAlertsAgg http, features, }); - const { active, recovered, error, alertsChartData } = await fetchRuleAlertsAggByTimeRange({ + const { active, recovered, error } = await fetchRuleAlertsAggByTimeRange({ http, index, ruleId, @@ -68,7 +65,6 @@ export function useLoadRuleAlertsAggs({ features, ruleId }: UseLoadRuleAlertsAgg active, recovered, }, - alertsChartData, isLoadingRuleAlertsAggs: false, })); } @@ -79,7 +75,6 @@ export function useLoadRuleAlertsAggs({ features, ruleId }: UseLoadRuleAlertsAgg ...oldState, isLoadingRuleAlertsAggs: false, errorRuleAlertsAggs: error, - alertsChartData: [], })); } } @@ -92,7 +87,7 @@ export function useLoadRuleAlertsAggs({ features, ruleId }: UseLoadRuleAlertsAgg return ruleAlertsAggs; } -export async function fetchIndexNameAPI({ +async function fetchIndexNameAPI({ http, features, }: { @@ -107,14 +102,7 @@ export async function fetchIndexNameAPI({ }; } -interface RuleAlertsAggs { - active: number; - recovered: number; - error?: string; - alertsChartData: AlertChartData[]; -} - -export async function fetchRuleAlertsAggByTimeRange({ +async function fetchRuleAlertsAggByTimeRange({ http, index, ruleId, @@ -183,109 +171,22 @@ export async function fetchRuleAlertsAggByTimeRange({ }, }, }, - statusPerDay: { - date_histogram: { - field: '@timestamp', - fixed_interval: '1d', - extended_bounds: { - min: 'now-30d', - max: 'now', - }, - }, - aggs: { - alertStatus: { - terms: { - field: 'kibana.alert.status', - }, - }, - }, - }, }, }), }); const active = res?.aggregations?.total.buckets.totalActiveAlerts?.doc_count ?? 0; const recovered = res?.aggregations?.total.buckets.totalRecoveredAlerts?.doc_count ?? 0; - let maxTotalAlertPerDay = 0; - res?.aggregations?.statusPerDay.buckets.forEach( - (dayAlerts: { - key: number; - doc_count: number; - alertStatus: { - buckets: Array<{ - key: 'active' | 'recovered'; - doc_count: number; - }>; - }; - }) => { - if (dayAlerts.doc_count > maxTotalAlertPerDay) { - maxTotalAlertPerDay = dayAlerts.doc_count; - } - } - ); - const alertsChartData = [ - ...res?.aggregations?.statusPerDay.buckets.reduce( - ( - acc: AlertChartData[], - dayAlerts: { - key: number; - doc_count: number; - alertStatus: { - buckets: Array<{ - key: 'active' | 'recovered'; - doc_count: number; - }>; - }; - } - ) => { - // We are adding this to each day to construct the 30 days bars (background bar) when there is no data for a given day or to show the delta today alerts/total alerts. - const totalDayAlerts = { - date: dayAlerts.key, - count: maxTotalAlertPerDay === 0 ? 1 : maxTotalAlertPerDay, - status: 'total', - }; - - if (dayAlerts.doc_count > 0) { - const localAlertChartData = acc; - // If there are alerts in this day, we construct the chart data - dayAlerts.alertStatus.buckets.forEach((alert) => { - localAlertChartData.push({ - date: dayAlerts.key, - count: alert.doc_count, - status: alert.key, - }); - }); - const deltaAlertsCount = maxTotalAlertPerDay - dayAlerts.doc_count; - if (deltaAlertsCount > 0) { - localAlertChartData.push({ - date: dayAlerts.key, - count: deltaAlertsCount, - status: 'total', - }); - } - return localAlertChartData; - } - return [...acc, totalDayAlerts]; - }, - [] - ), - ]; return { active, recovered, - alertsChartData: [ - ...alertsChartData.filter((acd) => acd.status === 'recovered'), - ...alertsChartData.filter((acd) => acd.status === 'active'), - ...alertsChartData.filter((acd) => acd.status === 'total'), - ], }; } catch (error) { return { error, active: 0, recovered: 0, - alertsChartData: [], } as RuleAlertsAggs; } } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/index.ts index 0e1a20c666ef6..8bb75e3cc4dbc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/index.ts @@ -6,4 +6,7 @@ */ export { templateActionVariable } from './template_action_variable'; +export { hasMustacheTokens } from './has_mustache_tokens'; +export { AlertProvidedActionVariables } from './action_variables'; +export { updateActionConnector } from './action_connector_api'; export { isRuleSnoozed } from './is_rule_snoozed'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/get_filter.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/get_filter.ts new file mode 100644 index 0000000000000..65ace4fa72c7b --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/get_filter.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +// TODO (Jiawei): Use node builder instead of strings +export const getFilter = ({ + message, + outcomeFilter, + runId, +}: { + message?: string; + outcomeFilter?: string[]; + runId?: string; +}) => { + const filter: string[] = []; + + if (message) { + const escapedMessage = message.replace(/([\)\(\<\>\}\{\"\:\\])/gm, '\\$&'); + filter.push(`message: "${escapedMessage}" OR error.message: "${escapedMessage}"`); + } + + if (outcomeFilter && outcomeFilter.length) { + filter.push(`event.outcome: ${outcomeFilter.join(' or ')}`); + } + + if (runId) { + filter.push(`kibana.alert.rule.execution.uuid: ${runId}`); + } + + return filter; +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/index.ts index e841506595c04..e23fe787e87c2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/index.ts @@ -28,6 +28,10 @@ export { loadExecutionLogAggregations, loadGlobalExecutionLogAggregations, } from './load_execution_log_aggregations'; +export type { LoadExecutionKPIAggregationsProps } from './load_execution_kpi_aggregations'; +export { loadExecutionKPIAggregations } from './load_execution_kpi_aggregations'; +export type { LoadGlobalExecutionKPIAggregationsProps } from './load_global_execution_kpi_aggregations'; +export { loadGlobalExecutionKPIAggregations } from './load_global_execution_kpi_aggregations'; export type { LoadActionErrorLogProps } from './load_action_error_log'; export { loadActionErrorLog } from './load_action_error_log'; export { unmuteAlertInstance } from './unmute_alert'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.test.ts index b4384713336f7..d06447be31fbc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.test.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.test.ts @@ -117,7 +117,7 @@ describe('loadActionErrorLog', () => { "query": Object { "date_end": "2022-03-23T16:17:53.482Z", "date_start": "2022-03-23T16:17:53.482Z", - "filter": "kibana.alert.rule.execution.uuid: 123 and message: \\"test\\" OR error.message: \\"test\\"", + "filter": "message: \\"test\\" OR error.message: \\"test\\" and kibana.alert.rule.execution.uuid: 123", "page": 1, "per_page": 10, "sort": "[{\\"@timestamp\\":{\\"order\\":\\"asc\\"}}]", diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts index 4ec1a6949bfe5..10f2879085cd0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts @@ -9,6 +9,7 @@ import { HttpSetup } from '@kbn/core/public'; import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { IExecutionErrorsResult, ActionErrorLogSortFields } from '@kbn/alerting-plugin/common'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; +import { getFilter } from './get_filter'; export type SortField = Record< ActionErrorLogSortFields, @@ -49,22 +50,6 @@ const getRenamedSort = (sort?: SortField[]) => { }); }; -// TODO (Jiawei): Use node builder instead of strings -const getFilter = ({ runId, message }: { runId?: string; message?: string }) => { - const filter: string[] = []; - - if (runId) { - filter.push(`kibana.alert.rule.execution.uuid: ${runId}`); - } - - if (message) { - const escapedMessage = message.replace(/([\)\(\<\>\}\{\"\:\\])/gm, '\\$&'); - filter.push(`message: "${escapedMessage}" OR error.message: "${escapedMessage}"`); - } - - return filter; -}; - export const loadActionErrorLog = ({ id, http, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_kpi_aggregations.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_kpi_aggregations.ts new file mode 100644 index 0000000000000..076e1167f444a --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_kpi_aggregations.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { HttpSetup } from '@kbn/core/public'; +import { IExecutionKPIResult } from '@kbn/alerting-plugin/common'; +import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; +import { getFilter } from './get_filter'; + +export interface LoadExecutionKPIAggregationsProps { + id: string; + outcomeFilter?: string[]; + message?: string; + dateStart: string; + dateEnd?: string; +} + +export const loadExecutionKPIAggregations = ({ + id, + http, + outcomeFilter, + message, + dateStart, + dateEnd, +}: LoadExecutionKPIAggregationsProps & { http: HttpSetup }) => { + const filter = getFilter({ outcomeFilter, message }); + + return http.get( + `${INTERNAL_BASE_ALERTING_API_PATH}/rule/${id}/_execution_kpi`, + { + query: { + filter: filter.length ? filter.join(' and ') : undefined, + date_start: dateStart, + date_end: dateEnd, + }, + } + ); +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts index c1f8487d842c5..bf5e529499b42 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts @@ -16,6 +16,7 @@ import { } from '@kbn/alerting-plugin/common'; import { AsApiContract, RewriteRequestCase } from '@kbn/actions-plugin/common'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; +import { getFilter } from './get_filter'; const getRenamedLog = (data: IExecutionLog) => { const { @@ -40,22 +41,6 @@ const rewriteBodyRes: RewriteRequestCase = ({ data, ...rest ...rest, }); -// TODO (Jiawei): Use node builder instead of strings -const getFilter = ({ outcomeFilter, message }: { outcomeFilter?: string[]; message?: string }) => { - const filter: string[] = []; - - if (outcomeFilter && outcomeFilter.length) { - filter.push(`event.outcome: ${outcomeFilter.join(' or ')}`); - } - - if (message) { - const escapedMessage = message.replace(/([\)\(\<\>\}\{\"\:\\])/gm, '\\$&'); - filter.push(`message: "${escapedMessage}" OR error.message: "${escapedMessage}"`); - } - - return filter; -}; - export type SortField = Record< ExecutionLogSortFields, { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_global_execution_kpi_aggregations.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_global_execution_kpi_aggregations.ts new file mode 100644 index 0000000000000..332e14ad4383f --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/load_global_execution_kpi_aggregations.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { HttpSetup } from '@kbn/core/public'; +import { IExecutionKPIResult } from '@kbn/alerting-plugin/common'; +import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; +import { getFilter } from './get_filter'; + +export interface LoadGlobalExecutionKPIAggregationsProps { + id: string; + outcomeFilter?: string[]; + message?: string; + dateStart: string; + dateEnd?: string; +} + +export const loadGlobalExecutionKPIAggregations = ({ + id, + http, + outcomeFilter, + message, + dateStart, + dateEnd, +}: LoadGlobalExecutionKPIAggregationsProps & { http: HttpSetup }) => { + const filter = getFilter({ outcomeFilter, message }); + + return http.get(`${INTERNAL_BASE_ALERTING_API_PATH}/_global_execution_kpi`, { + query: { + filter: filter.length ? filter.join(' and ') : undefined, + date_start: dateStart, + date_end: dateEnd, + }, + }); +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/snooze.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/snooze.ts index 1f020aff106f5..b82efdb5e09cf 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/snooze.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/snooze.ts @@ -5,6 +5,7 @@ * 2.0. */ import { HttpSetup } from '@kbn/core/public'; +import { KueryNode } from '@kbn/es-query'; import { SnoozeSchedule, BulkEditResponse } from '../../../types'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; @@ -37,7 +38,7 @@ export async function snoozeRule({ export interface BulkSnoozeRulesProps { ids?: string[]; - filter?: string; + filter?: KueryNode | null | undefined; snoozeSchedule: SnoozeSchedule; } @@ -51,7 +52,7 @@ export function bulkSnoozeRules({ try { body = JSON.stringify({ ids: ids?.length ? ids : undefined, - filter, + ...(filter ? { filter: JSON.stringify(filter) } : {}), operations: [ { operation: 'set', diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unsnooze.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unsnooze.ts index 7bfadf1e1b824..d055149fdfbd8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unsnooze.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/unsnooze.ts @@ -5,6 +5,7 @@ * 2.0. */ import { HttpSetup } from '@kbn/core/public'; +import { KueryNode } from '@kbn/es-query'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; import { BulkEditResponse } from '../../../types'; @@ -26,7 +27,7 @@ export async function unsnoozeRule({ export interface BulkUnsnoozeRulesProps { ids?: string[]; - filter?: string; + filter?: KueryNode | null | undefined; scheduleIds?: string[]; } @@ -40,7 +41,7 @@ export function bulkUnsnoozeRules({ try { body = JSON.stringify({ ids: ids?.length ? ids : undefined, - filter, + ...(filter ? { filter: JSON.stringify(filter) } : {}), operations: [ { operation: 'delete', diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/update_api_key.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/update_api_key.ts index 53327bbdb1e1e..f9a6912c1d43f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/update_api_key.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/rule_api/update_api_key.ts @@ -5,6 +5,7 @@ * 2.0. */ import { HttpSetup } from '@kbn/core/public'; +import { KueryNode } from '@kbn/es-query'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; import { BulkEditResponse } from '../../../types'; @@ -16,7 +17,7 @@ export async function updateAPIKey({ id, http }: { id: string; http: HttpSetup } export interface BulkUpdateAPIKeyProps { ids?: string[]; - filter?: string; + filter?: KueryNode | null | undefined; } export function bulkUpdateAPIKey({ @@ -28,7 +29,7 @@ export function bulkUpdateAPIKey({ try { body = JSON.stringify({ ids: ids?.length ? ids : undefined, - filter, + ...(filter ? { filter: JSON.stringify(filter) } : {}), operations: [ { operation: 'set', diff --git a/x-pack/plugins/triggers_actions_ui/public/application/mock/rule_details/alert_summary/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/mock/rule_details/alert_summary/index.ts index b0e5416bbf63d..2d5af068ae55d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/mock/rule_details/alert_summary/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/mock/rule_details/alert_summary/index.ts @@ -6,7 +6,6 @@ */ import { Rule } from '../../../../types'; -import { AlertChartData } from '../../../sections/rule_details/components/alert_summary'; export const mockRule = (): Rule => { return { @@ -63,383 +62,12 @@ export const mockRule = (): Rule => { }; }; -export function mockChartData(): AlertChartData[] { - return [ - { - date: 1660608000000, - count: 6, - status: 'recovered', - }, - { - date: 1660694400000, - count: 1, - status: 'recovered', - }, - { - date: 1660694400000, - count: 1, - status: 'active', - }, - { - date: 1658102400000, - count: 6, - status: 'total', - }, - { - date: 1658188800000, - count: 6, - status: 'total', - }, - { - date: 1658275200000, - count: 6, - status: 'total', - }, - { - date: 1658361600000, - count: 6, - status: 'total', - }, - { - date: 1658448000000, - count: 6, - status: 'total', - }, - { - date: 1658534400000, - count: 6, - status: 'total', - }, - { - date: 1658620800000, - count: 6, - status: 'total', - }, - { - date: 1658707200000, - count: 6, - status: 'total', - }, - { - date: 1658793600000, - count: 6, - status: 'total', - }, - { - date: 1658880000000, - count: 6, - status: 'total', - }, - { - date: 1658966400000, - count: 6, - status: 'total', - }, - { - date: 1659052800000, - count: 6, - status: 'total', - }, - { - date: 1659139200000, - count: 6, - status: 'total', - }, - { - date: 1659225600000, - count: 6, - status: 'total', - }, - { - date: 1659312000000, - count: 6, - status: 'total', - }, - { - date: 1659398400000, - count: 6, - status: 'total', - }, - { - date: 1659484800000, - count: 6, - status: 'total', - }, - { - date: 1659571200000, - count: 6, - status: 'total', - }, - { - date: 1659657600000, - count: 6, - status: 'total', - }, - { - date: 1659744000000, - count: 6, - status: 'total', - }, - { - date: 1659830400000, - count: 6, - status: 'total', - }, - { - date: 1659916800000, - count: 6, - status: 'total', - }, - { - date: 1660003200000, - count: 6, - status: 'total', - }, - { - date: 1660089600000, - count: 6, - status: 'total', - }, - { - date: 1660176000000, - count: 6, - status: 'total', - }, - { - date: 1660262400000, - count: 6, - status: 'total', - }, - { - date: 1660348800000, - count: 6, - status: 'total', - }, - { - date: 1660435200000, - count: 6, - status: 'total', - }, - { - date: 1660521600000, - count: 6, - status: 'total', - }, - { - date: 1660694400000, - count: 4, - status: 'total', - }, - ]; -} - export const mockAggsResponse = () => { return { aggregations: { total: { buckets: { totalActiveAlerts: { doc_count: 1 }, totalRecoveredAlerts: { doc_count: 7 } }, }, - statusPerDay: { - buckets: [ - { - key_as_string: '2022-07-18T00:00:00.000Z', - key: 1658102400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-19T00:00:00.000Z', - key: 1658188800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-20T00:00:00.000Z', - key: 1658275200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-21T00:00:00.000Z', - key: 1658361600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-22T00:00:00.000Z', - key: 1658448000000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-23T00:00:00.000Z', - key: 1658534400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-24T00:00:00.000Z', - key: 1658620800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-25T00:00:00.000Z', - key: 1658707200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-26T00:00:00.000Z', - key: 1658793600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-27T00:00:00.000Z', - key: 1658880000000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-28T00:00:00.000Z', - key: 1658966400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-29T00:00:00.000Z', - key: 1659052800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-30T00:00:00.000Z', - key: 1659139200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-07-31T00:00:00.000Z', - key: 1659225600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-01T00:00:00.000Z', - key: 1659312000000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-02T00:00:00.000Z', - key: 1659398400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-03T00:00:00.000Z', - key: 1659484800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-04T00:00:00.000Z', - key: 1659571200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-05T00:00:00.000Z', - key: 1659657600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-06T00:00:00.000Z', - key: 1659744000000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-07T00:00:00.000Z', - key: 1659830400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-08T00:00:00.000Z', - key: 1659916800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-09T00:00:00.000Z', - key: 1660003200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-10T00:00:00.000Z', - key: 1660089600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-11T00:00:00.000Z', - key: 1660176000000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-12T00:00:00.000Z', - key: 1660262400000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-13T00:00:00.000Z', - key: 1660348800000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-14T00:00:00.000Z', - key: 1660435200000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-15T00:00:00.000Z', - key: 1660521600000, - doc_count: 0, - alertStatus: { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: [] }, - }, - { - key_as_string: '2022-08-16T00:00:00.000Z', - key: 1660608000000, - doc_count: 6, - alertStatus: { - doc_count_error_upper_bound: 0, - sum_other_doc_count: 0, - buckets: [{ key: 'recovered', doc_count: 6 }], - }, - }, - { - key_as_string: '2022-08-17T00:00:00.000Z', - key: 1660694400000, - doc_count: 2, - alertStatus: { - doc_count_error_upper_bound: 0, - sum_other_doc_count: 0, - buckets: [ - { key: 'active', doc_count: 1 }, - { key: 'recovered', doc_count: 1 }, - ], - }, - }, - ], - }, }, }; }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form.test.tsx index b4cd8d1b979ac..5c2f9db816893 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form.test.tsx @@ -6,10 +6,7 @@ */ import React, { lazy } from 'react'; -import { - AppMockRenderer, - createAppMockRenderer, -} from '../../components/builtin_action_types/test_utils'; +import { AppMockRenderer, createAppMockRenderer } from '../../components/test_utils'; import { ConnectorForm } from './connector_form'; import { actionTypeRegistryMock } from '../../action_type_registry.mock'; import userEvent from '@testing-library/user-event'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields.test.tsx index 747a4925d35f8..dd99bbdbabed5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields.test.tsx @@ -11,7 +11,7 @@ import { AppMockRenderer, createAppMockRenderer, FormTestProvider, -} from '../../components/builtin_action_types/test_utils'; +} from '../../components/test_utils'; import { ConnectorFormFields } from './connector_form_fields'; import { actionTypeRegistryMock } from '../../action_type_registry.mock'; import { waitFor } from '@testing-library/dom'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields_global.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields_global.test.tsx index 9df345c45f1e1..04cbad726ead7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields_global.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_form_fields_global.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import userEvent from '@testing-library/user-event'; import { render, act } from '@testing-library/react'; -import { FormTestProvider } from '../../components/builtin_action_types/test_utils'; +import { FormTestProvider } from '../../components/test_utils'; import { ConnectorFormFieldsGlobal } from './connector_form_fields_global'; describe('ConnectorFormFieldsGlobal', () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/footer.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/footer.tsx index 4c4ccfe965716..c73c6ed042810 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/footer.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/footer.tsx @@ -6,35 +6,16 @@ */ import React, { memo } from 'react'; -import { - EuiFlexGroup, - EuiFlexItem, - EuiFlyoutFooter, - EuiButton, - EuiButtonEmpty, -} from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n-react'; +import { EuiFlexGroup, EuiFlexItem, EuiFlyoutFooter, EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; interface Props { - isSaving: boolean; - disabled: boolean; hasConnectorTypeSelected: boolean; - onSubmit: () => Promise; - onTestConnector?: () => void; onBack: () => void; onCancel: () => void; } -const FlyoutFooterComponent: React.FC = ({ - isSaving, - disabled, - hasConnectorTypeSelected, - onCancel, - onBack, - onTestConnector, - onSubmit, -}) => { +const FlyoutFooterComponent: React.FC = ({ hasConnectorTypeSelected, onCancel, onBack }) => { return ( @@ -49,57 +30,16 @@ const FlyoutFooterComponent: React.FC = ({ )} ) : ( - + {i18n.translate( - 'xpack.triggersActionsUI.sections.actionConnectorAdd.cancelButtonLabel', + 'xpack.triggersActionsUI.sections.actionConnectorAdd.closeButtonLabel', { - defaultMessage: 'Cancel', + defaultMessage: 'Close', } )} )}
    - {hasConnectorTypeSelected ? ( - - - <> - {onTestConnector && ( - - - - - - )} - - - - - - - - - ) : null}
    ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.test.tsx index f432f8fd6634c..6256ee29aee40 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.test.tsx @@ -11,10 +11,7 @@ import { actionTypeRegistryMock } from '../../../action_type_registry.mock'; import userEvent from '@testing-library/user-event'; import { waitFor } from '@testing-library/dom'; import { act } from '@testing-library/react'; -import { - AppMockRenderer, - createAppMockRenderer, -} from '../../../components/builtin_action_types/test_utils'; +import { AppMockRenderer, createAppMockRenderer } from '../../../components/test_utils'; import CreateConnectorFlyout from '.'; import { betaBadgeProps } from '../beta_badge_props'; @@ -102,6 +99,106 @@ describe('CreateConnectorFlyout', () => { expect(await getByTestId(`${actionTypeModel.id}-card`)).toBeInTheDocument(); }); + it('shows the correct buttons without an action type selected', async () => { + const { getByTestId, queryByTestId } = appMockRenderer.render( + + ); + await act(() => Promise.resolve()); + + expect(getByTestId('create-connector-flyout-close-btn')).toBeInTheDocument(); + expect(queryByTestId('create-connector-flyout-save-test-btn')).toBe(null); + expect(queryByTestId('create-connector-flyout-save-btn')).toBe(null); + }); + + it('shows the correct buttons when selecting an action type', async () => { + const { getByTestId } = appMockRenderer.render( + + ); + await act(() => Promise.resolve()); + + act(() => { + userEvent.click(getByTestId(`${actionTypeModel.id}-card`)); + }); + + await waitFor(() => { + expect(getByTestId('create-connector-flyout-back-btn')).toBeInTheDocument(); + expect(getByTestId('create-connector-flyout-save-test-btn')).toBeInTheDocument(); + expect(getByTestId('create-connector-flyout-save-btn')).toBeInTheDocument(); + }); + }); + + it('does not show the save and test button if the onTestConnector is not provided', async () => { + const { queryByTestId } = appMockRenderer.render( + + ); + await act(() => Promise.resolve()); + + expect(queryByTestId('create-connector-flyout-save-test-btn')).not.toBeInTheDocument(); + }); + + it('disables the buttons when the user does not have permissions to create a connector', async () => { + appMockRenderer.coreStart.application.capabilities = { + ...appMockRenderer.coreStart.application.capabilities, + actions: { save: false, show: true }, + }; + + const { getByTestId } = appMockRenderer.render( + + ); + await act(() => Promise.resolve()); + + expect(getByTestId('create-connector-flyout-close-btn')).not.toBeDisabled(); + }); + + it('disables the buttons when there are error on the form', async () => { + const { getByTestId } = appMockRenderer.render( + + ); + await act(() => Promise.resolve()); + + act(() => { + userEvent.click(getByTestId(`${actionTypeModel.id}-card`)); + }); + + await waitFor(() => { + expect(getByTestId('test-connector-text-field')).toBeInTheDocument(); + }); + + act(() => { + userEvent.click(getByTestId('create-connector-flyout-save-btn')); + }); + + await waitFor(() => { + expect(getByTestId('create-connector-flyout-back-btn')).not.toBeDisabled(); + expect(getByTestId('create-connector-flyout-save-test-btn')).toBeDisabled(); + expect(getByTestId('create-connector-flyout-save-btn')).toBeDisabled(); + }); + }); + describe('Licensing', () => { it('renders banner with subscription links when gold features are disabled due to licensing', async () => { const disabledActionType = actionTypeRegistryMock.createMockActionTypeModel(); @@ -509,44 +606,6 @@ describe('CreateConnectorFlyout', () => { }); describe('Footer', () => { - it('shows the correct buttons without an action type selected', async () => { - const { getByTestId, queryByTestId } = appMockRenderer.render( - - ); - await act(() => Promise.resolve()); - - expect(getByTestId('create-connector-flyout-cancel-btn')).toBeInTheDocument(); - expect(queryByTestId('create-connector-flyout-save-test-btn')).toBe(null); - expect(queryByTestId('create-connector-flyout-save-btn')).toBe(null); - }); - - it('shows the correct buttons when selecting an action type', async () => { - const { getByTestId } = appMockRenderer.render( - - ); - await act(() => Promise.resolve()); - - act(() => { - userEvent.click(getByTestId(`${actionTypeModel.id}-card`)); - }); - - await waitFor(() => { - expect(getByTestId('create-connector-flyout-back-btn')).toBeInTheDocument(); - expect(getByTestId('create-connector-flyout-save-test-btn')).toBeInTheDocument(); - expect(getByTestId('create-connector-flyout-save-btn')).toBeInTheDocument(); - }); - }); - it('shows the action types when pressing the back button', async () => { const { getByTestId } = appMockRenderer.render( { expect(getByTestId(`${actionTypeModel.id}-card`)).toBeInTheDocument(); }); - it('does not show the save and test button if the onTestConnector is not provided', async () => { - const { queryByTestId } = appMockRenderer.render( - - ); - await act(() => Promise.resolve()); - - expect(queryByTestId('create-connector-flyout-save-test-btn')).not.toBeInTheDocument(); - }); - - it('closes the flyout when pressing cancel', async () => { + it('closes the flyout when pressing close', async () => { const { getByTestId } = appMockRenderer.render( { await act(() => Promise.resolve()); act(() => { - userEvent.click(getByTestId('create-connector-flyout-cancel-btn')); + userEvent.click(getByTestId('create-connector-flyout-close-btn')); }); expect(onClose).toHaveBeenCalled(); }); - - it('disables the buttons when the user does not have permissions to create a connector', async () => { - appMockRenderer.coreStart.application.capabilities = { - ...appMockRenderer.coreStart.application.capabilities, - actions: { save: false, show: true }, - }; - - const { getByTestId } = appMockRenderer.render( - - ); - await act(() => Promise.resolve()); - - expect(getByTestId('create-connector-flyout-cancel-btn')).not.toBeDisabled(); - }); - - it('disables the buttons when there are error on the form', async () => { - const { getByTestId } = appMockRenderer.render( - - ); - await act(() => Promise.resolve()); - - act(() => { - userEvent.click(getByTestId(`${actionTypeModel.id}-card`)); - }); - - await waitFor(() => { - expect(getByTestId('test-connector-text-field')).toBeInTheDocument(); - }); - - act(() => { - userEvent.click(getByTestId('create-connector-flyout-save-btn')); - }); - - await waitFor(() => { - expect(getByTestId('create-connector-flyout-back-btn')).not.toBeDisabled(); - expect(getByTestId('create-connector-flyout-save-test-btn')).toBeDisabled(); - expect(getByTestId('create-connector-flyout-save-btn')).toBeDisabled(); - }); - }); }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.tsx index f25d86458632a..32bd7931aecc8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/create_connector_flyout/index.tsx @@ -6,9 +6,10 @@ */ import React, { memo, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; -import { EuiFlyout, EuiFlyoutBody } from '@elastic/eui'; +import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiFlyout, EuiFlyoutBody } from '@elastic/eui'; import { getConnectorCompatibility } from '@kbn/actions-plugin/common'; +import { FormattedMessage } from '@kbn/i18n-react'; import { ActionConnector, ActionType, @@ -163,15 +164,7 @@ const CreateConnectorFlyoutComponent: React.FC = ({ : null} > - {actionType == null ? ( - - ) : null} - {actionType != null ? ( + {hasConnectorTypeSelected ? ( <> = ({ isEdit={false} onChange={setFormState} /> - {preSubmitValidationErrorMessage} + {!!preSubmitValidationErrorMessage &&

    {preSubmitValidationErrorMessage}

    } + + + + <> + {onTestConnector && ( + + + + + + )} + + + + + + + + + - ) : null} + ) : ( + + )}
    ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/footer.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/footer.tsx index 5f19449df2bb5..75d5e8aba4000 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/footer.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/footer.tsx @@ -6,84 +6,25 @@ */ import React, { memo } from 'react'; -import { - EuiFlexGroup, - EuiFlexItem, - EuiFlyoutFooter, - EuiButton, - EuiButtonEmpty, -} from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n-react'; +import { EuiFlexGroup, EuiFlexItem, EuiFlyoutFooter, EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; interface Props { - isSaving: boolean; - showButtons: boolean; - disabled: boolean; - onCancel: () => void; - onSubmit: () => void; - onSubmitAndClose: () => void; + onClose: () => void; } -const FlyoutFooterComponent: React.FC = ({ - isSaving, - showButtons, - disabled, - onCancel, - onSubmit, - onSubmitAndClose, -}) => { +const FlyoutFooterComponent: React.FC = ({ onClose }) => { return ( - - {i18n.translate( - 'xpack.triggersActionsUI.sections.editConnectorForm.cancelButtonLabel', - { - defaultMessage: 'Cancel', - } - )} + + {i18n.translate('xpack.triggersActionsUI.sections.editConnectorForm.closeButtonLabel', { + defaultMessage: 'Close', + })} - - - {showButtons ? ( - <> - - - - - - - - - - - - ) : null} - - + ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.test.tsx index 8a828fcfc9539..715279fa67b1a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.test.tsx @@ -11,10 +11,7 @@ import { actionTypeRegistryMock } from '../../../action_type_registry.mock'; import userEvent from '@testing-library/user-event'; import { waitFor } from '@testing-library/dom'; import { act } from '@testing-library/react'; -import { - AppMockRenderer, - createAppMockRenderer, -} from '../../../components/builtin_action_types/test_utils'; +import { AppMockRenderer, createAppMockRenderer } from '../../../components/test_utils'; import EditConnectorFlyout from '.'; import { ActionConnector, EditConnectorTabs, GenericValidationResult } from '../../../../types'; import { betaBadgeProps } from '../beta_badge_props'; @@ -88,6 +85,52 @@ describe('EditConnectorFlyout', () => { expect(getByTestId('edit-connector-flyout-footer')).toBeInTheDocument(); }); + it('enables save button when the form is modified', async () => { + const { getByTestId } = appMockRenderer.render( + + ); + expect(getByTestId('edit-connector-flyout-save-btn')).toBeDisabled(); + + await act(async () => { + await userEvent.clear(getByTestId('nameInput')); + await userEvent.type(getByTestId('nameInput'), 'My new name', { + delay: 10, + }); + }); + + expect(getByTestId('edit-connector-flyout-save-btn')).not.toBeDisabled(); + }); + + it('shows a confirmation modal on close if the form is modified', async () => { + const { getByTestId, getByText } = appMockRenderer.render( + + ); + expect(getByTestId('edit-connector-flyout-save-btn')).toBeDisabled(); + + await act(async () => { + await userEvent.clear(getByTestId('nameInput')); + await userEvent.type(getByTestId('nameInput'), 'My new name', { + delay: 10, + }); + }); + + act(() => { + userEvent.click(getByTestId('edit-connector-flyout-close-btn')); + }); + + expect(getByText('Discard unsaved changes to connector?')).toBeInTheDocument(); + }); + it('renders the connector form correctly', async () => { const { getByTestId, queryByText } = appMockRenderer.render( { expect(getByText('This connector is readonly.')).toBeInTheDocument(); }); + it('shows the buttons', async () => { + const { getByTestId } = appMockRenderer.render( + + ); + + expect(getByTestId('edit-connector-flyout-save-btn')).toBeInTheDocument(); + expect(getByTestId('edit-connector-flyout-close-btn')).toBeInTheDocument(); + }); + + it('does not show the save button if the use does not have permissions to update connector', async () => { + appMockRenderer.coreStart.application.capabilities = { + ...appMockRenderer.coreStart.application.capabilities, + actions: { save: false, show: true }, + }; + + const { queryByTestId } = appMockRenderer.render( + + ); + + expect(queryByTestId('edit-connector-flyout-save-btn')).not.toBeInTheDocument(); + }); + + it('does not show the save button if the connector is preconfigured', async () => { + const { queryByTestId } = appMockRenderer.render( + + ); + + expect(queryByTestId('edit-connector-flyout-save-btn')).not.toBeInTheDocument(); + }); + + it('disables the buttons when there are error on the form', async () => { + const { getByTestId } = appMockRenderer.render( + + ); + + await waitFor(() => { + expect(getByTestId('test-connector-text-field')).toBeInTheDocument(); + }); + + act(() => { + /** + * Clear the name so the form can be invalid + */ + userEvent.clear(getByTestId('nameInput')); + }); + act(() => { + userEvent.click(getByTestId('edit-connector-flyout-save-btn')); + }); + + await waitFor(() => { + expect(getByTestId('edit-connector-flyout-close-btn')).not.toBeDisabled(); + expect(getByTestId('edit-connector-flyout-save-btn')).toBeDisabled(); + }); + }); + describe('Header', () => { it('shows the icon', async () => { const { getByTestId } = appMockRenderer.render( @@ -327,7 +445,7 @@ describe('EditConnectorFlyout', () => { }); it('updates the connector and close the flyout correctly', async () => { - const { getByTestId } = appMockRenderer.render( + const { getByTestId, getByText } = appMockRenderer.render( { }); act(() => { - userEvent.click(getByTestId('edit-connector-flyout-save-close-btn')); + userEvent.click(getByTestId('edit-connector-flyout-save-btn')); }); await waitFor(() => { @@ -363,6 +481,12 @@ describe('EditConnectorFlyout', () => { ); }); + expect(getByText('Changes Saved')).toBeInTheDocument(); + + act(() => { + userEvent.click(getByTestId('edit-connector-flyout-close-btn')); + }); + expect(onClose).toHaveBeenCalled(); expect(onConnectorUpdated).toHaveBeenCalledWith({ actionTypeId: 'test', @@ -395,6 +519,13 @@ describe('EditConnectorFlyout', () => { expect(getByTestId('test-connector-error-text-field')).toBeInTheDocument(); }); + await act(async () => { + await userEvent.clear(getByTestId('nameInput')); + await userEvent.type(getByTestId('nameInput'), 'My new name', { + delay: 100, + }); + }); + act(() => { userEvent.click(getByTestId('edit-connector-flyout-save-btn')); }); @@ -559,100 +690,4 @@ describe('EditConnectorFlyout', () => { expect(getByTestId('executeActionButton')).toBeDisabled(); }); }); - - describe('Footer', () => { - it('shows the buttons', async () => { - const { getByTestId } = appMockRenderer.render( - - ); - - expect(getByTestId('edit-connector-flyout-cancel-btn')).toBeInTheDocument(); - expect(getByTestId('edit-connector-flyout-save-btn')).toBeInTheDocument(); - expect(getByTestId('edit-connector-flyout-save-close-btn')).toBeInTheDocument(); - }); - - it('does not show the save and save and close button if the use does not have permissions to update connector', async () => { - appMockRenderer.coreStart.application.capabilities = { - ...appMockRenderer.coreStart.application.capabilities, - actions: { save: false, show: true }, - }; - - const { queryByTestId } = appMockRenderer.render( - - ); - - expect(queryByTestId('edit-connector-flyout-save-btn')).not.toBeInTheDocument(); - expect(queryByTestId('edit-connector-flyout-save-close-btn')).not.toBeInTheDocument(); - }); - - it('does not show the save and save and close button if the connector is preconfigured', async () => { - const { queryByTestId } = appMockRenderer.render( - - ); - - expect(queryByTestId('edit-connector-flyout-save-btn')).not.toBeInTheDocument(); - expect(queryByTestId('edit-connector-flyout-save-close-btn')).not.toBeInTheDocument(); - }); - - it('closes the flyout when pressing cancel', async () => { - const { getByTestId } = appMockRenderer.render( - - ); - - act(() => { - userEvent.click(getByTestId('edit-connector-flyout-cancel-btn')); - }); - - expect(onClose).toHaveBeenCalled(); - }); - - it('disables the buttons when there are error on the form', async () => { - const { getByTestId } = appMockRenderer.render( - - ); - - await waitFor(() => { - expect(getByTestId('test-connector-text-field')).toBeInTheDocument(); - }); - - act(() => { - /** - * Clear the name so the form can be invalid - */ - userEvent.clear(getByTestId('nameInput')); - userEvent.click(getByTestId('edit-connector-flyout-save-btn')); - }); - - await waitFor(() => { - expect(getByTestId('edit-connector-flyout-cancel-btn')).not.toBeDisabled(); - expect(getByTestId('edit-connector-flyout-save-close-btn')).toBeDisabled(); - expect(getByTestId('edit-connector-flyout-save-btn')).toBeDisabled(); - }); - }); - }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.tsx index 452a89d04f9c1..e00349cecd62b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/edit_connector_flyout/index.tsx @@ -6,7 +6,14 @@ */ import React, { memo, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; -import { EuiFlyout, EuiText, EuiFlyoutBody, EuiLink } from '@elastic/eui'; +import { + EuiFlyout, + EuiText, + EuiFlyoutBody, + EuiLink, + EuiButton, + EuiConfirmModal, +} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import { ActionTypeExecutorResult, isActionTypeExecutorResult } from '@kbn/actions-plugin/common'; @@ -73,6 +80,7 @@ const EditConnectorFlyoutComponent: React.FC = ({ docLinks, application: { capabilities }, } = useKibana().services; + const isMounted = useRef(false); const canSave = hasSaveActionsCapability(capabilities); const { isLoading: isUpdatingConnector, updateConnector } = useUpdateConnector(); @@ -117,7 +125,9 @@ const EditConnectorFlyoutComponent: React.FC = ({ ); const [isFormModified, setIsFormModified] = useState(false); - + const [showConfirmModal, setShowConfirmModal] = useState(false); + const [isEdit, setIsEdit] = useState(true); + const [isSaved, setIsSaved] = useState(false); const { preSubmitValidator, submit, isValid: isFormValid, isSubmitting } = formState; const hasErrors = isFormValid === false; const isSaving = isUpdatingConnector || isSubmitting || isExecutingConnector; @@ -146,6 +156,9 @@ const EditConnectorFlyoutComponent: React.FC = ({ const onFormModifiedChange = useCallback( (formModified: boolean) => { + if (formModified) { + setIsSaved(false); + } setIsFormModified(formModified); setTestExecutionResult(none); }, @@ -153,76 +166,72 @@ const EditConnectorFlyoutComponent: React.FC = ({ ); const closeFlyout = useCallback(() => { + if (isFormModified) { + setShowConfirmModal(true); + return; + } onClose(); - }, [onClose]); + }, [onClose, isFormModified, setShowConfirmModal]); - const onClickSave = useCallback( - async (closeAfterSave: boolean = true) => { - setPreSubmitValidationErrorMessage(null); + const onClickSave = useCallback(async () => { + setPreSubmitValidationErrorMessage(null); - const { isValid, data } = await submit(); - if (!isMounted.current) { - // User has closed the flyout meanwhile submitting the form - return; - } + const { isValid, data } = await submit(); + if (!isMounted.current) { + // User has closed the flyout meanwhile submitting the form + return; + } - if (isValid) { - if (preSubmitValidator) { - const validatorRes = await preSubmitValidator(); + if (isValid) { + if (preSubmitValidator) { + const validatorRes = await preSubmitValidator(); - if (validatorRes) { - setPreSubmitValidationErrorMessage(validatorRes.message); - return; - } + if (validatorRes) { + setPreSubmitValidationErrorMessage(validatorRes.message); + return; } + } + + /** + * At this point the form is valid + * and there are no pre submit error messages. + */ + const { name, config, secrets } = data; + const validConnector = { + id: connector.id, + name: name ?? '', + config: config ?? {}, + secrets: secrets ?? {}, + }; + + const updatedConnector = await updateConnector(validConnector); + + if (updatedConnector) { /** - * At this point the form is valid - * and there are no pre submit error messages. + * ConnectorFormSchema has been saved. + * Set the from to clean state. */ + onFormModifiedChange(false); - const { name, config, secrets } = data; - const validConnector = { - id: connector.id, - name: name ?? '', - config: config ?? {}, - secrets: secrets ?? {}, - }; - - const updatedConnector = await updateConnector(validConnector); - - if (updatedConnector) { - /** - * ConnectorFormSchema has been saved. - * Set the from to clean state. - */ - onFormModifiedChange(false); - - if (onConnectorUpdated && updatedConnector) { - onConnectorUpdated(updatedConnector); - } - - if (closeAfterSave) { - closeFlyout(); - } + if (onConnectorUpdated) { + onConnectorUpdated(updatedConnector); } - - return updatedConnector; + setIsSaved(true); + setIsEdit(false); + setIsEdit(true); } - }, - [ - submit, - preSubmitValidator, - connector.id, - updateConnector, - onFormModifiedChange, - onConnectorUpdated, - closeFlyout, - ] - ); - const onSubmit = useCallback(() => onClickSave(false), [onClickSave]); - const onSubmitAndClose = useCallback(() => onClickSave(true), [onClickSave]); + return updatedConnector; + } + }, [ + onConnectorUpdated, + submit, + preSubmitValidator, + connector.id, + updateConnector, + onFormModifiedChange, + ]); useEffect(() => { isMounted.current = true; @@ -233,59 +242,114 @@ const EditConnectorFlyoutComponent: React.FC = ({ }, []); return ( - - - - {selectedTab === EditConnectorTabs.Configuration ? ( - !connector.isPreconfigured ? ( - <> - - {preSubmitValidationErrorMessage} - + <> + + + + {selectedTab === EditConnectorTabs.Configuration ? ( + !connector.isPreconfigured ? ( + <> + {isEdit && ( + <> + + {!!preSubmitValidationErrorMessage &&

    {preSubmitValidationErrorMessage}

    } + {showButtons && ( + + {isSaved ? ( + + ) : ( + + )} + + )} + + )} + + ) : ( + + ) ) : ( - - ) - ) : ( - + )} +
    + +
    + {showConfirmModal && ( + { + setShowConfirmModal(false); + }} + onConfirm={onClose} + cancelButtonText={i18n.translate( + 'xpack.triggersActionsUI.sections.confirmConnectorEditClose.cancelButtonLabel', + { + defaultMessage: 'Cancel', + } + )} + confirmButtonText={i18n.translate( + 'xpack.triggersActionsUI.sections.confirmConnectorEditClose.discardButtonLabel', + { + defaultMessage: 'Discard Changes', + } + )} + > + - )} -
    - -
    + + )} + ); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/encrypted_fields_callout.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/encrypted_fields_callout.test.tsx index 6c55cd34c0655..41893e785f5bf 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/encrypted_fields_callout.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/encrypted_fields_callout.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { UseField } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib'; -import { FormTestProvider } from '../../components/builtin_action_types/test_utils'; +import { FormTestProvider } from '../../components/test_utils'; import { EncryptedFieldsCallout } from './encrypted_fields_callout'; import { render, RenderResult } from '@testing-library/react'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/index.ts index 993139926b696..d832351538601 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/index.ts @@ -26,3 +26,5 @@ export const ConnectorAddModal = suspendedComponentWithProps import('./connector_add_inline')) ); + +export type { ConnectorFormSchema } from './types'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx index 249f9f503fcf8..e973fce282dcb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx @@ -525,7 +525,7 @@ const ActionsConnectorsList: React.FunctionComponent = () => { setEditConnectorProps(omit(editConnectorProps, 'initialConnector')); }} onConnectorUpdated={(connector) => { - setEditConnectorProps({ initialConnector: connector }); + setEditConnectorProps({ ...editConnectorProps, initialConnector: connector }); loadActions(); }} actionTypeRegistry={actionTypeRegistry} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/alerts_flyout/alerts_flyout.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/alerts_flyout/alerts_flyout.tsx index e57e8c9902069..3ddefe1c4cf68 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/alerts_flyout/alerts_flyout.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/alerts_flyout/alerts_flyout.tsx @@ -99,7 +99,7 @@ export const AlertsFlyout: React.FunctionComponent = ({ ); return ( - + {isLoading && } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/toggle_column.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/toggle_column.ts index f7f181c60b024..ae7bceed0ac80 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/toggle_column.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/toggle_column.ts @@ -7,57 +7,59 @@ import { EuiDataGridColumn } from '@elastic/eui'; -const remove = ({ columnIds, index }: { columnIds: string[]; index: number }) => { - return [...columnIds.slice(0, index), ...columnIds.slice(index + 1)]; +const remove = ({ columns, index }: { columns: EuiDataGridColumn[]; index: number }) => { + return [...columns.slice(0, index), ...columns.slice(index + 1)]; }; const insert = ({ - columnId, - columnIds, + column, + columns, defaultColumns, }: { - columnId: string; - columnIds: string[]; + column: EuiDataGridColumn; + columns: EuiDataGridColumn[]; defaultColumns: EuiDataGridColumn[]; }) => { const defaultIndex = defaultColumns.findIndex( - (column: EuiDataGridColumn) => column.id === columnId + (defaultColumn: EuiDataGridColumn) => defaultColumn.id === column.id ); const isInDefaultConfig = defaultIndex >= 0; // if the column isn't shown but it's part of the default config // insert into the same position as in the default config if (isInDefaultConfig) { - return [...columnIds.slice(0, defaultIndex), columnId, ...columnIds.slice(defaultIndex)]; + return [...columns.slice(0, defaultIndex), column, ...columns.slice(defaultIndex)]; } // if the column isn't shown and it's not part of the default config // push it into the second position. Behaviour copied by t_grid, security // does this to insert right after the timestamp column - return [columnIds[0], columnId, ...columnIds.slice(1)]; + return [columns[0], column, ...columns.slice(1)]; }; /** - * @param param.columnId id of the column to be removed/inserted - * @param param.columnIds Current array of columnIds in the grid - * @param param.defaultColumns Those initial columns set up in the configuration before being modified by the user - * @returns the new list of columns to be shown + * @param param.column column to be removed/inserted + * @param param.columns current array of columns in the grid + * @param param.defaultColumns Initial columns set up in the configuration before being modified by the user + * @returns the new list of columns */ export const toggleColumn = ({ - columnId, - columnIds, + column, + columns, defaultColumns, }: { - columnId: string; - columnIds: string[]; + column: EuiDataGridColumn; + columns: EuiDataGridColumn[]; defaultColumns: EuiDataGridColumn[]; -}): string[] => { - const currentIndex = columnIds.indexOf(columnId); +}): EuiDataGridColumn[] => { + const currentIndex = columns.findIndex( + (currentColumn: EuiDataGridColumn) => currentColumn.id === column.id + ); const isVisible = currentIndex >= 0; if (isVisible) { - return remove({ columnIds, index: currentIndex }); + return remove({ columns, index: currentIndex }); } - return insert({ defaultColumns, columnId, columnIds }); + return insert({ defaultColumns, column, columns }); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/use_columns.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/use_columns.ts index eb6f6adad1cc5..f10807824e8fc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/use_columns.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_columns/use_columns.ts @@ -7,12 +7,12 @@ import { EuiDataGridColumn } from '@elastic/eui'; import { IStorageWrapper } from '@kbn/kibana-utils-plugin/public'; -import { AlertConsumers } from '@kbn/rule-data-utils'; import { BrowserField, BrowserFields } from '@kbn/rule-registry-plugin/common'; import { useCallback, useEffect, useState } from 'react'; +import { AlertConsumers } from '@kbn/rule-data-utils'; import { AlertsTableStorage } from '../../alerts_table_state'; -import { useFetchBrowserFieldCapabilities } from '../use_fetch_browser_fields_capabilities'; import { toggleColumn } from './toggle_column'; +import { useFetchBrowserFieldCapabilities } from '../use_fetch_browser_fields_capabilities'; interface UseColumnsArgs { featureIds: AlertConsumers[]; @@ -29,43 +29,62 @@ const fieldTypeToDataGridColumnTypeMapper = (fieldType: string | undefined) => { return fieldType; }; +const getFieldCategoryFromColumnId = (columnId: string): string => { + const fieldName = columnId.split('.'); + + if (fieldName.length === 1) { + return 'base'; + } + + return fieldName[0]; +}; + /** * EUI Data Grid expects the columns to have a property 'schema' defined for proper sorting * this schema as its own types as can be check out in the docs so we add it here manually * https://eui.elastic.co/#/tabular-content/data-grid-schema-columns */ const euiColumnFactory = ( - column: EuiDataGridColumn, - browserFields: BrowserFields + columnId: string, + browserFields: BrowserFields, + defaultColumns: EuiDataGridColumn[] ): EuiDataGridColumn => { - const browserFieldsProps = getBrowserFieldProps(column.id, browserFields); + const defaultColumn = getColumnByColumnId(defaultColumns, columnId); + const column = defaultColumn ? defaultColumn : { id: columnId }; + + const browserFieldsProps = getBrowserFieldProps(columnId, browserFields); return { ...column, schema: fieldTypeToDataGridColumnTypeMapper(browserFieldsProps.type), }; }; -/** - * Searches in browser fields object for a specific field - */ const getBrowserFieldProps = ( columnId: string, browserFields: BrowserFields ): Partial => { - for (const [, categoryDescriptor] of Object.entries(browserFields)) { - if (!categoryDescriptor.fields) { - continue; - } - - for (const [fieldName, fieldDescriptor] of Object.entries(categoryDescriptor.fields)) { - if (fieldName === columnId) { - return fieldDescriptor; - } - } + const notFoundSpecs = { type: 'string' }; + + if (!browserFields || Object.keys(browserFields).length === 0) { + return notFoundSpecs; + } + + const category = getFieldCategoryFromColumnId(columnId); + if (!browserFields[category]) { + return notFoundSpecs; + } + + const categorySpecs = browserFields[category].fields; + if (!categorySpecs) { + return notFoundSpecs; } - return { type: 'string' }; + + const fieldSpecs = categorySpecs[columnId]; + return fieldSpecs ? fieldSpecs : notFoundSpecs; }; +const isPopulatedColumn = (column: EuiDataGridColumn) => Boolean(column.schema); + /** * @param columns Columns to be considered in the alerts table * @param browserFields constant object with all field capabilities @@ -73,10 +92,13 @@ const getBrowserFieldProps = ( */ const populateColumns = ( columns: EuiDataGridColumn[], - browserFields: BrowserFields + browserFields: BrowserFields, + defaultColumns: EuiDataGridColumn[] ): EuiDataGridColumn[] => { return columns.map((column: EuiDataGridColumn) => { - return euiColumnFactory(column, browserFields); + return isPopulatedColumn(column) + ? column + : euiColumnFactory(column.id, browserFields, defaultColumns); }); }; @@ -128,10 +150,10 @@ export const useColumns = ({ useEffect(() => { if (isBrowserFieldDataLoading !== false || isColumnsPopulated) return; - const populatedColumns = populateColumns(columns, browserFields); + const populatedColumns = populateColumns(columns, browserFields, defaultColumns); setColumnsPopulated(true); setColumns(populatedColumns); - }, [browserFields, columns, isBrowserFieldDataLoading, isColumnsPopulated]); + }, [browserFields, columns, defaultColumns, isBrowserFieldDataLoading, isColumnsPopulated]); const setColumnsAndSave = useCallback( (newColumns: EuiDataGridColumn[]) => { @@ -156,15 +178,12 @@ export const useColumns = ({ const onToggleColumn = useCallback( (columnId: string): void => { - const newColumnIds = toggleColumn({ - columnId, - columnIds: getColumnIds(columns), - defaultColumns, - }); + const column = euiColumnFactory(columnId, browserFields, defaultColumns); - const newColumns = newColumnIds.map((_columnId: string) => { - const column = getColumnByColumnId(defaultColumns, _columnId); - return euiColumnFactory(column ? column : { id: _columnId }, browserFields); + const newColumns = toggleColumn({ + column, + columns, + defaultColumns, }); setColumnsAndSave(newColumns); @@ -173,7 +192,7 @@ export const useColumns = ({ ); const onResetColumns = useCallback(() => { - const populatedDefaultColumns = populateColumns(defaultColumns, browserFields); + const populatedDefaultColumns = populateColumns(defaultColumns, browserFields, defaultColumns); setColumnsAndSave(populatedDefaultColumns); }, [browserFields, defaultColumns, setColumnsAndSave]); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.test.tsx index 4e6ae5c7cdb91..fcf1ba99b7af4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.test.tsx @@ -20,9 +20,13 @@ jest.mock('../../../../common/lib/kibana', () => ({ const setRulesToUpdateAPIKey = jest.fn(); const setRulesToSnooze = jest.fn(); +const setRulesToUnsnooze = jest.fn(); const setRulesToSchedule = jest.fn(); +const setRulesToUnschedule = jest.fn(); const setRulesToSnoozeFilter = jest.fn(); +const setRulesToUnsnoozeFilter = jest.fn(); const setRulesToScheduleFilter = jest.fn(); +const setRulesToUnscheduleFilter = jest.fn(); const setRulesToUpdateAPIKeyFilter = jest.fn(); describe('rule_quick_edit_buttons', () => { @@ -39,16 +43,20 @@ describe('rule_quick_edit_buttons', () => { const wrapper = mountWithIntl( ''} + getFilter={() => null} selectedItems={[mockRule]} onPerformingAction={() => {}} onActionPerformed={() => {}} setRulesToDelete={() => {}} setRulesToUpdateAPIKey={() => {}} setRulesToSnooze={() => {}} + setRulesToUnsnooze={() => {}} setRulesToSchedule={() => {}} + setRulesToUnschedule={() => {}} setRulesToSnoozeFilter={() => {}} + setRulesToUnsnoozeFilter={() => {}} setRulesToScheduleFilter={() => {}} + setRulesToUnscheduleFilter={() => {}} setRulesToUpdateAPIKeyFilter={() => {}} /> ); @@ -58,7 +66,9 @@ describe('rule_quick_edit_buttons', () => { expect(wrapper.find('[data-test-subj="updateAPIKeys"]').exists()).toBeTruthy(); expect(wrapper.find('[data-test-subj="deleteAll"]').exists()).toBeTruthy(); expect(wrapper.find('[data-test-subj="bulkSnooze"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="bulkUnsnooze"]').exists()).toBeTruthy(); expect(wrapper.find('[data-test-subj="bulkSnoozeSchedule"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="bulkRemoveSnoozeSchedule"]').exists()).toBeTruthy(); }); it('renders enableAll if rules are all disabled', async () => { @@ -70,16 +80,20 @@ describe('rule_quick_edit_buttons', () => { const wrapper = mountWithIntl( ''} + getFilter={() => null} selectedItems={[mockRule]} onPerformingAction={() => {}} onActionPerformed={() => {}} setRulesToDelete={() => {}} setRulesToUpdateAPIKey={() => {}} setRulesToSnooze={() => {}} + setRulesToUnsnooze={() => {}} setRulesToSchedule={() => {}} + setRulesToUnschedule={() => {}} setRulesToSnoozeFilter={() => {}} + setRulesToUnsnoozeFilter={() => {}} setRulesToScheduleFilter={() => {}} + setRulesToUnscheduleFilter={() => {}} setRulesToUpdateAPIKeyFilter={() => {}} /> ); @@ -97,27 +111,34 @@ describe('rule_quick_edit_buttons', () => { const wrapper = mountWithIntl( ''} + getFilter={() => null} selectedItems={[mockRule]} onPerformingAction={() => {}} onActionPerformed={() => {}} setRulesToDelete={() => {}} setRulesToUpdateAPIKey={() => {}} setRulesToSnooze={() => {}} + setRulesToUnsnooze={() => {}} setRulesToSchedule={() => {}} + setRulesToUnschedule={() => {}} setRulesToSnoozeFilter={() => {}} + setRulesToUnsnoozeFilter={() => {}} setRulesToScheduleFilter={() => {}} + setRulesToUnscheduleFilter={() => {}} setRulesToUpdateAPIKeyFilter={() => {}} /> ); expect(wrapper.find('[data-test-subj="disableAll"]').first().prop('isDisabled')).toBeTruthy(); expect(wrapper.find('[data-test-subj="deleteAll"]').first().prop('isDisabled')).toBeTruthy(); - - expect(wrapper.find('[data-test-subj="updateAPIKeys"]').first().prop('isDiabled')).toBeFalsy(); - expect(wrapper.find('[data-test-subj="bulkSnooze"]').first().prop('isDiabled')).toBeFalsy(); + expect(wrapper.find('[data-test-subj="updateAPIKeys"]').first().prop('isDisabled')).toBeFalsy(); + expect(wrapper.find('[data-test-subj="bulkSnooze"]').first().prop('isDisabled')).toBeFalsy(); + expect(wrapper.find('[data-test-subj="bulkUnsnooze"]').first().prop('isDisabled')).toBeFalsy(); + expect( + wrapper.find('[data-test-subj="bulkSnoozeSchedule"]').first().prop('isDisabled') + ).toBeFalsy(); expect( - wrapper.find('[data-test-subj="bulkSnoozeSchedule"]').first().prop('isDiabled') + wrapper.find('[data-test-subj="bulkRemoveSnoozeSchedule"]').first().prop('isDisabled') ).toBeFalsy(); }); @@ -131,16 +152,20 @@ describe('rule_quick_edit_buttons', () => { const wrapper = mountWithIntl( ''} + getFilter={() => null} selectedItems={[mockRule]} onPerformingAction={() => {}} onActionPerformed={() => {}} setRulesToDelete={() => {}} setRulesToSnooze={setRulesToSnooze} + setRulesToUnsnooze={setRulesToUnsnooze} setRulesToSchedule={setRulesToSchedule} + setRulesToUnschedule={setRulesToUnschedule} setRulesToUpdateAPIKey={setRulesToUpdateAPIKey} setRulesToSnoozeFilter={setRulesToSnoozeFilter} + setRulesToUnsnoozeFilter={setRulesToUnsnoozeFilter} setRulesToScheduleFilter={setRulesToScheduleFilter} + setRulesToUnscheduleFilter={setRulesToUnscheduleFilter} setRulesToUpdateAPIKeyFilter={setRulesToUpdateAPIKeyFilter} /> ); @@ -148,14 +173,22 @@ describe('rule_quick_edit_buttons', () => { wrapper.find('[data-test-subj="bulkSnooze"]').first().simulate('click'); expect(setRulesToSnooze).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkUnsnooze"]').first().simulate('click'); + expect(setRulesToUnsnooze).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkSnoozeSchedule"]').first().simulate('click'); expect(setRulesToSchedule).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkRemoveSnoozeSchedule"]').first().simulate('click'); + expect(setRulesToUnschedule).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="updateAPIKeys"]').first().simulate('click'); expect(setRulesToUpdateAPIKey).toHaveBeenCalledTimes(1); expect(setRulesToSnoozeFilter).not.toHaveBeenCalled(); + expect(setRulesToUnsnoozeFilter).not.toHaveBeenCalled(); expect(setRulesToScheduleFilter).not.toHaveBeenCalled(); + expect(setRulesToUnscheduleFilter).not.toHaveBeenCalled(); expect(setRulesToUpdateAPIKeyFilter).not.toHaveBeenCalled(); }); @@ -169,16 +202,20 @@ describe('rule_quick_edit_buttons', () => { const wrapper = mountWithIntl( ''} + getFilter={() => null} selectedItems={[mockRule]} onPerformingAction={() => {}} onActionPerformed={() => {}} setRulesToDelete={() => {}} setRulesToSnooze={setRulesToSnooze} + setRulesToUnsnooze={setRulesToUnsnooze} setRulesToSchedule={setRulesToSchedule} + setRulesToUnschedule={setRulesToUnschedule} setRulesToUpdateAPIKey={setRulesToUpdateAPIKey} setRulesToSnoozeFilter={setRulesToSnoozeFilter} + setRulesToUnsnoozeFilter={setRulesToUnsnoozeFilter} setRulesToScheduleFilter={setRulesToScheduleFilter} + setRulesToUnscheduleFilter={setRulesToUnscheduleFilter} setRulesToUpdateAPIKeyFilter={setRulesToUpdateAPIKeyFilter} /> ); @@ -186,14 +223,22 @@ describe('rule_quick_edit_buttons', () => { wrapper.find('[data-test-subj="bulkSnooze"]').first().simulate('click'); expect(setRulesToSnoozeFilter).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkUnsnooze"]').first().simulate('click'); + expect(setRulesToUnsnoozeFilter).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkSnoozeSchedule"]').first().simulate('click'); expect(setRulesToScheduleFilter).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="bulkRemoveSnoozeSchedule"]').first().simulate('click'); + expect(setRulesToUnscheduleFilter).toHaveBeenCalledTimes(1); + wrapper.find('[data-test-subj="updateAPIKeys"]').first().simulate('click'); expect(setRulesToUpdateAPIKeyFilter).toHaveBeenCalledTimes(1); - expect(setRulesToSchedule).not.toHaveBeenCalled(); expect(setRulesToSnooze).not.toHaveBeenCalled(); + expect(setRulesToUnsnooze).not.toHaveBeenCalled(); + expect(setRulesToSchedule).not.toHaveBeenCalled(); + expect(setRulesToUnschedule).not.toHaveBeenCalled(); expect(setRulesToUpdateAPIKey).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.tsx index 0b7db1ebeceba..f3cbae535d777 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/common/components/rule_quick_edit_buttons.tsx @@ -6,6 +6,7 @@ */ import { i18n } from '@kbn/i18n'; +import { KueryNode } from '@kbn/es-query'; import React, { useState, useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiButtonEmpty, EuiFlexItem, EuiFlexGroup, EuiIconTip } from '@elastic/eui'; @@ -21,19 +22,25 @@ import { useKibana } from '../../../../common/lib/kibana'; export type ComponentOpts = { selectedItems: RuleTableItem[]; isAllSelected?: boolean; - getFilter: () => string; + getFilter: () => KueryNode | null; onPerformingAction?: () => void; onActionPerformed?: () => void; isSnoozingRules?: boolean; + isUnsnoozingRules?: boolean; isSchedulingRules?: boolean; + isUnschedulingRules?: boolean; isUpdatingRuleAPIKeys?: boolean; setRulesToDelete: React.Dispatch>; setRulesToUpdateAPIKey: React.Dispatch>; setRulesToSnooze: React.Dispatch>; + setRulesToUnsnooze: React.Dispatch>; setRulesToSchedule: React.Dispatch>; - setRulesToSnoozeFilter: React.Dispatch>; - setRulesToScheduleFilter: React.Dispatch>; - setRulesToUpdateAPIKeyFilter: React.Dispatch>; + setRulesToUnschedule: React.Dispatch>; + setRulesToSnoozeFilter: React.Dispatch>; + setRulesToUnsnoozeFilter: React.Dispatch>; + setRulesToScheduleFilter: React.Dispatch>; + setRulesToUnscheduleFilter: React.Dispatch>; + setRulesToUpdateAPIKeyFilter: React.Dispatch>; } & BulkOperationsComponentOpts; const ButtonWithTooltip = ({ @@ -65,16 +72,22 @@ export const RuleQuickEditButtons: React.FunctionComponent = ({ onPerformingAction = noop, onActionPerformed = noop, isSnoozingRules = false, + isUnsnoozingRules = false, isSchedulingRules = false, + isUnschedulingRules = false, isUpdatingRuleAPIKeys = false, enableRules, disableRules, setRulesToDelete, setRulesToUpdateAPIKey, setRulesToSnooze, + setRulesToUnsnooze, setRulesToSchedule, + setRulesToUnschedule, setRulesToSnoozeFilter, + setRulesToUnsnoozeFilter, setRulesToScheduleFilter, + setRulesToUnscheduleFilter, setRulesToUpdateAPIKeyFilter, }: ComponentOpts) => { const { @@ -90,7 +103,9 @@ export const RuleQuickEditButtons: React.FunctionComponent = ({ isDisablingRules || isDeletingRules || isSnoozingRules || + isUnsnoozingRules || isSchedulingRules || + isUnschedulingRules || isUpdatingRuleAPIKeys; const allRulesDisabled = useMemo(() => { @@ -220,6 +235,28 @@ export const RuleQuickEditButtons: React.FunctionComponent = ({ } } + async function onUnsnoozeAllClick() { + onPerformingAction(); + try { + if (isAllSelected) { + setRulesToUnsnoozeFilter(getFilter()); + } else { + setRulesToUnsnooze(selectedItems); + } + } catch (e) { + toasts.addDanger({ + title: i18n.translate( + 'xpack.triggersActionsUI.sections.rulesList.bulkActionPopover.failedToSnoozeRules', + { + defaultMessage: 'Failed to snooze or unsnooze rules', + } + ), + }); + } finally { + onActionPerformed(); + } + } + async function onScheduleAllClick() { onPerformingAction(); try { @@ -242,6 +279,28 @@ export const RuleQuickEditButtons: React.FunctionComponent = ({ } } + async function onUnscheduleAllClick() { + onPerformingAction(); + try { + if (isAllSelected) { + setRulesToUnscheduleFilter(getFilter()); + } else { + setRulesToUnschedule(selectedItems); + } + } catch (e) { + toasts.addDanger({ + title: i18n.translate( + 'xpack.triggersActionsUI.sections.rulesList.bulkActionPopover.failedToSnoozeRules', + { + defaultMessage: 'Failed to snooze or unsnooze rules', + } + ), + }); + } finally { + onActionPerformed(); + } + } + return ( = ({ />
    + + + + + = ({ /> + + + + + Promise; loadRuleSummary: (id: Rule['id'], numberOfExecutions?: number) => Promise; loadRuleTypes: () => Promise; + loadExecutionKPIAggregations: ( + props: LoadExecutionKPIAggregationsProps + ) => Promise; loadExecutionLogAggregations: ( props: LoadExecutionLogAggregationsProps ) => Promise; loadGlobalExecutionLogAggregations: ( props: LoadGlobalExecutionLogAggregationsProps ) => Promise; + loadGlobalExecutionKPIAggregations: ( + props: LoadGlobalExecutionKPIAggregationsProps + ) => Promise; loadActionErrorLog: (props: LoadActionErrorLogProps) => Promise; getHealth: () => Promise; resolveRule: (id: Rule['id']) => Promise; @@ -177,6 +191,22 @@ export function withBulkRuleOperations( http, }) } + loadExecutionKPIAggregations={async ( + loadExecutionKPIAggregationProps: LoadExecutionKPIAggregationsProps + ) => + loadExecutionKPIAggregations({ + ...loadExecutionKPIAggregationProps, + http, + }) + } + loadGlobalExecutionKPIAggregations={async ( + loadGlobalExecutionKPIAggregationsProps: LoadGlobalExecutionKPIAggregationsProps + ) => + loadGlobalExecutionKPIAggregations({ + ...loadGlobalExecutionKPIAggregationsProps, + http, + }) + } resolveRule={async (ruleId: Rule['id']) => resolveRule({ http, ruleId })} getHealth={async () => alertingFrameworkHealth({ http })} snoozeRule={async (rule: Rule, snoozeSchedule: SnoozeSchedule) => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_error.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_error.tsx new file mode 100644 index 0000000000000..1ee04fe2f69d1 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_error.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { EuiEmptyPrompt } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n-react'; + +export const AlertSummaryWidgetError = () => { + return ( + + + + } + body={ +

    + { + + } +

    + } + /> + ); +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.stories.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.stories.tsx new file mode 100644 index 0000000000000..ab064893ae6fe --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.stories.tsx @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { AlertsSummaryWidgetUI as Component } from './alert_summary_widget_ui'; + +export default { + component: Component, + title: 'app/AlertsSummaryWidgetUI', +}; + +export const Overview = { + args: { + active: 15, + recovered: 53, + timeRange: 'Last 30 days', + }, +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.tsx new file mode 100644 index 0000000000000..e4003e803032d --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/alert_summary_widget_ui.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { euiLightVars } from '@kbn/ui-theme'; +import { EuiFlexGroup, EuiFlexItem, EuiPanel, EuiSpacer, EuiText, EuiTitle } from '@elastic/eui'; +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { AlertsSummaryWidgetUIProps } from './types'; + +export const AlertsSummaryWidgetUI = ({ + active, + recovered, + timeRange, +}: AlertsSummaryWidgetUIProps) => { + return ( + + + + + + +
    + +
    +
    + {!!timeRange && ( + <> + + + {timeRange} + + + )} +
    + + + + + +

    {active + recovered}

    +
    + + + +
    + + + +

    {recovered}

    +
    +
    + + + +
    + + +

    {active}

    +
    + + + +
    +
    +
    +
    +
    +
    +
    + ); +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/index.ts new file mode 100644 index 0000000000000..e1f4ef4d231e7 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { AlertsSummaryWidgetUI } from './alert_summary_widget_ui'; +export { AlertSummaryWidgetError } from './alert_summary_widget_error'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/types.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/types.ts new file mode 100644 index 0000000000000..81437071fcea2 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/components/types.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export interface AlertsSummaryWidgetUIProps { + active: number; + recovered: number; + timeRange: JSX.Element | string; +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/helpers.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/helpers.tsx deleted file mode 100644 index 167c98a678f52..0000000000000 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/helpers.tsx +++ /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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { LIGHT_THEME, XYChartSeriesIdentifier } from '@elastic/charts'; -import { AlertChartData } from './types'; - -export const formatChartAlertData = ( - data: AlertChartData[] -): Array<{ x: number; y: number; g: string }> => - data.map((alert) => ({ - x: alert.date, - y: alert.count, - g: alert.status, - })); - -export const getColorSeries = ({ seriesKeys }: XYChartSeriesIdentifier) => { - switch (seriesKeys[0]) { - case 'active': - return LIGHT_THEME.colors.vizColors[2]; - case 'recovered': - return LIGHT_THEME.colors.vizColors[1]; - case 'total': - return '#f5f7fa'; - default: - return null; - } -}; - -/** - * This function may be passed to `Array.find()` to locate the `P1DT` - * configuration (sub) setting, a string array that contains two entries - * like the following example: `['P1DT', 'YYYY-MM-DD']`. - */ -export const isP1DTFormatterSetting = (formatNameFormatterPair?: string[]) => - Array.isArray(formatNameFormatterPair) && - formatNameFormatterPair[0] === 'P1DT' && - formatNameFormatterPair.length === 2; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/index.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/index.tsx index 80f221f436c49..ede15d4bac294 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/index.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/index.tsx @@ -6,5 +6,4 @@ */ export { RuleAlertsSummary } from './rule_alerts_summary'; -export type { RuleAlertsSummaryProps, AlertChartData, AlertsChartProps } from './types'; -export { formatChartAlertData, getColorSeries } from './helpers'; +export type { RuleAlertsSummaryProps } from './types'; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.test.tsx index 39264020f30a3..019d4f2ba549b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.test.tsx @@ -12,7 +12,6 @@ import { mount, ReactWrapper } from 'enzyme'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; import { ALERTS_FEATURE_ID } from '@kbn/alerting-plugin/common'; import { mockRule } from '../../../../mock/rule_details/alert_summary'; -import { AlertChartData } from './types'; jest.mock('@kbn/kibana-react-plugin/public/ui_settings/use_ui_setting', () => ({ useUiSetting: jest.fn().mockImplementation(() => true), @@ -25,7 +24,6 @@ jest.mock('../../../../hooks/use_load_rule_types', () => ({ jest.mock('../../../../hooks/use_load_rule_alerts_aggregations', () => ({ useLoadRuleAlertsAggs: jest.fn().mockReturnValue({ ruleAlertsAggs: { active: 1, recovered: 7 }, - alertsChartData: mockChartData(), }), })); @@ -80,174 +78,3 @@ describe('Rule Alert Summary', () => { expect(wrapper.find('[data-test-subj="totalAlertsCount"]').text()).toBe('8'); }); }); - -// This function should stay in the same file as the test otherwise the test will fail. -function mockChartData(): AlertChartData[] { - return [ - { - date: 1660608000000, - count: 6, - status: 'recovered', - }, - { - date: 1660694400000, - count: 1, - status: 'recovered', - }, - { - date: 1660694400000, - count: 1, - status: 'active', - }, - { - date: 1658102400000, - count: 6, - status: 'total', - }, - { - date: 1658188800000, - count: 6, - status: 'total', - }, - { - date: 1658275200000, - count: 6, - status: 'total', - }, - { - date: 1658361600000, - count: 6, - status: 'total', - }, - { - date: 1658448000000, - count: 6, - status: 'total', - }, - { - date: 1658534400000, - count: 6, - status: 'total', - }, - { - date: 1658620800000, - count: 6, - status: 'total', - }, - { - date: 1658707200000, - count: 6, - status: 'total', - }, - { - date: 1658793600000, - count: 6, - status: 'total', - }, - { - date: 1658880000000, - count: 6, - status: 'total', - }, - { - date: 1658966400000, - count: 6, - status: 'total', - }, - { - date: 1659052800000, - count: 6, - status: 'total', - }, - { - date: 1659139200000, - count: 6, - status: 'total', - }, - { - date: 1659225600000, - count: 6, - status: 'total', - }, - { - date: 1659312000000, - count: 6, - status: 'total', - }, - { - date: 1659398400000, - count: 6, - status: 'total', - }, - { - date: 1659484800000, - count: 6, - status: 'total', - }, - { - date: 1659571200000, - count: 6, - status: 'total', - }, - { - date: 1659657600000, - count: 6, - status: 'total', - }, - { - date: 1659744000000, - count: 6, - status: 'total', - }, - { - date: 1659830400000, - count: 6, - status: 'total', - }, - { - date: 1659916800000, - count: 6, - status: 'total', - }, - { - date: 1660003200000, - count: 6, - status: 'total', - }, - { - date: 1660089600000, - count: 6, - status: 'total', - }, - { - date: 1660176000000, - count: 6, - status: 'total', - }, - { - date: 1660262400000, - count: 6, - status: 'total', - }, - { - date: 1660348800000, - count: 6, - status: 'total', - }, - { - date: 1660435200000, - count: 6, - status: 'total', - }, - { - date: 1660521600000, - count: 6, - status: 'total', - }, - { - date: 1660694400000, - count: 4, - status: 'total', - }, - ]; -} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.tsx index 708b12ceb7b4a..da43783568658 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/rule_alerts_summary.tsx @@ -5,65 +5,17 @@ * 2.0. */ -import { - BarSeries, - Chart, - FilterPredicate, - LIGHT_THEME, - ScaleType, - Settings, - TooltipType, -} from '@elastic/charts'; -import { - EuiEmptyPrompt, - EuiFlexGroup, - EuiFlexItem, - EuiLoadingSpinner, - EuiPanel, - EuiSpacer, - EuiText, - EuiTitle, -} from '@elastic/eui'; +import { EuiLoadingSpinner } from '@elastic/eui'; import { ALERTS_FEATURE_ID } from '@kbn/alerting-plugin/common'; import { FormattedMessage } from '@kbn/i18n-react'; -import React, { useEffect, useMemo, useState } from 'react'; -import { - EUI_CHARTS_THEME_DARK, - EUI_CHARTS_THEME_LIGHT, - EUI_SPARKLINE_THEME_PARTIAL, -} from '@elastic/eui/dist/eui_charts_theme'; -import { useUiSetting } from '@kbn/kibana-react-plugin/public'; -import moment from 'moment'; +import React, { useEffect, useState } from 'react'; import { useLoadRuleAlertsAggs } from '../../../../hooks/use_load_rule_alerts_aggregations'; import { useLoadRuleTypes } from '../../../../hooks/use_load_rule_types'; -import { formatChartAlertData, getColorSeries } from '.'; import { RuleAlertsSummaryProps } from '.'; -import { isP1DTFormatterSetting } from './helpers'; +import { AlertSummaryWidgetError, AlertsSummaryWidgetUI } from './components'; -const Y_ACCESSORS = ['y']; -const X_ACCESSORS = ['x']; -const G_ACCESSORS = ['g']; -const FALLBACK_DATE_FORMAT_SCALED_P1DT = 'YYYY-MM-DD'; export const RuleAlertsSummary = ({ rule, filteredRuleTypes }: RuleAlertsSummaryProps) => { const [features, setFeatures] = useState(''); - const isDarkMode = useUiSetting('theme:darkMode'); - - const scaledDateFormatPreference = useUiSetting('dateFormat:scaled'); - const maybeP1DTFormatter = Array.isArray(scaledDateFormatPreference) - ? scaledDateFormatPreference.find(isP1DTFormatterSetting) - : null; - const p1dtFormat = - Array.isArray(maybeP1DTFormatter) && maybeP1DTFormatter.length === 2 - ? maybeP1DTFormatter[1] - : FALLBACK_DATE_FORMAT_SCALED_P1DT; - - const theme = useMemo( - () => [ - EUI_SPARKLINE_THEME_PARTIAL, - isDarkMode ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme, - ], - [isDarkMode] - ); const { ruleTypes } = useLoadRuleTypes({ filteredRuleTypes, }); @@ -71,21 +23,10 @@ export const RuleAlertsSummary = ({ rule, filteredRuleTypes }: RuleAlertsSummary ruleAlertsAggs: { active, recovered }, isLoadingRuleAlertsAggs, errorRuleAlertsAggs, - alertsChartData, } = useLoadRuleAlertsAggs({ ruleId: rule.id, features, }); - const chartData = useMemo(() => formatChartAlertData(alertsChartData), [alertsChartData]); - const tooltipSettings = useMemo( - () => ({ - type: TooltipType.VerticalCursor, - headerFormatter: ({ value }: { value: number }) => { - return <>{moment(value).format(p1dtFormat)}; - }, - }), - [p1dtFormat] - ); useEffect(() => { const matchedRuleType = ruleTypes.find((type) => type.id === rule.ruleTypeId); @@ -95,133 +36,18 @@ export const RuleAlertsSummary = ({ rule, filteredRuleTypes }: RuleAlertsSummary }, [rule, ruleTypes]); if (isLoadingRuleAlertsAggs) return ; - if (errorRuleAlertsAggs) - return ( - - - - } - body={ -

    - { - - } -

    - } - /> - ); - const isVisibleFunction: FilterPredicate = (series) => series.splitAccessors.get('g') !== 'total'; + if (errorRuleAlertsAggs) return ; return ( - - - - - - -
    - -
    -
    - - - - -
    - - - - - - - - - -

    {active + recovered}

    -
    -
    -
    - - - - - - -

    {active}

    -
    -
    -
    - - - - - - - -

    {recovered}

    -
    -
    -
    -
    -
    -
    -
    -
    - - - -
    - -
    -
    -
    -
    - - - - - -
    + } + /> ); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/types.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/types.ts index ae4d8696572b0..7ae05d1eaa10e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/types.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/alert_summary/types.ts @@ -11,12 +11,3 @@ export interface RuleAlertsSummaryProps { rule: Rule; filteredRuleTypes: string[]; } -export interface AlertChartData { - status: 'active' | 'recovered' | 'total'; - count: number; - date: number; -} - -export interface AlertsChartProps { - data: AlertChartData[]; -} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.test.tsx index bfe337a1fb880..5eac73c4e87ac 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.test.tsx @@ -419,8 +419,8 @@ describe('tabbed content', () => { tabbedContent.update(); }); - expect(tabbedContent.find('[aria-labelledby="rule_event_log_list"]').exists()).toBeTruthy(); - expect(tabbedContent.find('[aria-labelledby="rule_alert_list"]').exists()).toBeFalsy(); + expect(tabbedContent.find('[aria-labelledby="rule_event_log_list"]').exists()).toBeFalsy(); + expect(tabbedContent.find('[aria-labelledby="rule_alert_list"]').exists()).toBeTruthy(); tabbedContent.find('[data-test-subj="eventLogListTab"]').simulate('click'); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.tsx index 5c44b9161b2c2..db82f36cbc90c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule.tsx @@ -97,6 +97,14 @@ export function RuleComponent({ }; const tabs = [ + { + id: ALERT_LIST_TAB, + name: i18n.translate('xpack.triggersActionsUI.sections.ruleDetails.rule.alertsTabText', { + defaultMessage: 'Alerts', + }), + 'data-test-subj': 'ruleAlertListTab', + content: renderRuleAlertList(), + }, { id: EVENT_LOG_LIST_TAB, name: i18n.translate('xpack.triggersActionsUI.sections.ruleDetails.rule.eventLogTabText', { @@ -118,14 +126,6 @@ export function RuleComponent({ requestRefresh, }), }, - { - id: ALERT_LIST_TAB, - name: i18n.translate('xpack.triggersActionsUI.sections.ruleDetails.rule.alertsTabText', { - defaultMessage: 'Alerts', - }), - 'data-test-subj': 'ruleAlertListTab', - content: renderRuleAlertList(), - }, ]; const renderTabs = () => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.test.tsx new file mode 100644 index 0000000000000..f77494e4f3c12 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.test.tsx @@ -0,0 +1,183 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { act } from 'react-dom/test-utils'; +import { mountWithIntl, nextTick } from '@kbn/test-jest-helpers'; +import { loadExecutionKPIAggregations } from '../../../lib/rule_api/load_execution_kpi_aggregations'; +import { loadGlobalExecutionKPIAggregations } from '../../../lib/rule_api/load_global_execution_kpi_aggregations'; +import { RuleEventLogListKPI } from './rule_event_log_list_kpi'; + +jest.mock('../../../../common/lib/kibana', () => ({ + useKibana: jest.fn().mockReturnValue({ + services: { + notifications: { toast: { addDanger: jest.fn() } }, + }, + }), +})); + +jest.mock('../../../lib/rule_api/load_execution_kpi_aggregations', () => ({ + loadExecutionKPIAggregations: jest.fn(), +})); + +jest.mock('../../../lib/rule_api/load_global_execution_kpi_aggregations', () => ({ + loadGlobalExecutionKPIAggregations: jest.fn(), +})); + +const mockKpiResponse = { + success: 4, + unknown: 10, + failure: 60, + activeAlerts: 100, + newAlerts: 40, + recoveredAlerts: 30, + erroredActions: 60, + triggeredActions: 140, +}; + +const loadExecutionKPIAggregationsMock = + loadExecutionKPIAggregations as unknown as jest.MockedFunction; +const loadGlobalExecutionKPIAggregationsMock = + loadGlobalExecutionKPIAggregations as unknown as jest.MockedFunction; + +describe('rule_event_log_list_kpi', () => { + beforeEach(() => { + jest.clearAllMocks(); + loadExecutionKPIAggregationsMock.mockResolvedValue(mockKpiResponse); + loadGlobalExecutionKPIAggregationsMock.mockResolvedValue(mockKpiResponse); + }); + + it('renders correctly', async () => { + const wrapper = mountWithIntl( + + ); + + expect(wrapper.find('[data-test-subj="centerJustifiedSpinner"]').exists()).toBeTruthy(); + + // Let the load resolve + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(wrapper.find('[data-test-subj="centerJustifiedSpinner"]').exists()).toBeFalsy(); + + expect(loadExecutionKPIAggregationsMock).toHaveBeenCalledWith( + expect.objectContaining({ + id: '123', + message: undefined, + outcomeFilter: undefined, + }) + ); + + expect(loadGlobalExecutionKPIAggregations).not.toHaveBeenCalled(); + + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-successOutcome"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.success}`); + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-unknownOutcome"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.unknown}`); + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-failureOutcome"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.failure}`); + expect( + wrapper.find('[data-test-subj="ruleEventLogKpi-activeAlerts"] .euiStat__title').first().text() + ).toEqual(`${mockKpiResponse.activeAlerts}`); + expect( + wrapper.find('[data-test-subj="ruleEventLogKpi-newAlerts"] .euiStat__title').first().text() + ).toEqual(`${mockKpiResponse.newAlerts}`); + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-recoveredAlerts"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.recoveredAlerts}`); + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-erroredActions"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.erroredActions}`); + expect( + wrapper + .find('[data-test-subj="ruleEventLogKpi-triggeredActions"] .euiStat__title') + .first() + .text() + ).toEqual(`${mockKpiResponse.triggeredActions}`); + }); + + it('calls global KPI API if provided global rule id', async () => { + const wrapper = mountWithIntl( + + ); + // Let the load resolve + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(loadGlobalExecutionKPIAggregations).toHaveBeenCalledWith( + expect.objectContaining({ + id: '*', + message: undefined, + outcomeFilter: undefined, + }) + ); + + expect(loadExecutionKPIAggregationsMock).not.toHaveBeenCalled(); + }); + + it('calls KPI API with filters', async () => { + const wrapper = mountWithIntl( + + ); + + // Let the load resolve + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(loadExecutionKPIAggregationsMock).toHaveBeenCalledWith( + expect.objectContaining({ + id: '123', + message: 'test', + outcomeFilter: ['status: 123', 'test:456'], + }) + ); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.tsx new file mode 100644 index 0000000000000..7fe7dd8fdb029 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_kpi.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useEffect, useState, useMemo, useRef } from 'react'; +import { i18n } from '@kbn/i18n'; +import datemath from '@kbn/datemath'; +import { EuiFlexGroup, EuiFlexItem, EuiPanel, EuiIconTip, EuiStat, EuiSpacer } from '@elastic/eui'; +import { IExecutionKPIResult } from '@kbn/alerting-plugin/common'; +import { + ComponentOpts as RuleApis, + withBulkRuleOperations, +} from '../../common/components/with_bulk_rule_api_operations'; +import { useKibana } from '../../../../common/lib/kibana'; +import { CenterJustifiedSpinner } from '../../../components/center_justified_spinner'; +import { RuleEventLogListStatus } from './rule_event_log_list_status'; + +const getParsedDate = (date: string) => { + if (date.includes('now')) { + return datemath.parse(date)?.format() || date; + } + return date; +}; + +const API_FAILED_MESSAGE = i18n.translate( + 'xpack.triggersActionsUI.sections.ruleDetails.ruleEventLogListKpi.apiError', + { + defaultMessage: 'Failed to fetch event log KPI.', + } +); + +const RESPONSE_TOOLTIP = i18n.translate( + 'xpack.triggersActionsUI.sections.ruleDetails.ruleEventLogListKpi.responseTooltip', + { + defaultMessage: 'The responses for the latest rule runs.', + } +); + +const ALERTS_TOOLTIP = i18n.translate( + 'xpack.triggersActionsUI.sections.ruleDetails.ruleEventLogListKpi.alertsTooltip', + { + defaultMessage: 'The alert statuses for the latest rule runs.', + } +); + +const ACTIONS_TOOLTIP = i18n.translate( + 'xpack.triggersActionsUI.sections.ruleDetails.ruleEventLogListKpi.actionsTooltip', + { + defaultMessage: 'The action statuses for the latest rule runs.', + } +); + +const Stat = ({ + title, + tooltip, + children, +}: { + title: string; + tooltip: string; + children?: JSX.Element; +}) => { + return ( + + + + {title} + + + + + + + {children} + + ); +}; + +export type RuleEventLogListKPIProps = { + ruleId: string; + dateStart: string; + dateEnd: string; + outcomeFilter?: string[]; + message?: string; + refreshToken?: number; +} & Pick; + +export const RuleEventLogListKPI = (props: RuleEventLogListKPIProps) => { + const { + ruleId, + dateStart, + dateEnd, + outcomeFilter, + message, + refreshToken, + loadExecutionKPIAggregations, + loadGlobalExecutionKPIAggregations, + } = props; + const { + notifications: { toasts }, + } = useKibana().services; + + const isInitialized = useRef(false); + + const [isLoading, setIsLoading] = useState(false); + const [kpi, setKpi] = useState(); + + const loadKPIFn = useMemo(() => { + if (ruleId === '*') { + return loadGlobalExecutionKPIAggregations; + } + return loadExecutionKPIAggregations; + }, [ruleId, loadExecutionKPIAggregations, loadGlobalExecutionKPIAggregations]); + + const loadKPIs = async () => { + setIsLoading(true); + try { + const newKpi = await loadKPIFn({ + id: ruleId, + dateStart: getParsedDate(dateStart), + dateEnd: getParsedDate(dateEnd), + outcomeFilter, + message, + }); + setKpi(newKpi); + } catch (e) { + toasts.addDanger({ + title: API_FAILED_MESSAGE, + text: e.body?.message ?? e, + }); + } + setIsLoading(false); + }; + + useEffect(() => { + loadKPIs(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ruleId, dateStart, dateEnd, outcomeFilter, message]); + + useEffect(() => { + if (isInitialized.current) { + loadKPIs(); + } + isInitialized.current = true; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [refreshToken]); + + if (isLoading || !kpi) { + return ; + } + + const getStatDescription = (element: React.ReactNode) => { + return ( + <> + {element} + + + ); + }; + + return ( + + + + + + )} + titleSize="s" + title={kpi.success} + /> + + + )} + titleSize="s" + title={kpi.unknown} + /> + + + )} + titleSize="s" + title={kpi.failure} + /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export const RuleEventLogListKPIWithApi = withBulkRuleOperations(RuleEventLogListKPI); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_table.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_table.tsx index b647442a8eaf0..2c1d6df71fc3d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_table.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rule_details/components/rule_event_log_list_table.tsx @@ -30,9 +30,9 @@ import { RuleEventLogListStatusFilter } from './rule_event_log_list_status_filte import { RuleEventLogDataGrid } from './rule_event_log_data_grid'; import { CenterJustifiedSpinner } from '../../../components/center_justified_spinner'; import { RuleActionErrorLogFlyout } from './rule_action_error_log_flyout'; - import { RefineSearchPrompt } from '../refine_search_prompt'; import { LoadExecutionLogAggregationsProps } from '../../../lib/rule_api'; +import { RuleEventLogListKPIWithApi as RuleEventLogListKPI } from './rule_event_log_list_kpi'; import { ComponentOpts as RuleApis, withBulkRuleOperations, @@ -114,6 +114,9 @@ export const RuleEventLogListTable = ( const [search, setSearch] = useState(''); const [isFlyoutOpen, setIsFlyoutOpen] = useState(false); const [selectedRunLog, setSelectedRunLog] = useState(); + const [internalRefreshToken, setInternalRefreshToken] = useState( + refreshToken + ); // Data grid states const [logs, setLogs] = useState(); @@ -243,6 +246,7 @@ export const RuleEventLogListTable = ( ); const onRefresh = () => { + setInternalRefreshToken(Date.now()); loadEventLogs(); }; @@ -339,6 +343,10 @@ export const RuleEventLogListTable = ( localStorage.setItem(localStorageKey, JSON.stringify(visibleColumns)); }, [localStorageKey, visibleColumns]); + useEffect(() => { + setInternalRefreshToken(refreshToken); + }, [refreshToken]); + return ( <> @@ -371,6 +379,15 @@ export const RuleEventLogListTable = ( + + {renderList()} {isOnLastPage && ( void; onSave: () => void; - setIsLoading: (isLoading: boolean) => void; + setIsSnoozingRule: (isLoading: boolean) => void; + setIsUnsnoozingRule: (isLoading: boolean) => void; onSearchPopulate?: (filter: string) => void; } & BulkOperationsComponentOpts; @@ -43,13 +48,29 @@ const failureMessage = i18n.translate( } ); +const deleteConfirmPlural = (total: number) => + i18n.translate('xpack.triggersActionsUI.sections.rulesList.bulkUnsnoozeConfirmationPlural', { + defaultMessage: 'Unsnooze {total, plural, one {# rule} other {# rules}}? ', + values: { total }, + }); + +const deleteConfirmSingle = (ruleName: string) => + i18n.translate('xpack.triggersActionsUI.sections.rulesList.bulkUnsnoozeConfirmationSingle', { + defaultMessage: 'Unsnooze {ruleName}?', + values: { ruleName }, + }); + export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { const { rulesToSnooze, + rulesToUnsnooze, rulesToSnoozeFilter, + rulesToUnsnoozeFilter, + numberOfSelectedRules = 0, onClose, onSave, - setIsLoading, + setIsSnoozingRule, + setIsUnsnoozingRule, onSearchPopulate, bulkSnoozeRules, bulkUnsnoozeRules, @@ -62,18 +83,18 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { const { showToast } = useBulkEditResponse({ onSearchPopulate }); const isSnoozeModalOpen = useMemo(() => { - if (rulesToSnoozeFilter) { + if (typeof rulesToSnoozeFilter !== 'undefined') { return true; } return rulesToSnooze.length > 0; }, [rulesToSnooze, rulesToSnoozeFilter]); - const isSnoozed = useMemo(() => { - if (rulesToSnoozeFilter) { + const isUnsnoozeModalOpen = useMemo(() => { + if (typeof rulesToUnsnoozeFilter !== 'undefined') { return true; } - return rulesToSnooze.some((item) => isRuleSnoozed(item)); - }, [rulesToSnooze, rulesToSnoozeFilter]); + return rulesToUnsnooze.length > 0; + }, [rulesToUnsnooze, rulesToUnsnoozeFilter]); const interval = useMemo(() => { if (rulesToSnoozeFilter) { @@ -87,7 +108,7 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { const onSnoozeRule = async (schedule: SnoozeSchedule) => { onClose(); - setIsLoading(true); + setIsSnoozingRule(true); try { const response = await bulkSnoozeRules({ ids: rulesToSnooze.map((item) => item.id), @@ -100,18 +121,17 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { title: failureMessage, }); } - setIsLoading(false); + setIsSnoozingRule(false); onSave(); }; - const onUnsnoozeRule = async (scheduleIds?: string[]) => { + const onUnsnoozeRule = async () => { onClose(); - setIsLoading(true); + setIsUnsnoozingRule(true); try { const response = await bulkUnsnoozeRules({ - ids: rulesToSnooze.map((item) => item.id), - filter: rulesToSnoozeFilter, - scheduleIds, + ids: rulesToUnsnooze.map((item) => item.id), + filter: rulesToUnsnoozeFilter, }); showToast(response, 'snooze'); } catch (error) { @@ -119,10 +139,42 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { title: failureMessage, }); } - setIsLoading(false); + setIsUnsnoozingRule(false); onSave(); }; + const confirmationTitle = useMemo(() => { + if (!rulesToUnsnoozeFilter && numberOfSelectedRules === 1 && rulesToUnsnooze[0]) { + return deleteConfirmSingle(rulesToUnsnooze[0].name); + } + return deleteConfirmPlural(numberOfSelectedRules); + }, [rulesToUnsnooze, rulesToUnsnoozeFilter, numberOfSelectedRules]); + + if (isUnsnoozeModalOpen) { + return ( + + ); + } + if (isSnoozeModalOpen) { return ( @@ -138,11 +190,11 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { @@ -153,6 +205,7 @@ export const BulkSnoozeModal = (props: BulkSnoozeModalProps) => { ); } + return null; }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/bulk_snooze_schedule_modal.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/bulk_snooze_schedule_modal.tsx index 56293c01614de..d5a1fd3d62b78 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/bulk_snooze_schedule_modal.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/bulk_snooze_schedule_modal.tsx @@ -5,18 +5,19 @@ * 2.0. */ -import React, { useMemo, useState } from 'react'; +import React, { useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; +import { KueryNode } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { + EuiConfirmModal, EuiModal, EuiModalHeader, + EuiModalHeaderTitle, EuiModalBody, EuiModalFooter, EuiSpacer, EuiButtonEmpty, - EuiModalHeaderTitle, - EuiConfirmModal, } from '@elastic/eui'; import { withBulkRuleOperations, @@ -49,24 +50,30 @@ const deleteConfirmSingle = (ruleName: string) => export type BulkSnoozeScheduleModalProps = { rulesToSchedule: RuleTableItem[]; - rulesToScheduleFilter?: string; + rulesToUnschedule: RuleTableItem[]; + rulesToScheduleFilter?: KueryNode | null | undefined; + rulesToUnscheduleFilter?: KueryNode | null | undefined; numberOfSelectedRules?: number; onClose: () => void; onSave: () => void; - setIsLoading: (isLoading: boolean) => void; + setIsSchedulingRule: (isLoading: boolean) => void; + setIsUnschedulingRule: (isLoading: boolean) => void; onSearchPopulate?: (filter: string) => void; } & BulkOperationsComponentOpts; export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => { const { rulesToSchedule, + rulesToUnschedule, rulesToScheduleFilter, + rulesToUnscheduleFilter, numberOfSelectedRules = 0, onClose, onSave, bulkSnoozeRules, bulkUnsnoozeRules, - setIsLoading, + setIsSchedulingRule, + setIsUnschedulingRule, onSearchPopulate, } = props; @@ -76,18 +83,23 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => const { showToast } = useBulkEditResponse({ onSearchPopulate }); - const [showConfirmation, setShowConfirmation] = useState(false); - const isScheduleModalOpen = useMemo(() => { - if (rulesToScheduleFilter) { + if (typeof rulesToScheduleFilter !== 'undefined') { return true; } return rulesToSchedule.length > 0; }, [rulesToSchedule, rulesToScheduleFilter]); + const isUnscheduleModalOpen = useMemo(() => { + if (typeof rulesToUnscheduleFilter !== 'undefined') { + return true; + } + return rulesToUnschedule.length > 0; + }, [rulesToUnschedule, rulesToUnscheduleFilter]); + const onAddSnoozeSchedule = async (schedule: SnoozeSchedule) => { onClose(); - setIsLoading(true); + setIsSchedulingRule(true); try { const response = await bulkSnoozeRules({ ids: rulesToSchedule.map((item) => item.id), @@ -100,18 +112,17 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => title: failureMessage, }); } - setIsLoading(false); + setIsSchedulingRule(false); onSave(); }; const onRemoveSnoozeSchedule = async () => { - setShowConfirmation(false); onClose(); - setIsLoading(true); + setIsUnschedulingRule(true); try { const response = await bulkUnsnoozeRules({ - ids: rulesToSchedule.map((item) => item.id), - filter: rulesToScheduleFilter, + ids: rulesToUnschedule.map((item) => item.id), + filter: rulesToUnscheduleFilter, scheduleIds: [], }); showToast(response, 'snoozeSchedule'); @@ -120,7 +131,7 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => title: failureMessage, }); } - setIsLoading(false); + setIsUnschedulingRule(false); onSave(); }; @@ -131,14 +142,11 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => return deleteConfirmPlural(numberOfSelectedRules); }, [rulesToSchedule, rulesToScheduleFilter, numberOfSelectedRules]); - if (showConfirmation) { + if (isUnscheduleModalOpen) { return ( { - setShowConfirmation(false); - onClose(); - }} + onCancel={onClose} onConfirm={onRemoveSnoozeSchedule} confirmButtonText={i18n.translate( 'xpack.triggersActionsUI.sections.rulesList.bulkDeleteConfirmButton', @@ -154,6 +162,7 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) => )} buttonColor="danger" defaultFocusedButton="confirm" + data-test-subj="bulkRemoveScheduleConfirmationModal" /> ); } @@ -172,13 +181,12 @@ export const BulkSnoozeScheduleModal = (props: BulkSnoozeScheduleModalProps) =>
    setShowConfirmation(true)} + onCancelSchedules={onRemoveSnoozeSchedule} onClose={() => {}} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.test.tsx index eb432522c1188..6749a062a1a22 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.test.tsx @@ -105,6 +105,9 @@ describe('BaseSnoozePanel', () => { expect(wrapper.find('[data-test-subj="ruleAddSchedule"]').exists()).toBeFalsy(); expect(wrapper.find('[data-test-subj="ruleRemoveAllSchedules"]').exists()).toBeTruthy(); expect(wrapper.find('[data-test-subj="ruleSchedulesListAddButton"]').exists()).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="ruleSchedulesListAddButton"]').first().prop('isDisabled') + ).toBeFalsy(); expect( wrapper @@ -114,4 +117,65 @@ describe('BaseSnoozePanel', () => { .filter((e) => Boolean(e.key)).length ).toEqual(2); }); + test('should disable add snooze schedule button if rule has more than 5 schedules', () => { + const wrapper = mountWithIntl( + + ); + + expect(wrapper.find('[data-test-subj="ruleSchedulesListAddButton"]').exists()).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="ruleSchedulesListAddButton"]').first().prop('isDisabled') + ).toBeTruthy(); + }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.tsx index 2ea8752341ce5..437c75aa3ab2a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/panel/base_snooze_panel.tsx @@ -139,10 +139,14 @@ export const BaseSnoozePanel: React.FunctionComponent = ({ onRemoveAllSchedules(scheduledSnoozes!.filter((s) => s.id).map((s) => s.id as string)); }, [onRemoveAllSchedules, scheduledSnoozes]); - const hasSchedules = useMemo( - () => scheduledSnoozes && scheduledSnoozes.filter((s) => Boolean(s.id)).length > 0, - [scheduledSnoozes] - ); + const numberOfSchedules = useMemo(() => { + if (!scheduledSnoozes) { + return 0; + } + return scheduledSnoozes.filter((s) => Boolean(s.id)).length; + }, [scheduledSnoozes]); + + const hasSchedules = useMemo(() => numberOfSchedules > 0, [numberOfSchedules]); const renderSchedule = () => { if (!showAddSchedule) { @@ -236,6 +240,7 @@ export const BaseSnoozePanel: React.FunctionComponent = ({ = 5} data-test-subj="ruleSchedulesListAddButton" iconType="plusInCircleFilled" onClick={onClickAddSchedule} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/scheduler.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/scheduler.tsx index 179a92b6c7e8e..4b559e262424d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/scheduler.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rule_snooze/scheduler.tsx @@ -368,7 +368,7 @@ const RuleSnoozeSchedulerPanel: React.FunctionComponent = ({ {i18n.translate('xpack.triggersActionsUI.sections.rulesList.deleteSchedule', { - defaultMessage: 'Delete schedules', + defaultMessage: 'Delete schedule', })} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.test.tsx index 3bde062935a86..6bfe953e28696 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.test.tsx @@ -80,8 +80,14 @@ jest.mock('../../../../common/get_experimental_features', () => ({ const ruleTags = ['a', 'b', 'c', 'd']; -const { loadRuleTypes, updateAPIKey, loadRuleTags, bulkSnoozeRules, bulkUpdateAPIKey } = - jest.requireMock('../../../lib/rule_api'); +const { + loadRuleTypes, + updateAPIKey, + loadRuleTags, + bulkSnoozeRules, + bulkUnsnoozeRules, + bulkUpdateAPIKey, +} = jest.requireMock('../../../lib/rule_api'); const { loadRuleAggregationsWithKueryFilter } = jest.requireMock( '../../../lib/rule_api/aggregate_kuery_filter' ); @@ -1994,6 +2000,33 @@ describe.skip('Rules list bulk actions', () => { ); }); + it('can bulk unsnooze', async () => { + await setup(); + wrapper.find('[data-test-subj="checkboxSelectRow-1"]').at(1).simulate('change'); + wrapper.find('[data-test-subj="selectAllRulesButton"]').at(1).simulate('click'); + wrapper.find('[data-test-subj="showBulkActionButton"]').first().simulate('click'); + + // Unselect something to test filtering + wrapper.find('[data-test-subj="checkboxSelectRow-2"]').at(1).simulate('change'); + + wrapper.find('[data-test-subj="bulkUnsnooze"]').first().simulate('click'); + + expect(wrapper.find('[data-test-subj="bulkUnsnoozeConfirmationModal"]').exists()).toBeTruthy(); + wrapper.find('[data-test-subj="confirmModalConfirmButton"]').first().simulate('click'); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(bulkUnsnoozeRules).toHaveBeenCalledWith( + expect.objectContaining({ + ids: [], + filter: 'NOT (alert.id: "alert:2")', + }) + ); + }); + it('can bulk add snooze schedule', async () => { await setup(); wrapper.find('[data-test-subj="checkboxSelectRow-1"]').at(1).simulate('change'); @@ -2020,6 +2053,36 @@ describe.skip('Rules list bulk actions', () => { ); }); + it('can bulk remove snooze schedule', async () => { + await setup(); + wrapper.find('[data-test-subj="checkboxSelectRow-1"]').at(1).simulate('change'); + wrapper.find('[data-test-subj="selectAllRulesButton"]').at(1).simulate('click'); + wrapper.find('[data-test-subj="showBulkActionButton"]').first().simulate('click'); + + // Unselect something to test filtering + wrapper.find('[data-test-subj="checkboxSelectRow-2"]').at(1).simulate('change'); + + wrapper.find('[data-test-subj="bulkRemoveSnoozeSchedule"]').first().simulate('click'); + + expect( + wrapper.find('[data-test-subj="bulkRemoveScheduleConfirmationModal"]').exists() + ).toBeTruthy(); + wrapper.find('[data-test-subj="confirmModalConfirmButton"]').first().simulate('click'); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(bulkUnsnoozeRules).toHaveBeenCalledWith( + expect.objectContaining({ + ids: [], + filter: 'NOT (alert.id: "alert:2")', + scheduleIds: [], + }) + ); + }); + it('can bulk update API key', async () => { await setup(); wrapper.find('[data-test-subj="checkboxSelectRow-1"]').at(1).simulate('change'); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.tsx index a725a0e916c19..a06958fb3072e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/rules_list/components/rules_list.tsx @@ -10,6 +10,7 @@ import { i18n } from '@kbn/i18n'; import moment from 'moment'; import { capitalize, isEmpty, sortBy } from 'lodash'; +import { KueryNode } from '@kbn/es-query'; import { FormattedMessage } from '@kbn/i18n-react'; import React, { useEffect, useState, ReactNode, useCallback, useMemo } from 'react'; import { @@ -206,17 +207,36 @@ export const RulesList = ({ const [rulesToDelete, setRulesToDelete] = useState([]); + // TODO - tech debt: Right now we're using null and undefined to determine if we should + // render the bulk edit modal. Refactor this to only keep track of 1 set of rules and types + // to determine which modal to show const [rulesToSnooze, setRulesToSnooze] = useState([]); - const [rulesToSnoozeFilter, setRulesToSnoozeFilter] = useState(''); + const [rulesToSnoozeFilter, setRulesToSnoozeFilter] = useState(); + + const [rulesToUnsnooze, setRulesToUnsnooze] = useState([]); + const [rulesToUnsnoozeFilter, setRulesToUnsnoozeFilter] = useState< + KueryNode | null | undefined + >(); const [rulesToSchedule, setRulesToSchedule] = useState([]); - const [rulesToScheduleFilter, setRulesToScheduleFilter] = useState(''); + const [rulesToScheduleFilter, setRulesToScheduleFilter] = useState< + KueryNode | null | undefined + >(); + + const [rulesToUnschedule, setRulesToUnschedule] = useState([]); + const [rulesToUnscheduleFilter, setRulesToUnscheduleFilter] = useState< + KueryNode | null | undefined + >(); const [rulesToUpdateAPIKey, setRulesToUpdateAPIKey] = useState([]); - const [rulesToUpdateAPIKeyFilter, setRulesToUpdateAPIKeyFilter] = useState(''); + const [rulesToUpdateAPIKeyFilter, setRulesToUpdateAPIKeyFilter] = useState< + KueryNode | null | undefined + >(); const [isSnoozingRules, setIsSnoozingRules] = useState(false); const [isSchedulingRules, setIsSchedulingRules] = useState(false); + const [isUnsnoozingRules, setIsUnsnoozingRules] = useState(false); + const [isUnschedulingRules, setIsUnschedulingRules] = useState(false); const [isUpdatingRuleAPIKeys, setIsUpdatingRuleAPIKeys] = useState(false); const hasAnyAuthorizedRuleType = useMemo(() => { @@ -578,6 +598,12 @@ export const RulesList = ({ } = useBulkEditSelect({ totalItemCount: rulesState.totalItemCount, items: tableItems, + searchText, + typesFilter: rulesTypesFilter, + actionTypesFilter, + ruleExecutionStatusesFilter, + ruleStatusesFilter, + tagsFilter, }); const authorizedToModifySelectedRules = useMemo(() => { @@ -594,17 +620,27 @@ export const RulesList = ({ const clearRulesToSnooze = () => { setRulesToSnooze([]); - setRulesToSnoozeFilter(''); + setRulesToSnoozeFilter(undefined); + }; + + const clearRulesToUnsnooze = () => { + setRulesToUnsnooze([]); + setRulesToUnsnoozeFilter(undefined); }; const clearRulesToSchedule = () => { setRulesToSchedule([]); - setRulesToScheduleFilter(''); + setRulesToScheduleFilter(undefined); + }; + + const clearRulesToUnschedule = () => { + setRulesToUnschedule([]); + setRulesToUnscheduleFilter(undefined); }; const clearRulesToUpdateAPIKey = () => { setRulesToUpdateAPIKey([]); - setRulesToUpdateAPIKeyFilter(''); + setRulesToUpdateAPIKeyFilter(undefined); }; const isRulesTableLoading = useMemo(() => { @@ -613,7 +649,9 @@ export const RulesList = ({ ruleTypesState.isLoading || isPerformingAction || isSnoozingRules || + isUnsnoozingRules || isSchedulingRules || + isUnschedulingRules || isUpdatingRuleAPIKeys ); }, [ @@ -621,7 +659,9 @@ export const RulesList = ({ ruleTypesState, isPerformingAction, isSnoozingRules, + isUnsnoozingRules, isSchedulingRules, + isUnschedulingRules, isUpdatingRuleAPIKeys, ]); @@ -903,14 +943,20 @@ export const RulesList = ({ setIsPerformingAction(false); }} isSnoozingRules={isSnoozingRules} + isUnsnoozingRules={isUnsnoozingRules} isSchedulingRules={isSchedulingRules} + isUnschedulingRules={isUnschedulingRules} isUpdatingRuleAPIKeys={isUpdatingRuleAPIKeys} setRulesToDelete={setRulesToDelete} setRulesToUpdateAPIKey={setRulesToUpdateAPIKey} setRulesToSnooze={setRulesToSnooze} + setRulesToUnsnooze={setRulesToUnsnooze} setRulesToSchedule={setRulesToSchedule} + setRulesToUnschedule={setRulesToUnschedule} setRulesToSnoozeFilter={setRulesToSnoozeFilter} + setRulesToUnsnoozeFilter={setRulesToUnsnoozeFilter} setRulesToScheduleFilter={setRulesToScheduleFilter} + setRulesToUnscheduleFilter={setRulesToUnscheduleFilter} setRulesToUpdateAPIKeyFilter={setRulesToUpdateAPIKeyFilter} /> @@ -983,13 +1029,19 @@ export const RulesList = ({ /> { clearRulesToSnooze(); + clearRulesToUnsnooze(); }} onSave={async () => { clearRulesToSnooze(); + clearRulesToUnsnooze(); onClearSelection(); await loadData(); }} @@ -997,14 +1049,19 @@ export const RulesList = ({ /> { clearRulesToSchedule(); + clearRulesToUnschedule(); }} onSave={async () => { clearRulesToSchedule(); + clearRulesToUnschedule(); onClearSelection(); await loadData(); }} diff --git a/x-pack/plugins/triggers_actions_ui/public/common/index.ts b/x-pack/plugins/triggers_actions_ui/public/common/index.ts index fd43a6baf3f05..67677fa83b51d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/common/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/common/index.ts @@ -21,7 +21,8 @@ export { builtInAggregationTypes, builtInGroupByTypes, } from './constants'; +export { connectorDeprecatedMessage, deprecatedMessage } from './connectors_selection'; export type { IOption } from './index_controls'; export { getFields, getIndexOptions, firstFieldOption } from './index_controls'; -export { getTimeFieldOptions } from './lib'; +export { getTimeFieldOptions, useKibana } from './lib'; export type { Comparator, AggregationType, GroupByType, RuleStatus } from './types'; diff --git a/x-pack/plugins/triggers_actions_ui/public/common/lib/index.ts b/x-pack/plugins/triggers_actions_ui/public/common/lib/index.ts index c8f7a6e468595..f7af1fbbde257 100644 --- a/x-pack/plugins/triggers_actions_ui/public/common/lib/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/common/lib/index.ts @@ -6,3 +6,4 @@ */ export { getTimeFieldOptions, getTimeOptions } from './get_time_options'; +export { useKibana } from './kibana'; diff --git a/x-pack/plugins/triggers_actions_ui/public/index.ts b/x-pack/plugins/triggers_actions_ui/public/index.ts index 12f45dcc31e41..7500a66b70f16 100644 --- a/x-pack/plugins/triggers_actions_ui/public/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/index.ts @@ -43,12 +43,51 @@ export type { RulesListVisibleColumns, } from './types'; +export type { + ActionConnectorFieldsProps, + ActionParamsProps, + ActionTypeModel, + GenericValidationResult, +} from './types'; + +export { + AlertHistoryDefaultIndexName, + ALERT_HISTORY_PREFIX, + AlertHistoryDocumentTemplate, + AlertHistoryEsIndexConnectorId, +} from './types'; + +export { useConnectorContext } from './application/context/use_connector_context'; + export { ActionForm, CreateConnectorFlyout, EditConnectorFlyout, } from './application/sections/action_connector_form'; +export type { ConnectorFormSchema } from './application/sections/action_connector_form'; + +export type { ConfigFieldSchema, SecretsFieldSchema } from './application/components'; + +export { + ButtonGroupField, + HiddenField, + JsonEditorWithMessageVariables, + JsonFieldWrapper, + MustacheTextFieldWrapper, + PasswordField, + SimpleConnectorForm, + TextAreaWithMessageVariables, + TextFieldWithMessageVariables, +} from './application/components'; + +export { + AlertProvidedActionVariables, + hasMustacheTokens, + templateActionVariable, + updateActionConnector, +} from './application/lib'; + export type { ActionGroupWithCondition } from './application/sections'; export { AlertConditions, AlertConditionsGroup } from './application/sections'; @@ -57,6 +96,7 @@ export function plugin(context: PluginInitializerContext) { return new Plugin(context); } +export { useKibana } from './common'; export type { AggregationType, Comparator } from './common'; export { @@ -74,6 +114,8 @@ export { getTimeFieldOptions, GroupByExpression, COMPARATORS, + connectorDeprecatedMessage, + deprecatedMessage, } from './common'; export type { diff --git a/x-pack/plugins/triggers_actions_ui/public/mocks.ts b/x-pack/plugins/triggers_actions_ui/public/mocks.ts index b44ef00c5f425..02722bc0ee73b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/mocks.ts +++ b/x-pack/plugins/triggers_actions_ui/public/mocks.ts @@ -5,14 +5,12 @@ * 2.0. */ -import type { ValidatedEmail } from '@kbn/actions-plugin/common'; import type { TriggersAndActionsUIPublicPluginStart } from './plugin'; import { getAddConnectorFlyoutLazy } from './common/get_add_connector_flyout'; import { getEditConnectorFlyoutLazy } from './common/get_edit_connector_flyout'; import { getAddAlertFlyoutLazy } from './common/get_add_alert_flyout'; import { getEditAlertFlyoutLazy } from './common/get_edit_alert_flyout'; -import { RegistrationServices } from './application/components/builtin_action_types'; import { TypeRegistry } from './application/type_registry'; import { ActionTypeModel, @@ -132,9 +130,3 @@ function createStartMock(): TriggersAndActionsUIPublicPluginStart { export const triggersActionsUiMock = { createStart: createStartMock, }; - -function validateEmailAddresses(addresses: string[]): ValidatedEmail[] { - return addresses.map((address) => ({ address, valid: true })); -} - -export const registrationServicesMock: RegistrationServices = { validateEmailAddresses }; diff --git a/x-pack/plugins/triggers_actions_ui/public/plugin.ts b/x-pack/plugins/triggers_actions_ui/public/plugin.ts index 5cc4dbb0ece86..10c5e5637f159 100644 --- a/x-pack/plugins/triggers_actions_ui/public/plugin.ts +++ b/x-pack/plugins/triggers_actions_ui/public/plugin.ts @@ -23,7 +23,6 @@ import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; import { Storage } from '@kbn/kibana-utils-plugin/public'; import type { SpacesPluginStart } from '@kbn/spaces-plugin/public'; import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; -import { registerBuiltInActionTypes } from './application/components/builtin_action_types'; import { TypeRegistry } from './application/type_registry'; import { getAddConnectorFlyoutLazy } from './common/get_add_connector_flyout'; @@ -248,13 +247,6 @@ export class Plugin }, }); - registerBuiltInActionTypes({ - actionTypeRegistry: this.actionTypeRegistry, - services: { - validateEmailAddresses: plugins.actions.validateEmailAddresses, - }, - }); - if (this.experimentalFeatures.internalAlertsTable) { registerAlertsTableConfiguration({ alertsTableConfigurationRegistry: this.alertsTableConfigurationRegistry, diff --git a/x-pack/plugins/triggers_actions_ui/tsconfig.json b/x-pack/plugins/triggers_actions_ui/tsconfig.json index 991cbc5b01216..8618be6c9c285 100644 --- a/x-pack/plugins/triggers_actions_ui/tsconfig.json +++ b/x-pack/plugins/triggers_actions_ui/tsconfig.json @@ -16,7 +16,6 @@ "references": [ { "path": "../../../src/core/tsconfig.json" }, { "path": "../alerting/tsconfig.json" }, - { "path": "../stack_connectors/tsconfig.json" }, { "path": "../features/tsconfig.json" }, { "path": "../rule_registry/tsconfig.json" }, { "path": "../../../src/plugins/data/tsconfig.json" }, diff --git a/x-pack/test/accessibility/apps/graph.ts b/x-pack/test/accessibility/apps/graph.ts index d13ed5a58f871..03ca3b2afbfe4 100644 --- a/x-pack/test/accessibility/apps/graph.ts +++ b/x-pack/test/accessibility/apps/graph.ts @@ -63,12 +63,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await testSubjects.click('saveCancelButton'); }); - it('Graph inspect panel', async function () { - await testSubjects.click('graphInspectButton'); - await a11y.testAppSnapshot(); - await testSubjects.click('graphInspectButton'); - }); - it('Graph settings - advanced settings tab', async function () { await testSubjects.click('graphSettingsButton'); await a11y.testAppSnapshot(); @@ -85,12 +79,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await browser.pressKeys(browser.keys.ESCAPE); }); - // https://github.com/elastic/kibana/issues/134693 - it.skip('Graph settings drilldown tab - add new drilldown', async function () { + it('Graph settings drilldown tab - add new drilldown', async function () { + await testSubjects.click('graphSettingsButton'); + await testSubjects.click('drillDowns'); await testSubjects.click('graphAddNewTemplate'); await a11y.testAppSnapshot(); - await testSubjects.click('graphRemoveUrlTemplate'); - await testSubjects.click('euiFlyoutCloseButton'); await browser.pressKeys(browser.keys.ESCAPE); }); diff --git a/x-pack/test/accessibility/apps/observability.ts b/x-pack/test/accessibility/apps/observability.ts new file mode 100644 index 0000000000000..ee3e3a61a0ba6 --- /dev/null +++ b/x-pack/test/accessibility/apps/observability.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +// a11y tests for spaces, space selection and space creation and feature controls + +import { describe } from 'mocha'; +import { FtrProviderContext } from '../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const PageObjects = getPageObjects(['common', 'infraHome']); + const observability = getService('observability'); + const a11y = getService('a11y'); + const retry = getService('retry'); + const testSubjects = getService('testSubjects'); + const esArchiver = getService('esArchiver'); + + // https://github.com/elastic/kibana/issues/141724 + describe.skip('Observability UI', () => { + before(async () => { + await esArchiver.load('x-pack/test/functional/es_archives/infra/metrics_and_logs'); + await PageObjects.common.navigateToApp('observability'); + }); + + describe('Overview', async () => { + before(async () => { + await observability.overview.common.openAlertsSectionAndWaitToAppear(); + await a11y.testAppSnapshot(); + }); + it('Guided Setup', async () => { + await PageObjects.infraHome.clickGuidedSetupButton(); + await retry.waitFor('Guided setup header to be visible', async () => { + return await testSubjects.isDisplayed('statusVisualizationFlyoutTitle'); + }); + await a11y.testAppSnapshot(); + }); + }); + }); +} diff --git a/x-pack/test/accessibility/config.ts b/x-pack/test/accessibility/config.ts index be4fe6c531bed..524608b130779 100644 --- a/x-pack/test/accessibility/config.ts +++ b/x-pack/test/accessibility/config.ts @@ -54,6 +54,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { require.resolve('./apps/stack_monitoring'), require.resolve('./apps/watcher'), require.resolve('./apps/rollup_jobs'), + require.resolve('./apps/observability'), ], pageObjects, diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/server/alert_types.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/server/alert_types.ts index 3d68c420e4442..068c516618616 100644 --- a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/server/alert_types.ts +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/server/alert_types.ts @@ -109,31 +109,21 @@ async function alwaysFiringExecutor(alertExecutorOptions: any) { rule, } = alertExecutorOptions; let group: string | null = 'default'; - let subgroup: string | null = null; const alertInfo = { alertId, spaceId, namespace, name, tags, createdBy, updatedBy, ...rule }; if (params.groupsToScheduleActionsInSeries) { const index = state.groupInSeriesIndex || 0; - const [scheduledGroup, scheduledSubgroup] = ( - params.groupsToScheduleActionsInSeries[index] ?? '' - ).split(':'); + const [scheduledGroup] = (params.groupsToScheduleActionsInSeries[index] ?? '').split(':'); group = scheduledGroup; - subgroup = scheduledSubgroup; } if (group) { const instance = services.alertFactory.create('1').replaceState({ instanceStateValue: true }); - if (subgroup) { - instance.scheduleActionsWithSubGroup(group, subgroup, { - instanceContextValue: true, - }); - } else { - instance.scheduleActions(group, { - instanceContextValue: true, - }); - } + instance.scheduleActions(group, { + instanceContextValue: true, + }); } await services.scopedClusterClient.asCurrentUser.index({ @@ -506,9 +496,7 @@ function getPatternFiringAlertType() { deep: DeepContextVariables, }); } else if (typeof scheduleByPattern === 'string') { - services.alertFactory - .create(instanceId) - .scheduleActionsWithSubGroup('default', scheduleByPattern); + services.alertFactory.create(instanceId).scheduleActions('default', scheduleByPattern); } } diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/alerts.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/alerts.ts index 63c70e93ea194..8f1b8047e4331 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/alerts.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/alerts.ts @@ -953,82 +953,6 @@ instanceStateValue: true } }); - it('should not throttle when changing subgroups', async () => { - const testStart = new Date(); - const reference = alertUtils.generateReference(); - const response = await alertUtils.createAlwaysFiringAction({ - reference, - overwrites: { - schedule: { interval: '1s' }, - params: { - index: ES_TEST_INDEX_NAME, - reference, - groupsToScheduleActionsInSeries: ['default:prev', 'default:next'], - }, - actions: [ - { - group: 'default', - id: indexRecordActionId, - params: { - index: ES_TEST_INDEX_NAME, - reference, - message: 'from:{{alertActionGroup}}:{{alertActionSubgroup}}', - }, - }, - ], - }, - }); - - switch (scenario.id) { - case 'no_kibana_privileges at space1': - case 'space_1_all at space2': - case 'global_read at space1': - expect(response.statusCode).to.eql(403); - expect(response.body).to.eql({ - error: 'Forbidden', - message: getConsumerUnauthorizedErrorMessage( - 'create', - 'test.always-firing', - 'alertsFixture' - ), - statusCode: 403, - }); - break; - case 'space_1_all_alerts_none_actions at space1': - expect(response.statusCode).to.eql(403); - expect(response.body).to.eql({ - error: 'Forbidden', - message: `Unauthorized to get actions`, - statusCode: 403, - }); - break; - case 'space_1_all at space1': - case 'space_1_all_with_restricted_fixture at space1': - case 'superuser at space1': - expect(response.statusCode).to.eql(200); - // Wait for actions to execute twice before disabling the alert and waiting for tasks to finish - await esTestIndexTool.waitForDocs('action:test.index-record', reference, 2); - await alertUtils.disable(response.body.id); - await taskManagerUtils.waitForDisabled(response.body.id, testStart); - - // Ensure only 2 actions with proper params exists - const searchResult = await esTestIndexTool.search( - 'action:test.index-record', - reference - ); - // @ts-expect-error doesnt handle total: number - expect(searchResult.body.hits.total.value).to.eql(2); - const messages: string[] = searchResult.body.hits.hits.map( - // @ts-expect-error _source: unknown - (hit: { _source: { params: { message: string } } }) => hit._source.params.message - ); - expect(messages.sort()).to.eql(['from:default:next', 'from:default:prev']); - break; - default: - throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); - } - }); - it('should reset throttle window when not firing', async () => { const testStart = new Date(); const reference = alertUtils.generateReference(); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_global_execution_kpi.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_global_execution_kpi.ts new file mode 100644 index 0000000000000..133cca59f9472 --- /dev/null +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_global_execution_kpi.ts @@ -0,0 +1,162 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { UserAtSpaceScenarios } from '../../../scenarios'; +import { getUrlPrefix, getTestRuleData, ObjectRemover, getEventLog } from '../../../../common/lib'; +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function getGlobalExecutionKpiTests({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const supertestWithoutAuth = getService('supertestWithoutAuth'); + + const retry = getService('retry'); + + describe('getGlobalExecutionKpi', () => { + const objectRemover = new ObjectRemover(supertest); + + after(() => objectRemover.removeAll()); + + it('should return KPI only from the current space', async () => { + const startTime = new Date().toISOString(); + + const spaceId = UserAtSpaceScenarios[1].space.id; + const user = UserAtSpaceScenarios[1].user; + const response = await supertest + .post(`${getUrlPrefix(spaceId)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + rule_type_id: 'test.noop', + schedule: { interval: '1s' }, + throttle: null, + }) + ); + + expect(response.status).to.eql(200); + const ruleId = response.body.id; + objectRemover.add(spaceId, ruleId, 'rule', 'alerting'); + + const response2 = await supertest + .post(`${getUrlPrefix(spaceId)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + rule_type_id: 'test.noop', + schedule: { interval: '1s' }, + throttle: null, + }) + ); + + expect(response2.status).to.eql(200); + const ruleId2 = response2.body.id; + objectRemover.add(spaceId, ruleId2, 'rule', 'alerting'); + + await retry.try(async () => { + // break AAD + await supertest + .put(`${getUrlPrefix(spaceId)}/api/alerts_fixture/saved_object/alert/${ruleId2}`) + .set('kbn-xsrf', 'foo') + .send({ + attributes: { + name: 'bar', + }, + }) + .expect(200); + }); + + await retry.try(async () => { + // there can be a successful execute before the error one + const someEvents = await getEventLog({ + getService, + spaceId, + type: 'alert', + id: ruleId2, + provider: 'alerting', + actions: new Map([['execute', { gte: 1 }]]), + }); + const errorEvents = someEvents.filter( + (event) => event?.kibana?.alerting?.status === 'error' + ); + expect(errorEvents.length).to.be.above(0); + }); + + await retry.try(async () => { + // there can be a successful execute before the error one + const logResponse = await supertestWithoutAuth + .get( + `${getUrlPrefix( + spaceId + )}/internal/alerting/_global_execution_logs?date_start=${startTime}&date_end=9999-12-31T23:59:59Z&per_page=50&page=1` + ) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + expect(logResponse.statusCode).to.be(200); + expect(logResponse.body.data.length).to.be.above(1); + }); + + await retry.try(async () => { + // break AAD + await supertest + .put(`${getUrlPrefix(spaceId)}/api/alerts_fixture/saved_object/alert/${ruleId}`) + .set('kbn-xsrf', 'foo') + .send({ + attributes: { + name: 'bar', + }, + }) + .expect(200); + }); + + await retry.try(async () => { + // there can be a successful execute before the error one + const someEvents = await getEventLog({ + getService, + spaceId, + type: 'alert', + id: ruleId, + provider: 'alerting', + actions: new Map([['execute', { gte: 1 }]]), + }); + const errorEvents = someEvents.filter( + (event) => event?.kibana?.alerting?.status === 'error' + ); + expect(errorEvents.length).to.be.above(0); + }); + + const kpiLogs = await retry.try(async () => { + // there can be a successful execute before the error one + const logResponse = await supertestWithoutAuth + .get( + `${getUrlPrefix( + spaceId + )}/internal/alerting/_global_execution_kpi?date_start=${startTime}&date_end=9999-12-31T23:59:59Z` + ) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + expect(logResponse.statusCode).to.be(200); + + return logResponse.body; + }); + + expect(Object.keys(kpiLogs)).to.eql([ + 'success', + 'unknown', + 'failure', + 'activeAlerts', + 'newAlerts', + 'recoveredAlerts', + 'erroredActions', + 'triggeredActions', + ]); + // it should be above 1 since we have two rule running + expect(kpiLogs.success).to.be.above(1); + expect(kpiLogs.failure).to.be.above(0); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_rule_execution_kpi.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_rule_execution_kpi.ts new file mode 100644 index 0000000000000..2303fc616d8dc --- /dev/null +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/get_rule_execution_kpi.ts @@ -0,0 +1,133 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { UserAtSpaceScenarios } from '../../../scenarios'; +import { getUrlPrefix, getTestRuleData, ObjectRemover, getEventLog } from '../../../../common/lib'; +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function getRuleExecutionKpiTests({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const supertestWithoutAuth = getService('supertestWithoutAuth'); + + const retry = getService('retry'); + + describe('getRuleExecutionKpi', () => { + const objectRemover = new ObjectRemover(supertest); + + after(() => objectRemover.removeAll()); + + it('should return KPI only from the current space', async () => { + const startTime = new Date().toISOString(); + + const spaceId = UserAtSpaceScenarios[1].space.id; + const user = UserAtSpaceScenarios[1].user; + const response = await supertest + .post(`${getUrlPrefix(spaceId)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + rule_type_id: 'test.noop', + schedule: { interval: '1s' }, + throttle: null, + }) + ); + + expect(response.status).to.eql(200); + const ruleId = response.body.id; + objectRemover.add(spaceId, ruleId, 'rule', 'alerting'); + + const spaceId2 = UserAtSpaceScenarios[4].space.id; + const response2 = await supertest + .post(`${getUrlPrefix(spaceId2)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + rule_type_id: 'test.noop', + schedule: { interval: '1s' }, + throttle: null, + }) + ); + + expect(response2.status).to.eql(200); + const ruleId2 = response2.body.id; + objectRemover.add(spaceId2, ruleId2, 'rule', 'alerting'); + + await retry.try(async () => { + // there can be a successful execute before the error one + const someEvents = await getEventLog({ + getService, + spaceId, + type: 'alert', + id: ruleId, + provider: 'alerting', + actions: new Map([['execute', { gte: 1 }]]), + }); + + expect(someEvents.length).to.be.above(0); + }); + + await retry.try(async () => { + // break AAD + await supertest + .put(`${getUrlPrefix(spaceId)}/api/alerts_fixture/saved_object/alert/${ruleId}`) + .set('kbn-xsrf', 'foo') + .send({ + attributes: { + name: 'bar', + }, + }) + .expect(200); + }); + + await retry.try(async () => { + // there can be a successful execute before the error one + const someEvents = await getEventLog({ + getService, + spaceId, + type: 'alert', + id: ruleId, + provider: 'alerting', + actions: new Map([['execute', { gte: 1 }]]), + }); + const errorEvents = someEvents.filter( + (event) => event?.kibana?.alerting?.status === 'error' + ); + expect(errorEvents.length).to.be.above(0); + }); + + const kpiLogs = await retry.try(async () => { + // there can be a successful execute before the error one + const logResponse = await supertestWithoutAuth + .get( + `${getUrlPrefix( + spaceId + )}/internal/alerting/rule/${ruleId}/_execution_kpi?date_start=${startTime}&date_end=9999-12-31T23:59:59Z` + ) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + expect(logResponse.statusCode).to.be(200); + + return logResponse.body; + }); + + expect(Object.keys(kpiLogs)).to.eql([ + 'success', + 'unknown', + 'failure', + 'activeAlerts', + 'newAlerts', + 'recoveredAlerts', + 'erroredActions', + 'triggeredActions', + ]); + expect(kpiLogs.success).to.be.above(0); + expect(kpiLogs.failure).to.be.above(0); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/event_log.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/event_log.ts index 206036ef7fcac..2e63bed197864 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/event_log.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/event_log.ts @@ -6,7 +6,6 @@ */ import expect from '@kbn/expect'; -import uuid from 'uuid'; import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server'; import { Spaces } from '../../scenarios'; import { @@ -447,237 +446,6 @@ export default function eventLogTests({ getService }: FtrProviderContext) { } }); - it('should generate expected events for normal operation with subgroups', async () => { - const { body: createdAction } = await supertest - .post(`${getUrlPrefix(space.id)}/api/actions/connector`) - .set('kbn-xsrf', 'foo') - .send({ - name: 'MY action', - connector_type_id: 'test.noop', - config: {}, - secrets: {}, - }) - .expect(200); - - // pattern of when the alert should fire - const [firstSubgroup, secondSubgroup] = [uuid.v4(), uuid.v4()]; - const pattern = { - instance: [false, firstSubgroup, secondSubgroup], - }; - - const response = await supertest - .post(`${getUrlPrefix(space.id)}/api/alerting/rule`) - .set('kbn-xsrf', 'foo') - .send( - getTestRuleData({ - rule_type_id: 'test.patternFiring', - schedule: { interval: '1s' }, - throttle: null, - params: { - pattern, - }, - actions: [ - { - id: createdAction.id, - group: 'default', - params: {}, - }, - ], - }) - ); - - expect(response.status).to.eql(200); - const alertId = response.body.id; - objectRemover.add(space.id, alertId, 'rule', 'alerting'); - - // get the events we're expecting - const events = await retry.try(async () => { - return await getEventLog({ - getService, - spaceId: space.id, - type: 'alert', - id: alertId, - provider: 'alerting', - actions: new Map([ - // make sure the counts of the # of events per type are as expected - ['execute-start', { gte: 4 }], - ['execute', { gte: 4 }], - ['execute-action', { equal: 2 }], - ['new-instance', { equal: 1 }], - ['active-instance', { gte: 2 }], - ['recovered-instance', { equal: 1 }], - ]), - }); - }); - - const executeEvents = getEventsByAction(events, 'execute'); - const executeStartEvents = getEventsByAction(events, 'execute-start'); - const newInstanceEvents = getEventsByAction(events, 'new-instance'); - const recoveredInstanceEvents = getEventsByAction(events, 'recovered-instance'); - - // make sure the events are in the right temporal order - const executeTimes = getTimestamps(executeEvents); - const executeStartTimes = getTimestamps(executeStartEvents); - const newInstanceTimes = getTimestamps(newInstanceEvents); - const recoveredInstanceTimes = getTimestamps(recoveredInstanceEvents); - - expect(executeTimes[0] < newInstanceTimes[0]).to.be(true); - expect(executeTimes[1] >= newInstanceTimes[0]).to.be(true); - expect(executeTimes[2] > newInstanceTimes[0]).to.be(true); - expect(executeStartTimes.length === executeTimes.length).to.be(true); - expect(recoveredInstanceTimes[0] > newInstanceTimes[0]).to.be(true); - - // validate each event - let executeCount = 0; - let numActiveAlerts = 0; - let numNewAlerts = 0; - let numRecoveredAlerts = 0; - let currentExecutionId; - const executeStatuses = ['ok', 'active', 'active']; - for (const event of events) { - switch (event?.event?.action) { - case 'execute-start': - currentExecutionId = event?.kibana?.alert?.rule?.execution?.uuid; - validateEvent(event, { - spaceId: space.id, - savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, - ], - message: `rule execution start: "${alertId}"`, - shouldHaveTask: true, - executionId: currentExecutionId, - ruleTypeId: response.body.rule_type_id, - rule: { - id: alertId, - category: response.body.rule_type_id, - license: 'basic', - ruleset: 'alertsFixture', - }, - consumer: 'alertsFixture', - }); - break; - case 'execute-action': - expect( - [firstSubgroup, secondSubgroup].includes( - event?.kibana?.alerting?.action_subgroup! - ) - ).to.be(true); - validateEvent(event, { - spaceId: space.id, - savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, - { type: 'action', id: createdAction.id, type_id: 'test.noop' }, - ], - message: `alert: test.patternFiring:${alertId}: 'abc' instanceId: 'instance' scheduled actionGroup(subgroup): 'default(${event?.kibana?.alerting?.action_subgroup})' action: test.noop:${createdAction.id}`, - instanceId: 'instance', - actionGroupId: 'default', - executionId: currentExecutionId, - ruleTypeId: response.body.rule_type_id, - rule: { - id: alertId, - category: response.body.rule_type_id, - license: 'basic', - ruleset: 'alertsFixture', - name: response.body.name, - }, - consumer: 'alertsFixture', - }); - break; - case 'new-instance': - numNewAlerts++; - validateInstanceEvent( - event, - `created new alert: 'instance'`, - false, - currentExecutionId - ); - break; - case 'recovered-instance': - numRecoveredAlerts++; - validateInstanceEvent( - event, - `alert 'instance' has recovered`, - true, - currentExecutionId - ); - break; - case 'active-instance': - numActiveAlerts++; - expect( - [firstSubgroup, secondSubgroup].includes( - event?.kibana?.alerting?.action_subgroup! - ) - ).to.be(true); - validateInstanceEvent( - event, - `active alert: 'instance' in actionGroup(subgroup): 'default(${event?.kibana?.alerting?.action_subgroup})'`, - false, - currentExecutionId - ); - break; - case 'execute': - validateEvent(event, { - spaceId: space.id, - savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, - ], - outcome: 'success', - message: `rule executed: test.patternFiring:${alertId}: 'abc'`, - status: executeStatuses[executeCount++], - shouldHaveTask: true, - executionId: currentExecutionId, - ruleTypeId: response.body.rule_type_id, - rule: { - id: alertId, - category: response.body.rule_type_id, - license: 'basic', - ruleset: 'alertsFixture', - name: response.body.name, - }, - consumer: 'alertsFixture', - numActiveAlerts, - numNewAlerts, - numRecoveredAlerts, - }); - numActiveAlerts = 0; - numNewAlerts = 0; - numRecoveredAlerts = 0; - break; - // this will get triggered as we add new event actions - default: - throw new Error(`unexpected event action "${event?.event?.action}"`); - } - } - - function validateInstanceEvent( - event: IValidatedEvent, - subMessage: string, - shouldHaveEventEnd: boolean, - executionId?: string - ) { - validateEvent(event, { - spaceId: space.id, - savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, - ], - message: `test.patternFiring:${alertId}: 'abc' ${subMessage}`, - instanceId: 'instance', - actionGroupId: 'default', - shouldHaveEventEnd, - executionId, - ruleTypeId: response.body.rule_type_id, - rule: { - id: alertId, - category: response.body.rule_type_id, - license: 'basic', - ruleset: 'alertsFixture', - name: response.body.name, - }, - consumer: 'alertsFixture', - }); - } - }); - it('should generate events for execution errors', async () => { const response = await supertest .post(`${getUrlPrefix(space.id)}/api/alerting/rule`) diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts index 2d30465401caa..23dcc1abaea44 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts @@ -7,6 +7,7 @@ import expect from '@kbn/expect'; import { SuperTest, Test } from 'supertest'; +import { fromKueryExpression } from '@kbn/es-query'; import { Spaces } from '../../scenarios'; import { getUrlPrefix, getTestRuleData, ObjectRemover } from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; @@ -198,6 +199,20 @@ const findTestUtils = ( expect(response.body.data[0].params.strValue).to.eql('my b'); }); + it('should filter on kueryNode parameters', async () => { + const response = await supertest.get( + `${getUrlPrefix(Spaces.space1.id)}/${ + describeType === 'public' ? 'api' : 'internal' + }/alerting/rules/_find?filter=${JSON.stringify( + fromKueryExpression('alert.attributes.params.strValue:"my b"') + )}` + ); + + expect(response.status).to.eql(200); + expect(response.body.total).to.equal(1); + expect(response.body.data[0].params.strValue).to.eql('my b'); + }); + it('should sort by parameters', async () => { const response = await supertest.get( `${getUrlPrefix(Spaces.space1.id)}/${ diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/notify_when.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/notify_when.ts index 5024a1489f4c8..a7996f19554e8 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/notify_when.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/notify_when.ts @@ -174,97 +174,6 @@ export default function createNotifyWhenTests({ getService }: FtrProviderContext ); expect(executeActionEventsActionGroup).to.eql(expectedActionGroupBasedOnPattern); }); - - it(`alert with notifyWhen=onActionGroupChange should only execute actions when action subgroup changes`, async () => { - const { body: defaultAction } = await supertest - .post(`${getUrlPrefix(Spaces.space1.id)}/api/actions/connector`) - .set('kbn-xsrf', 'foo') - .send({ - name: 'My Default Action', - connector_type_id: 'test.noop', - config: {}, - secrets: {}, - }) - .expect(200); - - const { body: recoveredAction } = await supertest - .post(`${getUrlPrefix(Spaces.space1.id)}/api/actions/connector`) - .set('kbn-xsrf', 'foo') - .send({ - name: 'My Recovered Action', - connector_type_id: 'test.noop', - config: {}, - secrets: {}, - }) - .expect(200); - - const pattern = { - instance: [ - 'subgroup1', - 'subgroup1', - false, - false, - 'subgroup1', - 'subgroup2', - 'subgroup2', - false, - ], - }; - const expectedActionGroupBasedOnPattern = [ - 'default', - 'recovered', - 'default', - 'default', - 'recovered', - ]; - - const { body: createdAlert } = await supertest - .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) - .set('kbn-xsrf', 'foo') - .send( - getTestRuleData({ - rule_type_id: 'test.patternFiring', - params: { pattern }, - schedule: { interval: '1s' }, - throttle: null, - notify_when: 'onActionGroupChange', - actions: [ - { - id: defaultAction.id, - group: 'default', - params: {}, - }, - { - id: recoveredAction.id, - group: 'recovered', - params: {}, - }, - ], - }) - ) - .expect(200); - objectRemover.add(Spaces.space1.id, createdAlert.id, 'rule', 'alerting'); - - const events = await retry.try(async () => { - return await getEventLog({ - getService, - spaceId: Spaces.space1.id, - type: 'alert', - id: createdAlert.id, - provider: 'alerting', - actions: new Map([ - ['execute-action', { gte: 5 }], - ['new-instance', { equal: 2 }], - ]), - }); - }); - - const executeActionEvents = getEventsByAction(events, 'execute-action'); - const executeActionEventsActionGroup = executeActionEvents.map( - (event) => event?.kibana?.alerting?.action_group_id - ); - expect(executeActionEventsActionGroup).to.eql(expectedActionGroupBasedOnPattern); - }); }); } diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/snooze.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/snooze.ts index 02340f69718d6..a7301d1467bf7 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/snooze.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/snooze.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import uuid from 'uuid'; import { Spaces } from '../../scenarios'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; import { @@ -240,6 +241,79 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext expect(actionsAfter).to.be.greaterThan(0, 'no actions triggered after snooze'); expect(actionsDuring).to.be(0); }); + + it('should prevent more than 5 schedules from being added to a rule', async () => { + const { body: createdRule } = await supertest + .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + enabled: false, + }) + ) + .expect(200); + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); + + // Creating 5 snooze schedules, using Promise.all is very flaky, therefore + // the schedules are being created 1 at a time + await alertUtils + .getSnoozeRequest(createdRule.id) + .send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }) + .expect(204); + await alertUtils + .getSnoozeRequest(createdRule.id) + .send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }) + .expect(204); + await alertUtils + .getSnoozeRequest(createdRule.id) + .send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }) + .expect(204); + + await alertUtils + .getSnoozeRequest(createdRule.id) + .send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }) + .expect(204); + + await alertUtils + .getSnoozeRequest(createdRule.id) + .send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }) + .expect(204); + + // Adding the 6th snooze schedule, should fail + const response = await alertUtils.getSnoozeRequest(createdRule.id).send({ + snooze_schedule: { + ...SNOOZE_SCHEDULE, + id: uuid.v4(), + }, + }); + expect(response.statusCode).to.eql(400); + expect(response.body.message).to.eql('Rule cannot have more than 5 snooze schedules'); + }); }); async function getRuleEvents(id: string, minActions: number = 1) { diff --git a/x-pack/test/api_integration/apis/ml/index.ts b/x-pack/test/api_integration/apis/ml/index.ts index 915d755ca97c0..e76eef8cb82bf 100644 --- a/x-pack/test/api_integration/apis/ml/index.ts +++ b/x-pack/test/api_integration/apis/ml/index.ts @@ -67,5 +67,6 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./saved_objects')); loadTestFile(require.resolve('./system')); loadTestFile(require.resolve('./trained_models')); + loadTestFile(require.resolve('./notifications')); }); } diff --git a/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts b/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts new file mode 100644 index 0000000000000..58932ea199b5d --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/notifications/count_notifications.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import moment from 'moment'; +import type { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; + +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + describe('GET notifications count', () => { + before(async () => { + await ml.api.initSavedObjects(); + await ml.testResources.setKibanaTimeZoneToUTC(); + + const adJobConfig = ml.commonConfig.getADFqSingleMetricJobConfig('fq_job'); + await ml.api.createAnomalyDetectionJob(adJobConfig); + + await ml.api.waitForJobNotificationsToIndex('fq_job'); + }); + + after(async () => { + await ml.api.cleanMlIndices(); + await ml.testResources.cleanMLSavedObjects(); + }); + + it('return notifications count by level', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications/count`) + .query({ lastCheckedAt: moment().subtract(7, 'd').valueOf() }) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(200, status, body); + + expect(body.info).to.eql(1); + expect(body.warning).to.eql(0); + expect(body.error).to.eql(0); + }); + + it('returns an error for unauthorized user', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications/count`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(403, status, body); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts b/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts new file mode 100644 index 0000000000000..992065cdae67d --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts @@ -0,0 +1,102 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import type { + NotificationItem, + NotificationsSearchResponse, +} from '@kbn/ml-plugin/common/types/notifications'; +import type { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; + +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const esArchiver = getService('esArchiver'); + const ml = getService('ml'); + + describe('GET notifications', () => { + before(async () => { + await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/ml/bm_classification'); + await ml.api.initSavedObjects(); + await ml.testResources.setKibanaTimeZoneToUTC(); + + const adJobConfig = ml.commonConfig.getADFqSingleMetricJobConfig('fq_job'); + await ml.api.createAnomalyDetectionJob(adJobConfig); + + const dfaJobConfig = ml.commonConfig.getDFABmClassificationJobConfig('df_job'); + await ml.api.createDataFrameAnalyticsJob(dfaJobConfig); + + // wait for notification to index + + await ml.api.waitForJobNotificationsToIndex('fq_job'); + await ml.api.waitForJobNotificationsToIndex('df_job'); + }); + + after(async () => { + await ml.api.cleanMlIndices(); + await ml.testResources.cleanMLSavedObjects(); + }); + + it('return all notifications ', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications`) + .query({ earliest: 'now-1d', latest: 'now' }) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(200, status, body); + + expect((body as NotificationsSearchResponse).total).to.eql(2); + }); + + it('return notifications based on the query string', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications`) + .query({ earliest: 'now-1d', latest: 'now', queryString: 'job_type:anomaly_detector' }) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(200, status, body); + + expect((body as NotificationsSearchResponse).total).to.eql(1); + expect( + (body as NotificationsSearchResponse).results.filter( + (result: NotificationItem) => result.job_type === 'anomaly_detector' + ) + ).to.length(body.total); + }); + + it('supports sorting asc sorting by field', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications`) + .query({ earliest: 'now-1d', latest: 'now', sortField: 'job_id', sortDirection: 'asc' }) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(200, status, body); + + expect(body.results[0].job_id).to.eql('df_job'); + }); + + it('supports sorting desc sorting by field', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications`) + .query({ earliest: 'now-1h', latest: 'now', sortField: 'job_id', sortDirection: 'desc' }) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(200, status, body); + + expect(body.results[0].job_id).to.eql('fq_job'); + }); + + it('returns an error for unauthorized user', async () => { + const { body, status } = await supertest + .get(`/api/ml/notifications`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS); + ml.api.assertResponseStatusCode(403, status, body); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/notifications/index.ts b/x-pack/test/api_integration/apis/ml/notifications/index.ts new file mode 100644 index 0000000000000..4a09fce5ee51e --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/notifications/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('Notifications', function () { + loadTestFile(require.resolve('./get_notifications')); + loadTestFile(require.resolve('./count_notifications')); + }); +} diff --git a/x-pack/test/api_integration/apis/osquery/packs.ts b/x-pack/test/api_integration/apis/osquery/packs.ts index 9d00249a4e1b0..de490a489cec7 100644 --- a/x-pack/test/api_integration/apis/osquery/packs.ts +++ b/x-pack/test/api_integration/apis/osquery/packs.ts @@ -45,7 +45,8 @@ limit 1000;`; export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); - describe('Packs', () => { + // FLAKY: https://github.com/elastic/kibana/issues/133259 + describe.skip('Packs', () => { let packId: string = ''; let hostedPolicy: Record; let packagePolicyId: string; diff --git a/x-pack/test/api_integration/apis/uptime/rest/add_monitor_project.ts b/x-pack/test/api_integration/apis/uptime/rest/add_monitor_project.ts index 76af9a5731256..9dce7e7d8fdaa 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/add_monitor_project.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/add_monitor_project.ts @@ -220,7 +220,12 @@ export default function ({ getService }: FtrProviderContext) { expect(messages[2].failedMonitors).eql([ { id: httpProjectMonitors.monitors[0].id, - details: `The following Heartbeat options are not supported for ${httpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: check.response.body|unsupportedKey.nestedUnsupportedKey`, + details: `Multiple urls are not supported for http project monitors in ${kibanaVersion}. Please set only 1 url per monitor. You monitor was not created or updated.`, + reason: 'Unsupported Heartbeat option', + }, + { + id: httpProjectMonitors.monitors[0].id, + details: `The following Heartbeat options are not supported for ${httpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: check.response.body|unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.`, reason: 'Unsupported Heartbeat option', }, ]); @@ -328,7 +333,12 @@ export default function ({ getService }: FtrProviderContext) { expect(messages[2].failedMonitors).eql([ { id: tcpProjectMonitors.monitors[2].id, - details: `The following Heartbeat options are not supported for ${tcpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: ports|unsupportedKey.nestedUnsupportedKey`, + details: `Multiple hosts are not supported for tcp project monitors in ${kibanaVersion}. Please set only 1 host per monitor. You monitor was not created or updated.`, + reason: 'Unsupported Heartbeat option', + }, + { + id: tcpProjectMonitors.monitors[2].id, + details: `The following Heartbeat options are not supported for ${tcpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: ports|unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.`, reason: 'Unsupported Heartbeat option', }, ]); @@ -422,7 +432,12 @@ export default function ({ getService }: FtrProviderContext) { expect(messages[2].failedMonitors).eql([ { id: icmpProjectMonitors.monitors[2].id, - details: `The following Heartbeat options are not supported for ${icmpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: unsupportedKey.nestedUnsupportedKey`, + details: `Multiple hosts are not supported for icmp project monitors in ${kibanaVersion}. Please set only 1 host per monitor. You monitor was not created or updated.`, + reason: 'Unsupported Heartbeat option', + }, + { + id: icmpProjectMonitors.monitors[2].id, + details: `The following Heartbeat options are not supported for ${icmpProjectMonitors.monitors[0].type} project monitors in ${kibanaVersion}: unsupportedKey.nestedUnsupportedKey. You monitor was not created or updated.`, reason: 'Unsupported Heartbeat option', }, ]); diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_http_monitor.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_http_monitor.json index fc754cbdcd038..42044c8ba9cf3 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_http_monitor.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_http_monitor.json @@ -9,7 +9,8 @@ "id": "my-monitor-2", "name": "My Monitor 2", "urls": [ - "http://localhost:9200" + "http://localhost:9200", + "http://anotherurl:9200" ], "schedule": 60, "timeout": "80s", @@ -32,7 +33,6 @@ "saved" ] }, - "content": "", "unsupportedKey": { "nestedUnsupportedKey": "unsupportedValue" } @@ -69,8 +69,7 @@ "saved" ] } - }, - "content": "" + } } ] } \ No newline at end of file diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_icmp_monitor.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_icmp_monitor.json index 8dec1b28d50c4..b19e910882582 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_icmp_monitor.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_icmp_monitor.json @@ -14,7 +14,6 @@ "schedule": 1, "tags": [ "service:smtp", "org:google" ], "privateLocations": [ "Test private location 0" ], - "content": "", "wait": "30s" }, { @@ -26,7 +25,6 @@ "schedule": 1, "tags": "tag1,tag2", "privateLocations": [ "Test private location 0" ], - "content": "", "wait": "1m" }, { @@ -34,11 +32,10 @@ "type": "icmp", "id": "Cloudflare-DNS-3", "name": "Cloudflare DNS 3", - "hosts": "1.1.1.1", + "hosts": "1.1.1.1,2.2.2.2", "schedule": 1, "tags": "tag1,tag2", "privateLocations": [ "Test private location 0" ], - "content": "", "unsupportedKey": { "nestedUnsupportedKey": "unnsuportedValue" } diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_tcp_monitor.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_tcp_monitor.json index 30061673079d3..82d6c8c557e77 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_tcp_monitor.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/project_tcp_monitor.json @@ -10,8 +10,7 @@ "hosts": [ "smtp.gmail.com:587" ], "schedule": 1, "tags": [ "service:smtp", "org:google" ], - "privateLocations": [ "BEEP" ], - "content": "" + "privateLocations": [ "BEEP" ] }, { "locations": [ "localhost" ], @@ -21,20 +20,18 @@ "hosts": "localhost:18278", "schedule": 1, "tags": "tag1,tag2", - "privateLocations": [ "BEEP" ], - "content": "" + "privateLocations": [ "BEEP" ] }, { "locations": [ "localhost" ], "type": "tcp", "id": "always-down", "name": "Always Down", - "hosts": "localhost", + "hosts": ["localhost", "anotherhost"], "ports": ["5698"], "schedule": 1, "tags": "tag1,tag2", "privateLocations": [ "BEEP" ], - "content": "", "unsupportedKey": { "nestedUnsupportedKey": "unnsuportedValue" } diff --git a/x-pack/test/apm_api_integration/common/bootstrap_apm_synthtrace.ts b/x-pack/test/apm_api_integration/common/bootstrap_apm_synthtrace.ts index 96d0cbf3f8e7b..0a790d261ef49 100644 --- a/x-pack/test/apm_api_integration/common/bootstrap_apm_synthtrace.ts +++ b/x-pack/test/apm_api_integration/common/bootstrap_apm_synthtrace.ts @@ -7,7 +7,7 @@ import { apm, createLogger, LogLevel } from '@kbn/apm-synthtrace'; import { esTestConfig } from '@kbn/test'; -import { APM_TEST_PASSWORD } from './authentication'; +import { APM_TEST_PASSWORD } from '@kbn/apm-plugin/server/test_helpers/create_apm_users/authentication'; import { InheritedFtrProviderContext } from './ftr_provider_context'; export async function bootstrapApmSynthtrace( diff --git a/x-pack/test/apm_api_integration/common/config.ts b/x-pack/test/apm_api_integration/common/config.ts index e01c5fbf40541..431b445d3a1a0 100644 --- a/x-pack/test/apm_api_integration/common/config.ts +++ b/x-pack/test/apm_api_integration/common/config.ts @@ -8,11 +8,12 @@ import { FtrConfigProviderContext } from '@kbn/test'; import supertest from 'supertest'; import { format, UrlObject } from 'url'; -import { Client } from '@elastic/elasticsearch'; -import { ToolingLog } from '@kbn/tooling-log'; -import { SecurityServiceProvider } from '../../../../test/common/services/security'; +import { + ApmUsername, + APM_TEST_PASSWORD, +} from '@kbn/apm-plugin/server/test_helpers/create_apm_users/authentication'; +import { createApmUsers } from '@kbn/apm-plugin/server/test_helpers/create_apm_users/create_apm_users'; import { InheritedFtrProviderContext, InheritedServices } from './ftr_provider_context'; -import { createApmUser, APM_TEST_PASSWORD, ApmUsername } from './authentication'; import { APMFtrConfigName } from '../configs'; import { createApmApiClient } from './apm_api_supertest'; import { RegistryProvider } from './registry'; @@ -25,17 +26,8 @@ export interface ApmFtrConfig { kibanaConfig?: Record; } -type SecurityService = Awaited>; - function getLegacySupertestClient(kibanaServer: UrlObject, username: ApmUsername) { return async (context: InheritedFtrProviderContext) => { - const security = context.getService('security'); - const es = context.getService('es'); - const logger = context.getService('log'); - await security.init(); - - await createApmUser({ security, username, es, logger }); - const url = format({ ...kibanaServer, auth: `${username}:${APM_TEST_PASSWORD}`, @@ -47,19 +39,11 @@ function getLegacySupertestClient(kibanaServer: UrlObject, username: ApmUsername async function getApmApiClient({ kibanaServer, - security, username, - es, - logger, }: { kibanaServer: UrlObject; - security: SecurityService; username: ApmUsername; - es: Client; - logger: ToolingLog; }) { - await createApmUser({ security, username, es, logger }); - const url = format({ ...kibanaServer, auth: `${username}:${APM_TEST_PASSWORD}`, @@ -81,6 +65,8 @@ export function createTestConfig(config: ApmFtrConfig) { const services = xPackAPITestsConfig.get('services') as InheritedServices; const servers = xPackAPITestsConfig.get('servers'); const kibanaServer = servers.kibana as UrlObject; + const kibanaServerUrl = format(kibanaServer); + const esServer = servers.elasticsearch as UrlObject; return { testFiles: [require.resolve('../tests')], @@ -91,72 +77,50 @@ export function createTestConfig(config: ApmFtrConfig) { apmFtrConfig: () => config, registry: RegistryProvider, synthtraceEsClient: (context: InheritedFtrProviderContext) => { - const kibanaServerUrl = format(kibanaServer); return bootstrapApmSynthtrace(context, kibanaServerUrl); }, apmApiClient: async (context: InheritedFtrProviderContext) => { - const security = context.getService('security'); - const es = context.getService('es'); - const logger = context.getService('log'); + const { username, password } = servers.kibana; + const esUrl = format(esServer); - await security.init(); + // Creates APM users + await createApmUsers({ + elasticsearch: { node: esUrl, username, password }, + kibana: { hostname: kibanaServerUrl }, + }); return { noAccessUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.noAccessUser, - es, - logger, }), readUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.viewerUser, - es, - logger, }), writeUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.editorUser, - es, - logger, }), annotationWriterUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.apmAnnotationsWriteUser, - es, - logger, }), noMlAccessUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.apmReadUserWithoutMlAccess, - es, - logger, }), manageOwnAgentKeysUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.apmManageOwnAgentKeys, - es, - logger, }), createAndAllAgentKeysUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.apmManageOwnAndCreateAgentKeys, - es, - logger, }), monitorIndicesUser: await getApmApiClient({ kibanaServer, - security, username: ApmUsername.apmMonitorIndices, - es, - logger, }), }; }, diff --git a/x-pack/test/apm_api_integration/tests/services/sorted_and_filtered_services.spec.ts b/x-pack/test/apm_api_integration/tests/services/sorted_and_filtered_services.spec.ts index fdc1e84cddfc3..f084f8cdca187 100644 --- a/x-pack/test/apm_api_integration/tests/services/sorted_and_filtered_services.spec.ts +++ b/x-pack/test/apm_api_integration/tests/services/sorted_and_filtered_services.spec.ts @@ -50,7 +50,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { type ServiceListItem = ValuesType>>; - registry.when('Sorted and filtered services', { config: 'trial', archives: [] }, () => { + registry.when.skip('Sorted and filtered services', { config: 'trial', archives: [] }, () => { before(async () => { const serviceA = apm .service({ name: SERVICE_NAME_PREFIX + 'a', environment: 'production', agentName: 'java' }) diff --git a/x-pack/test/apm_api_integration/tests/settings/agent_keys/agent_keys.spec.ts b/x-pack/test/apm_api_integration/tests/settings/agent_keys/agent_keys.spec.ts index c0d6500fd298c..19459d2a4ec16 100644 --- a/x-pack/test/apm_api_integration/tests/settings/agent_keys/agent_keys.spec.ts +++ b/x-pack/test/apm_api_integration/tests/settings/agent_keys/agent_keys.spec.ts @@ -7,9 +7,9 @@ import expect from '@kbn/expect'; import { first } from 'lodash'; import { PrivilegeType } from '@kbn/apm-plugin/common/privilege_type'; +import { ApmUsername } from '@kbn/apm-plugin/server/test_helpers/create_apm_users/authentication'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; import { ApmApiError, ApmApiSupertest } from '../../../common/apm_api_supertest'; -import { ApmUsername } from '../../../common/authentication'; export default function ApiTest({ getService }: FtrProviderContext) { const registry = getService('registry'); diff --git a/x-pack/test/banners_functional/config.ts b/x-pack/test/banners_functional/config.ts index 2280cf11cfbf2..83d0c4656572c 100644 --- a/x-pack/test/banners_functional/config.ts +++ b/x-pack/test/banners_functional/config.ts @@ -35,7 +35,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { serverArgs: [ ...kibanaFunctionalConfig.get('kbnTestServer.serverArgs'), '--xpack.banners.placement=top', - '--xpack.banners.textContent=global_banner_text', + '--xpack.banners.textContent="global banner text"', ], }, }; diff --git a/x-pack/test/banners_functional/tests/global.ts b/x-pack/test/banners_functional/tests/global.ts index a36d98589163a..cef404d7ed132 100644 --- a/x-pack/test/banners_functional/tests/global.ts +++ b/x-pack/test/banners_functional/tests/global.ts @@ -16,7 +16,7 @@ export default function ({ getPageObjects }: FtrProviderContext) { await PageObjects.common.navigateToApp('login'); expect(await PageObjects.banners.isTopBannerVisible()).to.eql(true); - expect(await PageObjects.banners.getTopBannerText()).to.eql('global_banner_text'); + expect(await PageObjects.banners.getTopBannerText()).to.eql('global banner text'); }); }); } diff --git a/x-pack/test/banners_functional/tests/spaces.ts b/x-pack/test/banners_functional/tests/spaces.ts index 43c9612fa5696..2ec7d0939b100 100644 --- a/x-pack/test/banners_functional/tests/spaces.ts +++ b/x-pack/test/banners_functional/tests/spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { - const esArchiver = getService('esArchiver'); + const spacesService = getService('spaces'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects([ 'common', @@ -21,14 +21,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { describe('per-spaces banners', () => { before(async () => { - await esArchiver.load('x-pack/test/functional/es_archives/banners/multispace'); - }); - - after(async () => { - await esArchiver.unload('x-pack/test/functional/es_archives/banners/multispace'); - }); - - before(async () => { + await spacesService.create({ + id: 'another-space', + name: 'Another Space', + disabledFeatures: [], + }); await kibanaServer.uiSettings.replace( { 'banners:textContent': 'default space banner text', @@ -39,6 +36,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expectSpaceSelector: true, }); }); + after(async () => { + await spacesService.delete('another-space'); + await kibanaServer.savedObjects.cleanStandardList(); + }); it('displays the space-specific banner within the space', async () => { await PageObjects.common.navigateToApp('home'); @@ -51,7 +52,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.common.navigateToApp('home', { basePath: '/s/another-space' }); expect(await PageObjects.banners.isTopBannerVisible()).to.eql(true); - expect(await PageObjects.banners.getTopBannerText()).to.eql('global_banner_text'); + expect(await PageObjects.banners.getTopBannerText()).to.eql('global banner text'); }); it('displays the global banner on the login page', async () => { @@ -59,7 +60,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.common.navigateToApp('login'); expect(await PageObjects.banners.isTopBannerVisible()).to.eql(true); - expect(await PageObjects.banners.getTopBannerText()).to.eql('global_banner_text'); + expect(await PageObjects.banners.getTopBannerText()).to.eql('global banner text'); }); }); } diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/perform_bulk_action.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/perform_bulk_action.ts index b60ce575c4cd0..8f06bc93820a4 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/perform_bulk_action.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/perform_bulk_action.ts @@ -1513,10 +1513,9 @@ export default ({ getService }: FtrProviderContext): void => { }); describe('throttle', () => { + // For bulk editing of rule actions, NOTIFICATION_THROTTLE_NO_ACTIONS + // is not available as payload, because "Perform No Actions" is not a valid option const casesForEmptyActions = [ - { - payloadThrottle: NOTIFICATION_THROTTLE_NO_ACTIONS, - }, { payloadThrottle: NOTIFICATION_THROTTLE_RULE, }, @@ -1561,10 +1560,6 @@ export default ({ getService }: FtrProviderContext): void => { }); const casesForNonEmptyActions = [ - { - payloadThrottle: NOTIFICATION_THROTTLE_NO_ACTIONS, - expectedThrottle: NOTIFICATION_THROTTLE_NO_ACTIONS, - }, { payloadThrottle: NOTIFICATION_THROTTLE_RULE, expectedThrottle: NOTIFICATION_THROTTLE_RULE, @@ -1616,12 +1611,9 @@ export default ({ getService }: FtrProviderContext): void => { }); describe('notifyWhen', () => { + // For bulk editing of rule actions, NOTIFICATION_THROTTLE_NO_ACTIONS + // is not available as payload, because "Perform No Actions" is not a valid option const cases = [ - { - payload: { throttle: NOTIFICATION_THROTTLE_NO_ACTIONS }, - // keeps existing default value which is onActiveAlert - expected: { notifyWhen: 'onActiveAlert' }, - }, { payload: { throttle: '1d' }, expected: { notifyWhen: 'onThrottleInterval' }, @@ -1837,6 +1829,42 @@ export default ({ getService }: FtrProviderContext): void => { expect(setIndexRule.data_view_id).to.eql(undefined); }); + it('should return error when set an empty index pattern to a rule and overwrite the data view when overwrite_data_views is true', async () => { + const dataViewId = 'index1-*'; + const simpleRule = { + ...getSimpleRule(), + index: undefined, + data_view_id: dataViewId, + }; + const rule = await createRule(supertest, log, simpleRule); + + const { body } = await postBulkAction() + .send({ + query: '', + action: BulkAction.edit, + [BulkAction.edit]: [ + { + type: BulkActionEditType.set_index_patterns, + value: [], + overwrite_data_views: true, + }, + ], + }) + .expect(500); + + expect(body.attributes.summary).to.eql({ failed: 1, succeeded: 0, total: 1 }); + expect(body.attributes.errors[0]).to.eql({ + message: "Mutated params invalid: Index patterns can't be empty", + status_code: 500, + rules: [ + { + id: rule.id, + name: rule.name, + }, + ], + }); + }); + it('should NOT set an index pattern to a rule and overwrite the data view when overwrite_data_views is false', async () => { const ruleId = 'ruleId'; const dataViewId = 'index1-*'; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules.ts index a8dc735376f69..705714ec3ba50 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules.ts @@ -220,7 +220,7 @@ export default ({ getService }: FtrProviderContext) => { updatedRule.rule_id = createRuleBody.rule_id; updatedRule.name = 'some other name'; updatedRule.actions = [action1]; - updatedRule.throttle = '1m'; + updatedRule.throttle = '1d'; delete updatedRule.id; const { body } = await supertest @@ -243,7 +243,7 @@ export default ({ getService }: FtrProviderContext) => { }, }, ]; - outputRule.throttle = '1m'; + outputRule.throttle = '1d'; const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body); expect(bodyToCompare).to.eql(outputRule); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules_bulk.ts index dc7209b9f1c98..2f5fb63382552 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/group10/update_rules_bulk.ts @@ -150,12 +150,12 @@ export default ({ getService }: FtrProviderContext) => { const updatedRule1 = getSimpleRuleUpdate('rule-1'); updatedRule1.name = 'some other name'; updatedRule1.actions = [action1]; - updatedRule1.throttle = '1m'; + updatedRule1.throttle = '1d'; const updatedRule2 = getSimpleRuleUpdate('rule-2'); updatedRule2.name = 'some other name'; updatedRule2.actions = [action1]; - updatedRule2.throttle = '1m'; + updatedRule2.throttle = '1d'; // update both rule names const { body }: { body: FullResponseSchema[] } = await supertest @@ -179,7 +179,7 @@ export default ({ getService }: FtrProviderContext) => { }, }, ]; - outputRule.throttle = '1m'; + outputRule.throttle = '1d'; const bodyToCompare = removeServerGeneratedProperties(response); expect(bodyToCompare).to.eql(outputRule); }); diff --git a/x-pack/test/fleet_api_integration/apis/agents/reassign.ts b/x-pack/test/fleet_api_integration/apis/agents/reassign.ts index 746a2fcda1ba1..2dd546511dd9a 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/reassign.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/reassign.ts @@ -107,7 +107,7 @@ export default function (providerContext: FtrProviderContext) { }); it('should allow to reassign multiple agents by id -- mix valid & invalid', async () => { - const { body } = await supertest + await supertest .post(`/api/fleet/agents/bulk_reassign`) .set('kbn-xsrf', 'xxx') .send({ @@ -115,32 +115,24 @@ export default function (providerContext: FtrProviderContext) { policy_id: 'policy2', }); - expect(body).to.eql({ - agent2: { success: true }, - INVALID_ID: { - success: false, - error: 'Cannot find agent INVALID_ID', - }, - agent3: { success: true }, - MISSING_ID: { - success: false, - error: 'Cannot find agent MISSING_ID', - }, - etc: { - success: false, - error: 'Cannot find agent etc', - }, - }); - const [agent2data, agent3data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent2`), supertest.get(`/api/fleet/agents/agent3`), ]); expect(agent2data.body.item.policy_id).to.eql('policy2'); expect(agent3data.body.item.policy_id).to.eql('policy2'); + + const { body } = await supertest + .get(`/api/fleet/agents/action_status`) + .set('kbn-xsrf', 'xxx'); + const actionStatus = body.items[0]; + + expect(actionStatus.status).to.eql('FAILED'); + expect(actionStatus.nbAgentsActionCreated).to.eql(2); + expect(actionStatus.nbAgentsFailed).to.eql(3); }); - it('should allow to reassign multiple agents by id -- mixed invalid, hosted, etc', async () => { + it('should return error when none of the agents can be reassigned -- mixed invalid, hosted, etc', async () => { // agent1 is enrolled in policy1. set policy1 to hosted await supertest .put(`/api/fleet/agent_policies/policy1`) @@ -154,24 +146,9 @@ export default function (providerContext: FtrProviderContext) { .send({ agents: ['agent2', 'INVALID_ID', 'agent3'], policy_id: 'policy2', - }); - - expect(body).to.eql({ - agent2: { - success: false, - error: - 'Cannot reassign an agent from hosted agent policy policy1 in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.', - }, - INVALID_ID: { - success: false, - error: 'Cannot find agent INVALID_ID', - }, - agent3: { - success: false, - error: - 'Cannot reassign an agent from hosted agent policy policy1 in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.', - }, - }); + }) + .expect(400); + expect(body.message).to.eql('No agents to reassign, already assigned or hosted agents'); const [agent2data, agent3data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent2`), diff --git a/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts b/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts index 058fccfb376d8..7f778d77f1a51 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts @@ -120,7 +120,7 @@ export default function (providerContext: FtrProviderContext) { .expect(200); // try to unenroll - const { body: unenrolledBody } = await supertest + await supertest .post(`/api/fleet/agents/bulk_unenroll`) .set('kbn-xsrf', 'xxx') .send({ @@ -129,18 +129,6 @@ export default function (providerContext: FtrProviderContext) { // http request succeeds .expect(200); - expect(unenrolledBody).to.eql({ - agent2: { - success: false, - error: - 'Cannot unenroll agent2 from a hosted agent policy policy1 in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.', - }, - agent3: { - success: false, - error: - 'Cannot unenroll agent3 from a hosted agent policy policy1 in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.', - }, - }); // but agents are still enrolled const [agent2data, agent3data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent2`), @@ -152,6 +140,13 @@ export default function (providerContext: FtrProviderContext) { expect(typeof agent3data.body.item.unenrollment_started_at).to.be('undefined'); expect(typeof agent3data.body.item.unenrolled_at).to.be('undefined'); expect(agent2data.body.item.active).to.eql(true); + + const { body } = await supertest + .get(`/api/fleet/agents/action_status`) + .set('kbn-xsrf', 'xxx'); + const actionStatus = body.items[0]; + expect(actionStatus.status).to.eql('FAILED'); + expect(actionStatus.nbAgentsFailed).to.eql(2); }); it('/agents/bulk_unenroll should allow to unenroll multiple agents by id from an regular agent policy', async () => { @@ -161,18 +156,13 @@ export default function (providerContext: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ name: 'Test policy', namespace: 'default', is_managed: false }) .expect(200); - const { body: unenrolledBody } = await supertest + await supertest .post(`/api/fleet/agents/bulk_unenroll`) .set('kbn-xsrf', 'xxx') .send({ agents: ['agent2', 'agent3'], }); - expect(unenrolledBody).to.eql({ - agent2: { success: true }, - agent3: { success: true }, - }); - const [agent2data, agent3data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent2`), supertest.get(`/api/fleet/agents/agent3`), diff --git a/x-pack/test/fleet_api_integration/apis/agents/update_agent_tags.ts b/x-pack/test/fleet_api_integration/apis/agents/update_agent_tags.ts index afe9f8d677d35..ff11076addcec 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/update_agent_tags.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/update_agent_tags.ts @@ -88,27 +88,46 @@ export default function (providerContext: FtrProviderContext) { }); it('should bulk update tags of multiple agents by kuery in batches', async () => { - await supertest + const { body: actionBody } = await supertest .post(`/api/fleet/agents/bulk_update_agent_tags`) .set('kbn-xsrf', 'xxx') .send({ agents: 'active: true', tagsToAdd: ['newTag'], tagsToRemove: ['existingTag'], - batchSize: 2, + batchSize: 3, }) .expect(200); + const actionId = actionBody.actionId; + + const verifyActionResult = async () => { + const { body } = await supertest.get(`/api/fleet/agents`).set('kbn-xsrf', 'xxx'); + expect(body.total).to.eql(4); + body.items.forEach((agent: any) => { + expect(agent.tags.includes('newTag')).to.be(true); + expect(agent.tags.includes('existingTag')).to.be(false); + }); + }; + await new Promise((resolve, reject) => { - setTimeout(async () => { - const { body } = await supertest.get(`/api/fleet/agents`).set('kbn-xsrf', 'xxx'); - expect(body.total).to.eql(4); - body.items.forEach((agent: any) => { - expect(agent.tags.includes('newTag')).to.be(true); - expect(agent.tags.includes('existingTag')).to.be(false); - }); - resolve({}); - }, 2000); + let attempts = 0; + const intervalId = setInterval(async () => { + if (attempts > 4) { + clearInterval(intervalId); + reject('action timed out'); + } + ++attempts; + const { + body: { items: actionStatuses }, + } = await supertest.get(`/api/fleet/agents/action_status`).set('kbn-xsrf', 'xxx'); + const action = actionStatuses.find((a: any) => a.actionId === actionId); + if (action && action.nbAgentsAck === 4) { + clearInterval(intervalId); + await verifyActionResult(); + resolve({}); + } + }, 1000); }).catch((e) => { throw e; }); @@ -140,7 +159,7 @@ export default function (providerContext: FtrProviderContext) { }); // attempt to update tags of agent in hosted agent policy - const { body } = await supertest + await supertest .post(`/api/fleet/agents/bulk_update_agent_tags`) .set('kbn-xsrf', 'xxx') .send({ @@ -149,14 +168,6 @@ export default function (providerContext: FtrProviderContext) { }) .expect(200); - expect(body).to.eql({ - agent1: { - success: false, - error: `Cannot modify tags on a hosted agent in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.`, - }, - agent2: { success: true }, - }); - const [agent1data, agent2data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent1`), supertest.get(`/api/fleet/agents/agent2`), @@ -164,6 +175,13 @@ export default function (providerContext: FtrProviderContext) { expect(agent1data.body.item.tags.includes('newTag')).to.be(false); expect(agent2data.body.item.tags.includes('newTag')).to.be(true); + + const { body } = await supertest + .get(`/api/fleet/agents/action_status`) + .set('kbn-xsrf', 'xxx'); + const actionStatus = body.items[0]; + expect(actionStatus.status).to.eql('FAILED'); + expect(actionStatus.nbAgentsFailed).to.eql(1); }); }); }); diff --git a/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts b/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts index b842f89c8ac64..e8dad8624021f 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts @@ -57,8 +57,38 @@ export default function (providerContext: FtrProviderContext) { }); describe('one agent', () => { + const fleetServerVersion = '7.16.0'; + + beforeEach(async () => { + await supertest.post(`/api/fleet/agent_policies`).set('kbn-xsrf', 'kibana').send({ + name: 'Fleet Server policy 1', + id: 'fleet-server-policy', + namespace: 'default', + has_fleet_server: true, + }); + + await kibanaServer.savedObjects.create({ + id: `package-policy-test`, + type: PACKAGE_POLICY_SAVED_OBJECT_TYPE, + overwrite: true, + attributes: { + policy_id: 'fleet-server-policy', + name: 'Fleet Server', + package: { + name: 'fleet_server', + }, + }, + }); + await generateAgent( + providerContext, + 'healthy', + 'agentWithFS', + 'fleet-server-policy', + fleetServerVersion + ); + }); + it('should respond 200 to upgrade agent and update the agent SO', async () => { - const kibanaVersion = await kibanaServer.version.get(); await es.update({ id: 'agent1', refresh: 'wait_for', @@ -73,23 +103,39 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersion, + version: fleetServerVersion, }) .expect(200); const res = await supertest.get(`/api/fleet/agents/agent1`).set('kbn-xsrf', 'xxx'); expect(typeof res.body.item.upgrade_started_at).to.be('string'); }); - it('should respond 400 if upgrading agent with version the same as snapshot version', async () => { + + it('should allow to upgrade a Fleet server agent to a version > fleet server version', async () => { const kibanaVersion = await kibanaServer.version.get(); - const kibanaVersionSnapshot = makeSnapshotVersion(kibanaVersion); + await supertest + .post(`/api/fleet/agents/agentWithFS/upgrade`) + .set('kbn-xsrf', 'xxx') + .send({ + version: kibanaVersion, + }) + .expect(200); + + const res = await supertest.get(`/api/fleet/agents/agentWithFS`).set('kbn-xsrf', 'xxx'); + expect(typeof res.body.item.upgrade_started_at).to.be('string'); + }); + + it('should respond 400 if upgrading agent with version the same as snapshot version', async () => { + const fleetServerVersionSnapshot = makeSnapshotVersion(fleetServerVersion); await es.update({ id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, body: { doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: kibanaVersion } } }, + local_metadata: { + elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, + }, }, }, }); @@ -97,20 +143,21 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersionSnapshot, + version: fleetServerVersionSnapshot, }) .expect(400); }); it('should respond 200 if upgrading agent with version the same as snapshot version and force flag is passed', async () => { - const kibanaVersion = await kibanaServer.version.get(); - const kibanaVersionSnapshot = makeSnapshotVersion(kibanaVersion); + const fleetServerVersionSnapshot = makeSnapshotVersion(fleetServerVersion); await es.update({ id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, body: { doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: kibanaVersion } } }, + local_metadata: { + elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, + }, }, }, }); @@ -118,14 +165,13 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersionSnapshot, + version: fleetServerVersionSnapshot, force: true, }) .expect(200); }); it('should respond 200 if upgrading agent with version less than kibana snapshot version', async () => { - const kibanaVersion = await kibanaServer.version.get(); - const kibanaVersionSnapshot = makeSnapshotVersion(kibanaVersion); + const fleetServerVersionSnapshot = makeSnapshotVersion(fleetServerVersion); await es.update({ id: 'agent1', @@ -141,12 +187,11 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersionSnapshot, + version: fleetServerVersionSnapshot, }) .expect(200); }); it('should respond 200 if trying to upgrade with source_uri set', async () => { - const kibanaVersion = await kibanaServer.version.get(); await es.update({ id: 'agent1', refresh: 'wait_for', @@ -161,7 +206,7 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersion, + version: fleetServerVersion, source_uri: 'http://path/to/download', }) .expect(200); @@ -205,7 +250,6 @@ export default function (providerContext: FtrProviderContext) { .expect(400); }); it('should respond 400 if trying to upgrade an agent that is unenrolling', async () => { - const kibanaVersion = await kibanaServer.version.get(); await supertest.post(`/api/fleet/agents/agent1/unenroll`).set('kbn-xsrf', 'xxx').send({ revoke: true, }); @@ -213,12 +257,11 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersion, + version: fleetServerVersion, }) .expect(400); }); it('should respond 400 if trying to upgrade an agent that is unenrolled', async () => { - const kibanaVersion = await kibanaServer.version.get(); await es.update({ id: 'agent1', refresh: 'wait_for', @@ -233,18 +276,17 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersion, + version: fleetServerVersion, }) .expect(400); }); it('should respond 400 if trying to upgrade an agent that is not upgradeable', async () => { - const kibanaVersion = await kibanaServer.version.get(); const res = await supertest .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') .send({ - version: kibanaVersion, + version: fleetServerVersion, }) .expect(400); expect(res.body.message).to.equal('agent agent1 is not upgradeable'); @@ -258,7 +300,6 @@ export default function (providerContext: FtrProviderContext) { is_managed: true, }); - const kibanaVersion = await kibanaServer.version.get(); await es.update({ id: 'agent1', refresh: 'wait_for', @@ -273,7 +314,7 @@ export default function (providerContext: FtrProviderContext) { const { body } = await supertest .post(`/api/fleet/agents/agent1/upgrade`) .set('kbn-xsrf', 'xxx') - .send({ version: kibanaVersion }) + .send({ version: fleetServerVersion }) .expect(400); expect(body.message).to.contain( 'Cannot upgrade agent agent1 in hosted agent policy policy1' @@ -284,7 +325,6 @@ export default function (providerContext: FtrProviderContext) { }); it('should respond 403 if user lacks fleet all permissions', async () => { - const kibanaVersion = await kibanaServer.version.get(); await es.update({ id: 'agent1', refresh: 'wait_for', @@ -300,7 +340,7 @@ export default function (providerContext: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .auth(testUsers.fleet_no_access.username, testUsers.fleet_no_access.password) .send({ - version: kibanaVersion, + version: fleetServerVersion, }) .expect(403); }); @@ -312,7 +352,7 @@ export default function (providerContext: FtrProviderContext) { beforeEach(async () => { await supertest.post(`/api/fleet/agent_policies`).set('kbn-xsrf', 'kibana').send({ name: 'Fleet Server policy 1', - policy_id: 'fleet-server-policy', + id: 'fleet-server-policy', namespace: 'default', has_fleet_server: true, }); @@ -568,7 +608,7 @@ export default function (providerContext: FtrProviderContext) { .send({ agents: 'active:true', version: fleetServerVersion, - batchSize: 2, + batchSize: 3, }) .expect(200); @@ -586,7 +626,7 @@ export default function (providerContext: FtrProviderContext) { await new Promise((resolve, reject) => { let attempts = 0; const intervalId = setInterval(async () => { - if (attempts > 2) { + if (attempts > 4) { clearInterval(intervalId); reject('action timed out'); } @@ -596,7 +636,7 @@ export default function (providerContext: FtrProviderContext) { } = await supertest.get(`/api/fleet/agents/action_status`).set('kbn-xsrf', 'xxx'); const action = actionStatuses.find((a: any) => a.actionId === actionId); // 2 upgradeable - if (action && action.nbAgentsActionCreated === 2) { + if (action && action.nbAgentsActionCreated === 2 && action.nbAgentsFailed === 3) { clearInterval(intervalId); await verifyActionResult(); resolve({}); @@ -976,7 +1016,7 @@ export default function (providerContext: FtrProviderContext) { }, }); // attempt to upgrade agent in hosted agent policy - const { body } = await supertest + await supertest .post(`/api/fleet/agents/bulk_upgrade`) .set('kbn-xsrf', 'xxx') .send({ @@ -985,15 +1025,6 @@ export default function (providerContext: FtrProviderContext) { }) .expect(200); - expect(body).to.eql({ - agent1: { - success: false, - error: - 'Cannot upgrade agent in hosted agent policy policy1 in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.', - }, - agent2: { success: true }, - }); - const [agent1data, agent2data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent1`), supertest.get(`/api/fleet/agents/agent2`), @@ -1001,6 +1032,13 @@ export default function (providerContext: FtrProviderContext) { expect(typeof agent1data.body.item.upgrade_started_at).to.be('undefined'); expect(typeof agent2data.body.item.upgrade_started_at).to.be('string'); + + const { body } = await supertest + .get(`/api/fleet/agents/action_status`) + .set('kbn-xsrf', 'xxx'); + const actionStatus = body.items[0]; + expect(actionStatus.status).to.eql('FAILED'); + expect(actionStatus.nbAgentsFailed).to.eql(1); }); it('enrolled in a hosted agent policy bulk upgrade with force flag should respond with 200 and update the agent SOs', async () => { @@ -1036,7 +1074,7 @@ export default function (providerContext: FtrProviderContext) { }, }); // attempt to upgrade agent in hosted agent policy - const { body } = await supertest + await supertest .post(`/api/fleet/agents/bulk_upgrade`) .set('kbn-xsrf', 'xxx') .send({ @@ -1045,11 +1083,6 @@ export default function (providerContext: FtrProviderContext) { force: true, }); - expect(body).to.eql({ - agent1: { success: true }, - agent2: { success: true }, - }); - const [agent1data, agent2data] = await Promise.all([ supertest.get(`/api/fleet/agents/agent1`), supertest.get(`/api/fleet/agents/agent2`), diff --git a/x-pack/test/fleet_api_integration/helpers.ts b/x-pack/test/fleet_api_integration/helpers.ts index 552c83d3ca890..d3b623d0426f3 100644 --- a/x-pack/test/fleet_api_integration/helpers.ts +++ b/x-pack/test/fleet_api_integration/helpers.ts @@ -69,6 +69,7 @@ export async function generateAgent( await es.index({ index: '.fleet-agents', + id, body: { id, active: true, @@ -79,6 +80,7 @@ export async function generateAgent( elastic: { agent: { version, + upgradeable: true, }, }, }, diff --git a/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_security.ts b/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_security.ts index 8f7fc4fe73062..3a33f14d682a6 100644 --- a/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_security.ts +++ b/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_security.ts @@ -6,10 +6,6 @@ */ import expect from '@kbn/expect'; -import { - createDashboardEditUrl, - DashboardConstants, -} from '@kbn/dashboard-plugin/public/dashboard_constants'; import { FtrProviderContext } from '../../../../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { @@ -32,6 +28,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const savedQueryManagementComponent = getService('savedQueryManagementComponent'); const kbnServer = getService('kibanaServer'); + const navigationArgs = { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, + }; + describe('dashboard feature controls security', () => { before(async () => { await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/logstash_functional'); @@ -97,14 +98,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`landing page shows "Create new Dashboard" button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.LANDING_PAGE_PATH, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardListingURL({ + args: navigationArgs, + }); await testSubjects.existOrFail('dashboardLandingPage', { timeout: config.get('timeouts.waitFor'), }); @@ -116,28 +112,17 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`create new dashboard shows addNew button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ args: navigationArgs }); await testSubjects.existOrFail('emptyDashboardWidget', { timeout: config.get('timeouts.waitFor'), }); }); it(`can view existing Dashboard`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-exist'), - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ + id: 'i-exist', + args: navigationArgs, + }); await testSubjects.existOrFail('embeddablePanelHeading-APie', { timeout: config.get('timeouts.waitFor'), }); @@ -307,14 +292,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`landing page doesn't show "Create new Dashboard" button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.LANDING_PAGE_PATH, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardListingURL({ + args: navigationArgs, + }); await testSubjects.existOrFail('dashboardLandingPage', { timeout: config.get('timeouts.waitFor'), }); @@ -322,38 +302,24 @@ 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 PageObjects.dashboard.gotoDashboardListingURL({ + args: navigationArgs, + }); await globalNav.badgeExistsOrFail('Read only'); }); it(`create new dashboard shows the read only warning`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ + args: navigationArgs, + }); await testSubjects.existOrFail('dashboardEmptyReadOnly', { timeout: 20000 }); }); it(`can view existing Dashboard`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-exist'), - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ + id: 'i-exist', + args: navigationArgs, + }); await testSubjects.existOrFail('embeddablePanelHeading-APie', { timeout: config.get('timeouts.waitFor'), }); @@ -438,14 +404,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`landing page doesn't show "Create new Dashboard" button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.LANDING_PAGE_PATH, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardListingURL({ + args: navigationArgs, + }); await testSubjects.existOrFail('dashboardLandingPage', { timeout: 10000 }); await testSubjects.missingOrFail('newItemButton'); }); @@ -455,26 +416,14 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`create new dashboard shows the read only warning`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ + args: navigationArgs, + }); await testSubjects.existOrFail('dashboardEmptyReadOnly', { timeout: 20000 }); }); it(`can view existing Dashboard`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-exist'), - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ id: 'i-exist', args: navigationArgs }); await testSubjects.existOrFail('embeddablePanelHeading-APie', { timeout: 10000 }); }); @@ -552,50 +501,24 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`landing page shows 403`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.LANDING_PAGE_PATH, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardListingURL({ + args: navigationArgs, + }); await PageObjects.error.expectForbidden(); }); it(`create new dashboard shows 403`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ args: navigationArgs }); await PageObjects.error.expectForbidden(); }); it(`edit dashboard for object which doesn't exist shows 403`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-dont-exist'), - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ id: 'i-dont-exist', args: navigationArgs }); await PageObjects.error.expectForbidden(); }); it(`edit dashboard for object which exists shows 403`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-exist'), - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } - ); + await PageObjects.dashboard.gotoDashboardURL({ id: 'i-exist', args: navigationArgs }); await PageObjects.error.expectForbidden(); }); }); diff --git a/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_spaces.ts b/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_spaces.ts index a702b7a716a15..ef8c83ec667ba 100644 --- a/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_spaces.ts +++ b/x-pack/test/functional/apps/dashboard/group1/feature_controls/dashboard_spaces.ts @@ -6,10 +6,6 @@ */ import expect from '@kbn/expect'; -import { - createDashboardEditUrl, - DashboardConstants, -} from '@kbn/dashboard-plugin/public/dashboard_constants'; import { FtrProviderContext } from '../../../../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { @@ -53,15 +49,13 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`landing page shows "Create new Dashboard" button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.LANDING_PAGE_PATH, - { + await PageObjects.dashboard.gotoDashboardListingURL({ + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await testSubjects.existOrFail('dashboardLandingPage', { timeout: config.get('timeouts.waitFor'), }); @@ -69,30 +63,27 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`create new dashboard shows addNew button`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { + await PageObjects.dashboard.gotoDashboardURL({ + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await testSubjects.existOrFail('emptyDashboardWidget', { timeout: config.get('timeouts.waitFor'), }); }); it(`can view existing Dashboard`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('8fba09d8-df3f-5aa1-83cc-65f7fbcbc0d9'), - { + await PageObjects.dashboard.gotoDashboardURL({ + id: '8fba09d8-df3f-5aa1-83cc-65f7fbcbc0d9', + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await testSubjects.existOrFail('embeddablePanelHeading-APie', { timeout: config.get('timeouts.waitFor'), }); @@ -125,41 +116,37 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`create new dashboard shows 404`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - DashboardConstants.CREATE_NEW_DASHBOARD_URL, - { + await PageObjects.dashboard.gotoDashboardURL({ + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await PageObjects.error.expectNotFound(); }); it(`edit dashboard for object which doesn't exist shows 404`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-dont-exist'), - { + await PageObjects.dashboard.gotoDashboardURL({ + id: 'i-dont-exist', + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await PageObjects.error.expectNotFound(); }); it(`edit dashboard for object which exists shows 404`, async () => { - await PageObjects.common.navigateToActualUrl( - 'dashboard', - createDashboardEditUrl('i-exist'), - { + await PageObjects.dashboard.gotoDashboardURL({ + id: 'i-exist', + args: { basePath: '/s/custom_space', ensureCurrentUrl: false, shouldLoginIfPrompted: false, - } - ); + }, + }); await PageObjects.error.expectNotFound(); }); }); diff --git a/x-pack/test/functional/apps/infra/home_page.ts b/x-pack/test/functional/apps/infra/home_page.ts index 6acaabcd5d207..1c0323808270d 100644 --- a/x-pack/test/functional/apps/infra/home_page.ts +++ b/x-pack/test/functional/apps/infra/home_page.ts @@ -14,8 +14,9 @@ const DATE_WITHOUT_DATA = DATES.metricsAndLogs.hosts.withoutData; export default ({ getPageObjects, getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); + const browser = getService('browser'); const retry = getService('retry'); - const pageObjects = getPageObjects(['common', 'infraHome', 'infraSavedViews']); + const pageObjects = getPageObjects(['common', 'header', 'infraHome', 'infraSavedViews']); const kibanaServer = getService('kibanaServer'); describe('Home page', function () { @@ -34,6 +35,22 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await pageObjects.common.navigateToApp('infraOps'); await pageObjects.infraHome.getNoMetricsIndicesPrompt(); }); + + it('renders the correct error page title', async () => { + await pageObjects.common.navigateToUrlWithBrowserHistory( + 'infraOps', + '/detail/host/test', + '', + { + ensureCurrentUrl: false, + } + ); + await pageObjects.infraHome.waitForLoading(); + await pageObjects.header.waitUntilLoadingHasFinished(); + + const documentTitle = await browser.getTitle(); + expect(documentTitle).to.contain('Uh oh - Observability - Elastic'); + }); }); describe('with metrics present', () => { @@ -47,6 +64,13 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await esArchiver.unload('x-pack/test/functional/es_archives/infra/metrics_and_logs') ); + it('renders the correct page title', async () => { + await pageObjects.header.waitUntilLoadingHasFinished(); + + const documentTitle = await browser.getTitle(); + expect(documentTitle).to.contain('Inventory - Infrastructure - Observability - Elastic'); + }); + it('renders an empty data prompt for dates with no data', async () => { await pageObjects.infraHome.goToTime(DATE_WITHOUT_DATA); await pageObjects.infraHome.getNoMetricsDataPrompt(); diff --git a/x-pack/test/functional/apps/infra/link_to.ts b/x-pack/test/functional/apps/infra/link_to.ts index ebfcb740961b1..05eccc8e57ebc 100644 --- a/x-pack/test/functional/apps/infra/link_to.ts +++ b/x-pack/test/functional/apps/infra/link_to.ts @@ -42,6 +42,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await retry.tryForTime(5000, async () => { const currentUrl = await browser.getCurrentUrl(); const parsedUrl = new URL(currentUrl); + const documentTitle = await browser.getTitle(); expect(parsedUrl.pathname).to.be('/app/logs/stream'); expect(parsedUrl.searchParams.get('logFilter')).to.be( @@ -51,6 +52,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { `(end:'${endDate}',position:(tiebreaker:0,time:${timestamp}),start:'${startDate}',streamLive:!f)` ); expect(parsedUrl.searchParams.get('sourceId')).to.be('default'); + expect(documentTitle).to.contain('Stream - Logs - Observability - Elastic'); }); }); }); diff --git a/x-pack/test/functional/apps/infra/logs_source_configuration.ts b/x-pack/test/functional/apps/infra/logs_source_configuration.ts index 56eed5ec4b635..38cc795034a22 100644 --- a/x-pack/test/functional/apps/infra/logs_source_configuration.ts +++ b/x-pack/test/functional/apps/infra/logs_source_configuration.ts @@ -16,6 +16,7 @@ const COMMON_REQUEST_HEADERS = { export default ({ getPageObjects, getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); + const browser = getService('browser'); const logsUi = getService('logsUi'); const infraSourceConfigurationForm = getService('infraSourceConfigurationForm'); const pageObjects = getPageObjects(['common', 'header', 'infraLogs']); @@ -49,6 +50,15 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await esArchiver.unload('x-pack/test/functional/es_archives/infra/metrics_and_logs'); }); + it('renders the correct page title', async () => { + await pageObjects.infraLogs.navigateToTab('settings'); + + await pageObjects.header.waitUntilLoadingHasFinished(); + const documentTitle = await browser.getTitle(); + + expect(documentTitle).to.contain('Settings - Logs - Observability - Elastic'); + }); + it('can change the log indices to a pattern that matches nothing', async () => { await pageObjects.infraLogs.navigateToTab('settings'); diff --git a/x-pack/test/functional/apps/infra/metrics_explorer.ts b/x-pack/test/functional/apps/infra/metrics_explorer.ts index fc620d9ba5665..4d6859a4e99e7 100644 --- a/x-pack/test/functional/apps/infra/metrics_explorer.ts +++ b/x-pack/test/functional/apps/infra/metrics_explorer.ts @@ -16,6 +16,7 @@ const timepickerFormat = 'MMM D, YYYY @ HH:mm:ss.SSS'; export default ({ getPageObjects, getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); + const browser = getService('browser'); const pageObjects = getPageObjects([ 'common', 'infraHome', @@ -42,6 +43,13 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); after(() => esArchiver.unload('x-pack/test/functional/es_archives/infra/metrics_and_logs')); + it('should render the correct page title', async () => { + const documentTitle = await browser.getTitle(); + expect(documentTitle).to.contain( + 'Metrics Explorer - Infrastructure - Observability - Elastic' + ); + }); + it('should have three metrics by default', async () => { const metrics = await pageObjects.infraMetricsExplorer.getMetrics(); expect(metrics.length).to.equal(3); diff --git a/x-pack/test/functional/apps/lens/group1/index.ts b/x-pack/test/functional/apps/lens/group1/index.ts index 717f33c60181e..c01a43ce8c6ab 100644 --- a/x-pack/test/functional/apps/lens/group1/index.ts +++ b/x-pack/test/functional/apps/lens/group1/index.ts @@ -77,6 +77,7 @@ export default ({ getService, loadTestFile, getPageObjects }: FtrProviderContext loadTestFile(require.resolve('./persistent_context')); loadTestFile(require.resolve('./table_dashboard')); loadTestFile(require.resolve('./table')); + loadTestFile(require.resolve('./text_based_languages')); } }); }; diff --git a/x-pack/test/functional/apps/lens/group1/table.ts b/x-pack/test/functional/apps/lens/group1/table.ts index 7bf9b49c53d8d..724efbe6c6c82 100644 --- a/x-pack/test/functional/apps/lens/group1/table.ts +++ b/x-pack/test/functional/apps/lens/group1/table.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { - const PageObjects = getPageObjects(['visualize', 'lens', 'common', 'header']); + const PageObjects = getPageObjects(['visualize', 'lens', 'common']); const listingTable = getService('listingTable'); const find = getService('find'); const retry = getService('retry'); @@ -91,14 +91,14 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should allow to sort by transposed columns', async () => { await PageObjects.lens.changeTableSortingBy(2, 'ascending'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); expect(await PageObjects.lens.getDatatableCellText(0, 2)).to.eql('17,246'); }); it('should show dynamic coloring feature for numeric columns', async () => { await PageObjects.lens.openDimensionEditor('lnsDatatable_metrics > lns-dimensionTrigger'); await PageObjects.lens.setTableDynamicColoring('text'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); const styleObj = await PageObjects.lens.getDatatableCellStyle(0, 2); expect(styleObj['background-color']).to.be(undefined); expect(styleObj.color).to.be('rgb(133, 189, 177)'); @@ -106,7 +106,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should allow to color cell background rather than text', async () => { await PageObjects.lens.setTableDynamicColoring('cell'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); const styleObj = await PageObjects.lens.getDatatableCellStyle(0, 2); expect(styleObj['background-color']).to.be('rgb(133, 189, 177)'); // should also set text color when in cell mode @@ -115,9 +115,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should open the palette panel to customize the palette look', async () => { await PageObjects.lens.openPalettePanel('lnsDatatable'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); await PageObjects.lens.changePaletteTo('temperature'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); const styleObj = await PageObjects.lens.getDatatableCellStyle(0, 2); expect(styleObj['background-color']).to.be('rgb(235, 239, 245)'); }); @@ -125,7 +125,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should keep the coloring consistent when changing mode', async () => { // Change mode from percent to number await testSubjects.click('lnsPalettePanel_dynamicColoring_rangeType_groups_number'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); // check that all remained the same const styleObj = await PageObjects.lens.getDatatableCellStyle(0, 2); expect(styleObj['background-color']).to.be('rgb(235, 239, 245)'); @@ -133,7 +133,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should keep the coloring consistent when moving to custom palette from default', async () => { await PageObjects.lens.changePaletteTo('custom'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); // check that all remained the same const styleObj = await PageObjects.lens.getDatatableCellStyle(0, 2); expect(styleObj['background-color']).to.be('rgb(235, 239, 245)'); @@ -149,7 +149,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }); // when clicking on another row will trigger a sorting + update await testSubjects.click('lnsPalettePanel_dynamicColoring_range_value_1'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); // pick a cell without color as is below the range const styleObj = await PageObjects.lens.getDatatableCellStyle(3, 3); expect(styleObj['background-color']).to.be(undefined); @@ -159,7 +159,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should allow the user to reverse the palette', async () => { await testSubjects.click('lnsPalettePanel_dynamicColoring_reverseColors'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); const styleObj = await PageObjects.lens.getDatatableCellStyle(1, 1); expect(styleObj['background-color']).to.be('rgb(168, 191, 218)'); // should also set text color when in cell mode @@ -169,7 +169,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should allow to show a summary table for metric columns', async () => { await PageObjects.lens.setTableSummaryRowFunction('sum'); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.waitForVisualization(); await PageObjects.lens.assertExactText( '[data-test-subj="lnsDataTable-footer-169.228.188.120-›-Average-of-bytes"]', 'Sum: 18,994' diff --git a/x-pack/test/functional/apps/lens/group1/text_based_languages.ts b/x-pack/test/functional/apps/lens/group1/text_based_languages.ts new file mode 100644 index 0000000000000..d4766916d0da8 --- /dev/null +++ b/x-pack/test/functional/apps/lens/group1/text_based_languages.ts @@ -0,0 +1,139 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DebugState } from '@elastic/charts'; +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const PageObjects = getPageObjects([ + 'visualize', + 'lens', + 'header', + 'unifiedSearch', + 'dashboard', + 'common', + ]); + const elasticChart = getService('elasticChart'); + const queryBar = getService('queryBar'); + const testSubjects = getService('testSubjects'); + const kibanaServer = getService('kibanaServer'); + const monacoEditor = getService('monacoEditor'); + + function assertMatchesExpectedData(state: DebugState) { + expect(state.axes?.x![0].labels.sort()).to.eql(['css', 'gif', 'jpg', 'php', 'png']); + } + + const defaultSettings = { + 'discover:enableSql': true, + }; + + async function switchToTextBasedLanguage(language: string) { + await PageObjects.visualize.navigateToNewVisualization(); + await PageObjects.visualize.clickVisType('lens'); + await PageObjects.lens.goToTimeRange(); + await elasticChart.setNewChartUiDebugFlag(true); + await PageObjects.lens.switchToTextBasedLanguage(language); + await PageObjects.header.waitUntilLoadingHasFinished(); + } + + describe('lens text based language tests', () => { + before(async () => { + await kibanaServer.uiSettings.replace(defaultSettings); + }); + it('should navigate to text based languages mode correctly', async () => { + await switchToTextBasedLanguage('SQL'); + expect(await testSubjects.exists('showQueryBarMenu')).to.be(false); + expect(await testSubjects.exists('addFilter')).to.be(false); + const textBasedQuery = await monacoEditor.getCodeEditorValue(); + expect(textBasedQuery).to.be('SELECT * FROM "log*"'); + }); + + it('should allow adding and using a field', async () => { + await monacoEditor.setCodeEditorValue( + 'SELECT extension, AVG("bytes") as average FROM "logstash-*" GROUP BY extension' + ); + await testSubjects.click('querySubmitButton'); + await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.switchToVisualization('lnsMetric'); + await PageObjects.lens.configureTextBasedLanguagesDimension({ + dimension: 'lnsMetric_primaryMetricDimensionPanel > lns-empty-dimension', + field: 'average', + }); + + await PageObjects.lens.waitForVisualization('mtrVis'); + const metricData = await PageObjects.lens.getMetricVisualizationData(); + expect(metricData[0].title).to.eql('average'); + }); + + it('should allow switching to another chart', async () => { + await testSubjects.click('querySubmitButton'); + await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.switchToVisualization('bar'); + await PageObjects.lens.configureTextBasedLanguagesDimension({ + dimension: 'lnsXY_xDimensionPanel > lns-empty-dimension', + field: 'extension', + }); + + await PageObjects.lens.configureTextBasedLanguagesDimension({ + dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', + field: 'average', + }); + + await PageObjects.lens.waitForVisualization('xyVisChart'); + const data = await PageObjects.lens.getCurrentChartDebugState('xyVisChart'); + assertMatchesExpectedData(data!); + }); + + it('should allow adding an text based languages chart to a dashboard', async () => { + await PageObjects.lens.switchToVisualization('lnsMetric'); + + await PageObjects.lens.waitForVisualization('mtrVis'); + await PageObjects.lens.removeDimension('lnsMetric_breakdownByDimensionPanel'); + await PageObjects.lens.waitForVisualization('mtrVis'); + const metricData = await PageObjects.lens.getMetricVisualizationData(); + expect(metricData[0].value).to.eql('5.7K'); + expect(metricData[0].title).to.eql('average'); + await PageObjects.lens.save('New text based languages viz', false, false, false, 'new'); + + await PageObjects.dashboard.waitForRenderComplete(); + expect(metricData[0].value).to.eql('5.7K'); + + const panelCount = await PageObjects.dashboard.getPanelCount(); + expect(panelCount).to.eql(1); + }); + + it('should allow saving the text based languages chart into a saved object', async () => { + await switchToTextBasedLanguage('SQL'); + await monacoEditor.setCodeEditorValue( + 'SELECT extension, AVG("bytes") as average FROM "logstash-*" GROUP BY extension' + ); + await testSubjects.click('querySubmitButton'); + await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.lens.configureTextBasedLanguagesDimension({ + dimension: 'lnsXY_xDimensionPanel > lns-empty-dimension', + field: 'extension', + }); + + await PageObjects.lens.configureTextBasedLanguagesDimension({ + dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', + field: 'average', + }); + await PageObjects.lens.waitForVisualization('xyVisChart'); + await PageObjects.lens.save('Lens with text based language'); + await PageObjects.lens.waitForVisualization('xyVisChart'); + const data = await PageObjects.lens.getCurrentChartDebugState('xyVisChart'); + assertMatchesExpectedData(data!); + }); + + it('should allow to return to the dataview mode', async () => { + await PageObjects.lens.switchDataPanelIndexPattern('logstash-*', true); + expect(await testSubjects.exists('addFilter')).to.be(true); + expect(await queryBar.getQueryString()).to.be(''); + }); + }); +} diff --git a/x-pack/test/functional/apps/lens/group2/tsdb.ts b/x-pack/test/functional/apps/lens/group2/tsdb.ts index 7a43fc47471a5..d19ab9d19db7d 100644 --- a/x-pack/test/functional/apps/lens/group2/tsdb.ts +++ b/x-pack/test/functional/apps/lens/group2/tsdb.ts @@ -119,7 +119,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await testSubjects.click('lns-indexPatternDimension-median'); await PageObjects.lens.waitForVisualization('xyVisChart'); await PageObjects.lens.assertEditorWarning( - '"Median of kubernetes.container.memory.available.bytes" does not work for all indices in the selected data view because it\'s using a function which is not supported on rolled up data. Please edit the visualization to use another function or change the time range.' + 'Median of kubernetes.container.memory.available.bytes uses a function that is unsupported by rolled up data. Select a different function or change the time range.' ); }); it('shows warnings in dashboards as well', async () => { @@ -127,7 +127,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.dashboard.waitForRenderComplete(); await PageObjects.lens.assertInlineWarning( - '"Median of kubernetes.container.memory.available.bytes" does not work for all indices in the selected data view because it\'s using a function which is not supported on rolled up data. Please edit the visualization to use another function or change the time range.' + 'Median of kubernetes.container.memory.available.bytes uses a function that is unsupported by rolled up data. Select a different function or change the time range.' ); }); it('still shows other warnings as toast', async () => { diff --git a/x-pack/test/functional/apps/lens/group3/index.ts b/x-pack/test/functional/apps/lens/group3/index.ts index 44365d5333d16..627e9d560ca21 100644 --- a/x-pack/test/functional/apps/lens/group3/index.ts +++ b/x-pack/test/functional/apps/lens/group3/index.ts @@ -86,7 +86,7 @@ export default ({ getService, loadTestFile, getPageObjects }: FtrProviderContext loadTestFile(require.resolve('./error_handling')); loadTestFile(require.resolve('./lens_tagging')); loadTestFile(require.resolve('./lens_reporting')); - loadTestFile(require.resolve('./tsvb_open_in_lens')); + loadTestFile(require.resolve('./open_in_lens')); // keep these two last in the group in this order because they are messing with the default saved objects loadTestFile(require.resolve('./rollup')); loadTestFile(require.resolve('./no_data')); diff --git a/x-pack/test/stack_functional_integration/services/index.js b/x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/index.ts similarity index 51% rename from x-pack/test/stack_functional_integration/services/index.js rename to x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/index.ts index e311dd8b38f7e..b279f0d8a93cd 100644 --- a/x-pack/test/stack_functional_integration/services/index.js +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/index.ts @@ -5,10 +5,10 @@ * 2.0. */ -import { services as xpackFunctionalServices } from '../../functional/services'; -import { EsArchiverProvider } from './es_archiver'; +import { FtrProviderContext } from '../../../../../ftr_provider_context'; -export const services = { - ...xpackFunctionalServices, - esArchiver: EsArchiverProvider, -}; +export default function ({ loadTestFile }: FtrProviderContext) { + describe('Agg based Vis to Lens', function () { + loadTestFile(require.resolve('./pie')); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/pie.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/pie.ts new file mode 100644 index 0000000000000..1640a6a14631d --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/agg_based/pie.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../../../ftr_provider_context'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const { visualize, visEditor, lens, timePicker, header } = getPageObjects([ + 'visualize', + 'lens', + 'visEditor', + 'timePicker', + 'header', + ]); + + const testSubjects = getService('testSubjects'); + const pieChart = getService('pieChart'); + + describe('Pie', function describeIndexTests() { + const isNewChartsLibraryEnabled = true; + + before(async () => { + await visualize.initTests(isNewChartsLibraryEnabled); + }); + + beforeEach(async () => { + await visualize.navigateToNewAggBasedVisualization(); + await visualize.clickPieChart(); + await visualize.clickNewSearch(); + await timePicker.setDefaultAbsoluteRange(); + }); + + it('should hide the "Edit Visualization in Lens" menu item if no split slices were defined', async () => { + const button = await testSubjects.exists('visualizeEditInLensButton'); + expect(button).to.eql(false); + }); + + it('should show the "Edit Visualization in Lens" menu item', async () => { + await visEditor.clickBucket('Split slices'); + await visEditor.selectAggregation('Terms'); + await visEditor.selectField('machine.os.raw'); + await header.waitUntilLoadingHasFinished(); + await visEditor.clickGo(isNewChartsLibraryEnabled); + + const button = await testSubjects.exists('visualizeEditInLensButton'); + expect(button).to.eql(true); + }); + + it('should convert to Lens', async () => { + const expectedTableData = ['ios', 'osx', 'win 7', 'win 8', 'win xp']; + await visEditor.clickBucket('Split slices'); + await visEditor.selectAggregation('Terms'); + await visEditor.selectField('machine.os.raw'); + await header.waitUntilLoadingHasFinished(); + await visEditor.clickGo(isNewChartsLibraryEnabled); + + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('partitionVisChart'); + + await pieChart.expectPieChartLabels(expectedTableData, isNewChartsLibraryEnabled); + }); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/index.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/index.ts new file mode 100644 index 0000000000000..b1d5a1cbb3c52 --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('Open in Lens', function () { + loadTestFile(require.resolve('./tsvb')); + loadTestFile(require.resolve('./agg_based')); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/dashboard.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/dashboard.ts new file mode 100644 index 0000000000000..bd74e109326bf --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/dashboard.ts @@ -0,0 +1,101 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../../../ftr_provider_context'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const { visualize, visualBuilder, lens, timeToVisualize, dashboard, canvas } = getPageObjects([ + 'visualBuilder', + 'visualize', + 'lens', + 'timeToVisualize', + 'dashboard', + 'canvas', + ]); + + const testSubjects = getService('testSubjects'); + const retry = getService('retry'); + const panelActions = getService('dashboardPanelActions'); + const dashboardAddPanel = getService('dashboardAddPanel'); + + describe('Dashboard to TSVB to Lens', function describeIndexTests() { + before(async () => { + await visualize.initTests(); + }); + + it('should convert a by value TSVB viz to a Lens viz', async () => { + await visualize.navigateToNewVisualization(); + await visualize.clickVisualBuilder(); + await visualBuilder.checkVisualBuilderIsPresent(); + await visualBuilder.resetPage(); + await testSubjects.click('visualizeSaveButton'); + + await timeToVisualize.saveFromModal('My TSVB to Lens viz 1', { + addToDashboard: 'new', + saveToLibrary: false, + }); + + await dashboard.waitForRenderComplete(); + const originalEmbeddableCount = await canvas.getEmbeddableCount(); + await panelActions.openContextMenu(); + await panelActions.clickEdit(); + + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('xyVisChart'); + await retry.try(async () => { + const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); + expect(await dimensions[1].getVisibleText()).to.be('Count of records'); + }); + + await lens.saveAndReturn(); + await retry.try(async () => { + const embeddableCount = await canvas.getEmbeddableCount(); + expect(embeddableCount).to.eql(originalEmbeddableCount); + }); + await panelActions.removePanel(); + }); + + it('should convert a by reference TSVB viz to a Lens viz', async () => { + await dashboardAddPanel.clickEditorMenuButton(); + await dashboardAddPanel.clickVisType('metrics'); + await testSubjects.click('visualizesaveAndReturnButton'); + // save it to library + const originalPanel = await testSubjects.find('embeddablePanelHeading-'); + await panelActions.saveToLibrary('My TSVB to Lens viz 2', originalPanel); + + await dashboard.waitForRenderComplete(); + const originalEmbeddableCount = await canvas.getEmbeddableCount(); + await panelActions.openContextMenu(); + await panelActions.clickEdit(); + + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('legacyMtrVis'); + await retry.try(async () => { + const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); + expect(await dimensions[1].getVisibleText()).to.be('Count of records'); + }); + + await lens.saveAndReturn(); + await retry.try(async () => { + const embeddableCount = await canvas.getEmbeddableCount(); + expect(embeddableCount).to.eql(originalEmbeddableCount); + }); + + const panel = await testSubjects.find(`embeddablePanelHeading-`); + const descendants = await testSubjects.findAllDescendant( + 'embeddablePanelNotification-ACTION_LIBRARY_NOTIFICATION', + panel + ); + expect(descendants.length).to.equal(0); + + await panelActions.removePanel(); + }); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/index.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/index.ts new file mode 100644 index 0000000000000..c786ed22c6a1a --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('TSVB to Lens', function () { + loadTestFile(require.resolve('./metric')); + loadTestFile(require.resolve('./timeseries')); + loadTestFile(require.resolve('./dashboard')); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/metric.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/metric.ts new file mode 100644 index 0000000000000..273473b67a31e --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/metric.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../../../ftr_provider_context'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const { visualize, visualBuilder, lens } = getPageObjects(['visualBuilder', 'visualize', 'lens']); + + const testSubjects = getService('testSubjects'); + + describe('Metric', function describeIndexTests() { + before(async () => { + await visualize.initTests(); + }); + + beforeEach(async () => { + await visualize.navigateToNewVisualization(); + await visualize.clickVisualBuilder(); + await visualBuilder.checkVisualBuilderIsPresent(); + await visualBuilder.resetPage(); + await visualBuilder.clickMetric(); + await visualBuilder.clickDataTab('metric'); + }); + + it('should show the "Edit Visualization in Lens" menu item', async () => { + const button = await testSubjects.exists('visualizeEditInLensButton'); + expect(button).to.eql(true); + }); + + it('should convert to Lens', async () => { + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('mtrVis'); + + const metricData = await lens.getMetricVisualizationData(); + expect(metricData[0].title).to.eql('Count of records'); + }); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/timeseries.ts b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/timeseries.ts new file mode 100644 index 0000000000000..17e3a6b1bee8a --- /dev/null +++ b/x-pack/test/functional/apps/lens/group3/open_in_lens/tsvb/timeseries.ts @@ -0,0 +1,87 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../../../ftr_provider_context'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const { visualize, visualBuilder, lens, header } = getPageObjects([ + 'visualBuilder', + 'visualize', + 'header', + 'lens', + ]); + + const testSubjects = getService('testSubjects'); + const retry = getService('retry'); + const find = getService('find'); + const filterBar = getService('filterBar'); + const queryBar = getService('queryBar'); + + describe('Time Series', function describeIndexTests() { + before(async () => { + await visualize.initTests(); + }); + + it('should show the "Edit Visualization in Lens" menu item for a count aggregation', async () => { + await visualize.navigateToNewVisualization(); + await visualize.clickVisualBuilder(); + await visualBuilder.checkVisualBuilderIsPresent(); + await visualBuilder.resetPage(); + const isMenuItemVisible = await find.existsByCssSelector( + '[data-test-subj="visualizeEditInLensButton"]' + ); + expect(isMenuItemVisible).to.be(true); + }); + + it('visualizes field to Lens and loads fields to the dimesion editor', async () => { + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('xyVisChart'); + await retry.try(async () => { + const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); + expect(dimensions).to.have.length(2); + expect(await dimensions[0].getVisibleText()).to.be('@timestamp'); + expect(await dimensions[1].getVisibleText()).to.be('Count of records'); + }); + }); + + it('navigates back to TSVB when the Back button is clicked', async () => { + const goBackBtn = await testSubjects.find('lnsApp_goBackToAppButton'); + goBackBtn.click(); + await visualBuilder.checkVisualBuilderIsPresent(); + await retry.try(async () => { + const actualCount = await visualBuilder.getRhythmChartLegendValue(); + expect(actualCount).to.be('56'); + }); + }); + + it('should preserve app filters in lens', async () => { + await filterBar.addFilter('extension', 'is', 'css'); + await header.waitUntilLoadingHasFinished(); + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('xyVisChart'); + + expect(await filterBar.hasFilter('extension', 'css')).to.be(true); + }); + + it('should preserve query in lens', async () => { + const goBackBtn = await testSubjects.find('lnsApp_goBackToAppButton'); + goBackBtn.click(); + await visualBuilder.checkVisualBuilderIsPresent(); + await queryBar.setQuery('machine.os : ios'); + await queryBar.submitQuery(); + await header.waitUntilLoadingHasFinished(); + const button = await testSubjects.find('visualizeEditInLensButton'); + await button.click(); + await lens.waitForVisualization('xyVisChart'); + + expect(await queryBar.getQueryString()).to.equal('machine.os : ios'); + }); + }); +} diff --git a/x-pack/test/functional/apps/lens/group3/tsvb_open_in_lens.ts b/x-pack/test/functional/apps/lens/group3/tsvb_open_in_lens.ts deleted file mode 100644 index a7acd8bf5ba1c..0000000000000 --- a/x-pack/test/functional/apps/lens/group3/tsvb_open_in_lens.ts +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; - -import { FtrProviderContext } from '../../../ftr_provider_context'; - -export default function ({ getPageObjects, getService }: FtrProviderContext) { - const { visualize, visualBuilder, header, lens, timeToVisualize, dashboard, canvas } = - getPageObjects([ - 'visualBuilder', - 'visualize', - 'header', - 'lens', - 'timeToVisualize', - 'dashboard', - 'canvas', - ]); - const testSubjects = getService('testSubjects'); - const find = getService('find'); - const dashboardAddPanel = getService('dashboardAddPanel'); - const panelActions = getService('dashboardPanelActions'); - const retry = getService('retry'); - const filterBar = getService('filterBar'); - const queryBar = getService('queryBar'); - - describe('TSVB to Lens', function describeIndexTests() { - before(async () => { - await visualize.initTests(); - }); - - describe('Time Series', () => { - it('should show the "Edit Visualization in Lens" menu item for a count aggregation', async () => { - await visualize.navigateToNewVisualization(); - await visualize.clickVisualBuilder(); - await visualBuilder.checkVisualBuilderIsPresent(); - await visualBuilder.resetPage(); - const isMenuItemVisible = await find.existsByCssSelector( - '[data-test-subj="visualizeEditInLensButton"]' - ); - expect(isMenuItemVisible).to.be(true); - }); - - it('visualizes field to Lens and loads fields to the dimesion editor', async () => { - const button = await testSubjects.find('visualizeEditInLensButton'); - await button.click(); - await lens.waitForVisualization('xyVisChart'); - await retry.try(async () => { - const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); - expect(dimensions).to.have.length(2); - expect(await dimensions[0].getVisibleText()).to.be('@timestamp'); - expect(await dimensions[1].getVisibleText()).to.be('Count of records'); - }); - }); - - it('navigates back to TSVB when the Back button is clicked', async () => { - const goBackBtn = await testSubjects.find('lnsApp_goBackToAppButton'); - goBackBtn.click(); - await visualBuilder.checkVisualBuilderIsPresent(); - await retry.try(async () => { - const actualCount = await visualBuilder.getRhythmChartLegendValue(); - expect(actualCount).to.be('56'); - }); - }); - - it('should preserve app filters in lens', async () => { - await filterBar.addFilter('extension', 'is', 'css'); - await header.waitUntilLoadingHasFinished(); - const button = await testSubjects.find('visualizeEditInLensButton'); - await button.click(); - await lens.waitForVisualization('xyVisChart'); - - expect(await filterBar.hasFilter('extension', 'css')).to.be(true); - }); - - it('should preserve query in lens', async () => { - const goBackBtn = await testSubjects.find('lnsApp_goBackToAppButton'); - goBackBtn.click(); - await visualBuilder.checkVisualBuilderIsPresent(); - await queryBar.setQuery('machine.os : ios'); - await queryBar.submitQuery(); - await header.waitUntilLoadingHasFinished(); - const button = await testSubjects.find('visualizeEditInLensButton'); - await button.click(); - await lens.waitForVisualization('xyVisChart'); - - expect(await queryBar.getQueryString()).to.equal('machine.os : ios'); - }); - }); - - describe('Metric', () => { - beforeEach(async () => { - await visualize.navigateToNewVisualization(); - await visualize.clickVisualBuilder(); - await visualBuilder.checkVisualBuilderIsPresent(); - await visualBuilder.resetPage(); - await visualBuilder.clickMetric(); - await visualBuilder.clickDataTab('metric'); - }); - - it('should hide the "Edit Visualization in Lens" menu item', async () => { - const button = await testSubjects.exists('visualizeEditInLensButton'); - expect(button).to.eql(false); - }); - }); - - describe('Dashboard to TSVB to Lens', () => { - it('should convert a by value TSVB viz to a Lens viz', async () => { - await visualize.navigateToNewVisualization(); - await visualize.clickVisualBuilder(); - await visualBuilder.checkVisualBuilderIsPresent(); - await visualBuilder.resetPage(); - await testSubjects.click('visualizeSaveButton'); - - await timeToVisualize.saveFromModal('My TSVB to Lens viz 1', { - addToDashboard: 'new', - saveToLibrary: false, - }); - - await dashboard.waitForRenderComplete(); - const originalEmbeddableCount = await canvas.getEmbeddableCount(); - await panelActions.openContextMenu(); - await panelActions.clickEdit(); - - const button = await testSubjects.find('visualizeEditInLensButton'); - await button.click(); - await lens.waitForVisualization('xyVisChart'); - await retry.try(async () => { - const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); - expect(await dimensions[1].getVisibleText()).to.be('Count of records'); - }); - - await lens.saveAndReturn(); - await retry.try(async () => { - const embeddableCount = await canvas.getEmbeddableCount(); - expect(embeddableCount).to.eql(originalEmbeddableCount); - }); - await panelActions.removePanel(); - }); - - it('should convert a by reference TSVB viz to a Lens viz', async () => { - await dashboardAddPanel.clickEditorMenuButton(); - await dashboardAddPanel.clickVisType('metrics'); - await testSubjects.click('visualizesaveAndReturnButton'); - // save it to library - const originalPanel = await testSubjects.find('embeddablePanelHeading-'); - await panelActions.saveToLibrary('My TSVB to Lens viz 2', originalPanel); - - await dashboard.waitForRenderComplete(); - const originalEmbeddableCount = await canvas.getEmbeddableCount(); - await panelActions.openContextMenu(); - await panelActions.clickEdit(); - - const button = await testSubjects.find('visualizeEditInLensButton'); - await button.click(); - await lens.waitForVisualization('legacyMtrVis'); - await retry.try(async () => { - const dimensions = await testSubjects.findAll('lns-dimensionTrigger'); - expect(await dimensions[1].getVisibleText()).to.be('Count of records'); - }); - - await lens.saveAndReturn(); - await retry.try(async () => { - const embeddableCount = await canvas.getEmbeddableCount(); - expect(embeddableCount).to.eql(originalEmbeddableCount); - }); - - const panel = await testSubjects.find(`embeddablePanelHeading-`); - const descendants = await testSubjects.findAllDescendant( - 'embeddablePanelNotification-ACTION_LIBRARY_NOTIFICATION', - panel - ); - expect(descendants.length).to.equal(0); - - await panelActions.removePanel(); - }); - }); - }); -} diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts index 2ba4ac6f08350..ea95525062700 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts @@ -13,7 +13,8 @@ export default function ({ getService }: FtrProviderContext) { const ml = getService('ml'); const editedDescription = 'Edited description'; - describe('classification creation', function () { + // FLAKY: https://github.com/elastic/kibana/issues/142102 + describe.skip('classification creation', function () { before(async () => { await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/ml/bm_classification'); await ml.testResources.createIndexPatternIfNeeded('ft_bank_marketing', '@timestamp'); @@ -92,7 +93,8 @@ export default function ({ getService }: FtrProviderContext) { }, ]; for (const testData of testDataList) { - describe(`${testData.suiteTitle}`, function () { + // FLAKY: https://github.com/elastic/kibana/issues/142102 + describe.skip(`${testData.suiteTitle}`, function () { after(async () => { await ml.api.deleteIndices(testData.destinationIndex); await ml.testResources.deleteIndexPatternByTitle(testData.destinationIndex); diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/cloning.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/cloning.ts index 3a33c95edba42..7d6cc5ea9881a 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/cloning.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/cloning.ts @@ -15,7 +15,8 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const ml = getService('ml'); - describe('jobs cloning supported by UI form', function () { + // FLAKY: https://github.com/elastic/kibana/issues/142118 + describe.skip('jobs cloning supported by UI form', function () { const testDataList: Array<{ suiteTitle: string; archive: string; @@ -135,7 +136,8 @@ export default function ({ getService }: FtrProviderContext) { }); for (const testData of testDataList) { - describe(`${testData.suiteTitle}`, function () { + // FLAKY: https://github.com/elastic/kibana/issues/142118 + describe.skip(`${testData.suiteTitle}`, function () { const cloneJobId = `${testData.job.id}_clone`; const cloneDestIndex = `${testData.job!.dest!.index}_clone`; 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 947cd82cdd342..fb04cd793d9d8 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 @@ -13,7 +13,8 @@ export default function ({ getService }: FtrProviderContext) { const ml = getService('ml'); const editedDescription = 'Edited description'; - describe('outlier detection creation', function () { + // FLAKY: https://github.com/elastic/kibana/issues/142083 + describe.skip('outlier detection creation', function () { before(async () => { await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/ml/ihp_outlier'); await ml.testResources.createIndexPatternIfNeeded('ft_ihp_outlier', '@timestamp'); @@ -108,7 +109,8 @@ export default function ({ getService }: FtrProviderContext) { ]; for (const testData of testDataList) { - describe(`${testData.suiteTitle}`, function () { + // FLAKY: https://github.com/elastic/kibana/issues/142083 + describe.skip(`${testData.suiteTitle}`, function () { after(async () => { await ml.api.deleteIndices(testData.destinationIndex); await ml.testResources.deleteIndexPatternByTitle(testData.destinationIndex); diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts index 7a84c41aa4a66..744b61a2a06ca 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts @@ -13,7 +13,8 @@ export default function ({ getService }: FtrProviderContext) { const ml = getService('ml'); const editedDescription = 'Edited description'; - describe('regression creation', function () { + // FLAKY: https://github.com/elastic/kibana/issues/142095 + describe.skip('regression creation', function () { before(async () => { await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/ml/egs_regression'); await ml.testResources.createIndexPatternIfNeeded('ft_egs_regression', '@timestamp'); @@ -86,7 +87,8 @@ export default function ({ getService }: FtrProviderContext) { ]; for (const testData of testDataList) { - describe(`${testData.suiteTitle}`, function () { + // FLAKY: https://github.com/elastic/kibana/issues/142095 + describe.skip(`${testData.suiteTitle}`, function () { after(async () => { await ml.api.deleteIndices(testData.destinationIndex); await ml.testResources.deleteIndexPatternByTitle(testData.destinationIndex); diff --git a/x-pack/test/functional/apps/ml/short_tests/index.ts b/x-pack/test/functional/apps/ml/short_tests/index.ts index f96d2b91ee0ef..d446a35933474 100644 --- a/x-pack/test/functional/apps/ml/short_tests/index.ts +++ b/x-pack/test/functional/apps/ml/short_tests/index.ts @@ -33,5 +33,6 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./model_management')); loadTestFile(require.resolve('./feature_controls')); loadTestFile(require.resolve('./settings')); + loadTestFile(require.resolve('./notifications')); }); } diff --git a/x-pack/test/functional/apps/ml/short_tests/notifications/index.ts b/x-pack/test/functional/apps/ml/short_tests/notifications/index.ts new file mode 100644 index 0000000000000..e026d44a67af2 --- /dev/null +++ b/x-pack/test/functional/apps/ml/short_tests/notifications/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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('Notifcations', function () { + this.tags(['ml', 'skipFirefox']); + + loadTestFile(require.resolve('./notification_list')); + }); +} diff --git a/x-pack/test/functional/apps/ml/short_tests/notifications/notification_list.ts b/x-pack/test/functional/apps/ml/short_tests/notifications/notification_list.ts new file mode 100644 index 0000000000000..c9ad8d2423ef8 --- /dev/null +++ b/x-pack/test/functional/apps/ml/short_tests/notifications/notification_list.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../../../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const PageObjects = getPageObjects(['common']); + const esArchiver = getService('esArchiver'); + const ml = getService('ml'); + const browser = getService('browser'); + + describe('Notifications list', function () { + before(async () => { + await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/ml/farequote'); + await ml.testResources.createIndexPatternIfNeeded('ft_farequote', '@timestamp'); + await ml.testResources.setKibanaTimeZoneToUTC(); + + // Prepare jobs to generate notifications + await Promise.all( + [ + { jobId: 'fq_001', spaceId: undefined }, + { jobId: 'fq_002', spaceId: 'space1' }, + ].map(async (v) => { + const datafeedConfig = ml.commonConfig.getADFqDatafeedConfig(v.jobId); + + await ml.api.createAnomalyDetectionJob( + ml.commonConfig.getADFqSingleMetricJobConfig(v.jobId), + v.spaceId + ); + await ml.api.openAnomalyDetectionJob(v.jobId); + await ml.api.createDatafeed(datafeedConfig, v.spaceId); + await ml.api.startDatafeed(datafeedConfig.datafeed_id); + }) + ); + + await ml.securityUI.loginAsMlPowerUser(); + await PageObjects.common.navigateToApp('ml', { + basePath: '', + }); + }); + + after(async () => { + await ml.api.cleanMlIndices(); + await ml.testResources.cleanMLSavedObjects(); + await ml.testResources.deleteIndexPatternByTitle('ft_farequote'); + }); + + it('displays a generic notification indicator', async () => { + await ml.notifications.assertNotificationIndicatorExist(); + }); + + it('opens the Notifications page', async () => { + await ml.navigation.navigateToNotifications(); + + await ml.notifications.table.waitForTableToLoad(); + await ml.notifications.table.assertRowsNumberPerPage(25); + }); + + it('does not show notifications from another space', async () => { + await ml.notifications.table.filterWithSearchString('Job created', 1); + }); + + it('display a number of errors in the notification indicator', async () => { + await ml.navigation.navigateToOverview(); + + const jobConfig = ml.commonConfig.getADFqSingleMetricJobConfig('fq_fail'); + jobConfig.analysis_config = { + bucket_span: '15m', + influencers: ['airline'], + detectors: [ + { function: 'mean', field_name: 'responsetime', partition_field_name: 'airline' }, + { function: 'min', field_name: 'responsetime', partition_field_name: 'airline' }, + { function: 'max', field_name: 'responsetime', partition_field_name: 'airline' }, + ], + }; + // Set extremely low memory limit to trigger an error + jobConfig.analysis_limits!.model_memory_limit = '1024kb'; + + const datafeedConfig = ml.commonConfig.getADFqDatafeedConfig(jobConfig.job_id); + + await ml.api.createAnomalyDetectionJob(jobConfig); + await ml.api.openAnomalyDetectionJob(jobConfig.job_id); + await ml.api.createDatafeed(datafeedConfig); + await ml.api.startDatafeed(datafeedConfig.datafeed_id); + await ml.api.waitForJobMemoryStatus(jobConfig.job_id, 'hard_limit'); + + // refresh the page to avoid 1m wait + await browser.refresh(); + await ml.notifications.assertNotificationErrorsCount(0); + }); + }); +} diff --git a/x-pack/test/functional/es_archives/banners/multispace/data.json b/x-pack/test/functional/es_archives/banners/multispace/data.json deleted file mode 100644 index fc0e0dc7b7eee..0000000000000 --- a/x-pack/test/functional/es_archives/banners/multispace/data.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "type": "doc", - "value": { - "id": "config:6.0.0", - "index": ".kibana", - "source": { - "config": { - "buildNum": 8467, - "dateFormat:tz": "UTC", - "defaultRoute": "http://example.com/evil" - }, - "type": "config" - } - } -} - -{ - "type": "doc", - "value": { - "id": "another-space:config:6.0.0", - "index": ".kibana", - "source": { - "namespace": "another-space", - "config": { - "buildNum": 8467, - "dateFormat:tz": "UTC", - "defaultRoute": "/app/canvas" - }, - "type": "config" - } - } -} - -{ - "type": "doc", - "value": { - "id": "space:default", - "index": ".kibana", - "source": { - "space": { - "description": "This is the default space!", - "name": "Default" - }, - "type": "space" - } - } -} - -{ - "type": "doc", - "value": { - "id": "space:another-space", - "index": ".kibana", - "source": { - "space": { - "description": "This is another space", - "name": "Another Space" - }, - "type": "space" - } - } -} diff --git a/x-pack/test/functional/es_archives/banners/multispace/mappings.json b/x-pack/test/functional/es_archives/banners/multispace/mappings.json deleted file mode 100644 index f813fca64c328..0000000000000 --- a/x-pack/test/functional/es_archives/banners/multispace/mappings.json +++ /dev/null @@ -1,248 +0,0 @@ -{ - "type": "index", - "value": { - "aliases": { - ".kibana": {} - }, - "index": ".kibana_1", - "mappings": { - "properties": { - "config": { - "dynamic": "true", - "properties": { - "buildNum": { - "type": "keyword" - }, - "dateFormat:tz": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "defaultRoute": { - "type": "keyword" - } - } - }, - "dashboard": { - "dynamic": "strict", - "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" - } - } - }, - "index-pattern": { - "dynamic": "strict", - "properties": { - "fieldFormatMap": { - "type": "text" - }, - "fields": { - "type": "text" - }, - "intervalName": { - "type": "keyword" - }, - "notExpandable": { - "type": "boolean" - }, - "sourceFilters": { - "type": "text" - }, - "timeFieldName": { - "type": "keyword" - }, - "title": { - "type": "text" - } - } - }, - "search": { - "dynamic": "strict", - "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": { - "dynamic": "strict", - "properties": { - "uuid": { - "type": "keyword" - } - } - }, - "space": { - "properties": { - "_reserved": { - "type": "boolean" - }, - "color": { - "type": "keyword" - }, - "description": { - "type": "text" - }, - "disabledFeatures": { - "type": "keyword" - }, - "initials": { - "type": "keyword" - }, - "name": { - "fields": { - "keyword": { - "ignore_above": 2048, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "spaceId": { - "type": "keyword" - }, - "type": { - "type": "keyword" - }, - "url": { - "dynamic": "strict", - "properties": { - "accessCount": { - "type": "long" - }, - "accessDate": { - "type": "date" - }, - "createDate": { - "type": "date" - }, - "url": { - "fields": { - "keyword": { - "ignore_above": 2048, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "visualization": { - "dynamic": "strict", - "properties": { - "description": { - "type": "text" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "savedSearchId": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - }, - "visState": { - "type": "text" - } - } - } - } - }, - "settings": { - "index": { - "number_of_replicas": "1", - "number_of_shards": "1" - } - } - } -} diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index 82820993e5715..56d5185a6583b 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -880,8 +880,15 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont /** * Changes the index pattern in the data panel */ - async switchDataPanelIndexPattern(dataViewTitle: string) { - await PageObjects.unifiedSearch.switchDataView('lns-dataView-switch-link', dataViewTitle); + async switchDataPanelIndexPattern( + dataViewTitle: string, + transitionFromTextBasedLanguages?: boolean + ) { + await PageObjects.unifiedSearch.switchDataView( + 'lns-dataView-switch-link', + dataViewTitle, + transitionFromTextBasedLanguages + ); await PageObjects.header.waitUntilLoadingHasFinished(); }, @@ -1297,6 +1304,35 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont await PageObjects.unifiedSearch.createNewDataView(name, true); }, + async switchToTextBasedLanguage(language: string) { + await testSubjects.click('lns-dataView-switch-link'); + await PageObjects.unifiedSearch.selectTextBasedLanguage(language); + }, + + async configureTextBasedLanguagesDimension(opts: { + dimension: string; + field: string; + keepOpen?: boolean; + palette?: string; + }) { + await retry.try(async () => { + if (!(await testSubjects.exists('lns-indexPattern-dimensionContainerClose'))) { + await testSubjects.click(opts.dimension); + } + await testSubjects.existOrFail('lns-indexPattern-dimensionContainerClose'); + }); + + await this.selectOptionFromComboBox('text-based-dimension-field', opts.field); + + if (opts.palette) { + await this.setPalette(opts.palette); + } + + if (!opts.keepOpen) { + await this.closeDimensionEditor(); + } + }, + /** resets visualization/layer or removes a layer */ async removeLayer(index: number = 0) { await retry.try(async () => { diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 07bd1f346cf25..62d46e644f173 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -273,6 +273,16 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { return state; }, + async getJobMemoryStatus(jobId: string): Promise<'hard_limit' | 'soft_limit' | 'ok'> { + const jobStats = await this.getADJobStats(jobId); + + expect(jobStats.jobs).to.have.length( + 1, + `Expected job stats to have exactly one job (got '${jobStats.length}')` + ); + return jobStats.jobs[0].model_size_stats.memory_status; + }, + async getADJobStats(jobId: string): Promise { log.debug(`Fetching anomaly detection job stats for job ${jobId}...`); const { body: jobStats, status } = await esSupertest.get( @@ -299,6 +309,27 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }); }, + async waitForJobMemoryStatus( + jobId: string, + expectedMemoryStatus: 'hard_limit' | 'soft_limit' | 'ok', + timeout: number = 2 * 60 * 1000 + ) { + await retry.waitForWithTimeout( + `job memory status to be ${expectedMemoryStatus}`, + timeout, + async () => { + const memoryStatus = await this.getJobMemoryStatus(jobId); + if (memoryStatus === expectedMemoryStatus) { + return true; + } else { + throw new Error( + `expected job memory status to be ${expectedMemoryStatus} but got ${memoryStatus}` + ); + } + } + ); + }, + async getDatafeedState(datafeedId: string): Promise { log.debug(`Fetching datafeed state for datafeed ${datafeedId}`); const { body: datafeedStats, status } = await esSupertest.get( @@ -576,6 +607,18 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { return response; }, + async hasNotifications(query: object) { + const body = await es.search({ + index: '.ml-notifications*', + body: { + size: 10000, + query, + }, + }); + + return body.hits.hits.length > 0; + }, + async adJobExist(jobId: string) { this.validateJobId(jobId); try { @@ -608,6 +651,24 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }); }, + async waitForJobNotificationsToIndex(jobId: string, timeout: number = 60 * 1000) { + await retry.waitForWithTimeout(`Notifications for '${jobId}' to exist`, timeout, async () => { + if ( + await this.hasNotifications({ + term: { + job_id: { + value: jobId, + }, + }, + }) + ) { + return true; + } else { + throw new Error(`expected '${jobId}' notifications to exist`); + } + }); + }, + async createAnomalyDetectionJob(jobConfig: Job, space?: string) { const jobId = jobConfig.job_id; log.debug( diff --git a/x-pack/test/functional/services/ml/common_table_service.ts b/x-pack/test/functional/services/ml/common_table_service.ts new file mode 100644 index 0000000000000..50a40ab43f35a --- /dev/null +++ b/x-pack/test/functional/services/ml/common_table_service.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { WebElementWrapper } from '../../../../../test/functional/services/lib/web_element_wrapper'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export type MlTableService = ReturnType; + +export function MlTableServiceProvider({ getPageObject, getService }: FtrProviderContext) { + const testSubjects = getService('testSubjects'); + const commonPage = getPageObject('common'); + + const TableService = class { + constructor( + public readonly tableTestSubj: string, + public readonly tableRowSubj: string, + public readonly columns: Array<{ id: string; testSubj: string }>, + public readonly searchInputSubj: string + ) {} + + public async assertTableLoaded() { + await testSubjects.existOrFail(`~${this.tableTestSubj} loaded`); + } + + public async assertTableLoading() { + await testSubjects.existOrFail(`~${this.tableTestSubj} loading`); + } + + public async parseTable() { + const table = await testSubjects.find(`~${this.tableTestSubj}`); + const $ = await table.parseDomContent(); + const rows = []; + + for (const tr of $.findTestSubjects(`~${this.tableRowSubj}`).toArray()) { + const $tr = $(tr); + + const rowObject = this.columns.reduce((acc, curr) => { + acc[curr.id] = $tr + .findTestSubject(curr.testSubj) + .find('.euiTableCellContent') + .text() + .trim(); + return acc; + }, {} as Record); + + rows.push(rowObject); + } + + return rows; + } + + public async assertRowsNumberPerPage(rowsNumber: 10 | 25 | 50 | 100) { + const textContent = await testSubjects.getVisibleText( + `~${this.tableTestSubj} > tablePaginationPopoverButton` + ); + expect(textContent).to.be(`Rows per page: ${rowsNumber}`); + } + + public async waitForTableToStartLoading() { + await testSubjects.existOrFail(`~${this.tableTestSubj}`, { timeout: 60 * 1000 }); + await testSubjects.existOrFail(`${this.tableTestSubj} loading`, { timeout: 30 * 1000 }); + } + + public async waitForTableToLoad() { + await testSubjects.existOrFail(`~${this.tableTestSubj}`, { timeout: 60 * 1000 }); + await testSubjects.existOrFail(`${this.tableTestSubj} loaded`, { timeout: 30 * 1000 }); + } + + async getSearchInput(): Promise { + return await testSubjects.find(this.searchInputSubj); + } + + public async assertSearchInputValue(expectedSearchValue: string) { + const searchBarInput = await this.getSearchInput(); + const actualSearchValue = await searchBarInput.getAttribute('value'); + expect(actualSearchValue).to.eql( + expectedSearchValue, + `Search input value should be '${expectedSearchValue}' (got '${actualSearchValue}')` + ); + } + + public async filterWithSearchString(queryString: string, expectedRowCount: number = 1) { + await this.waitForTableToLoad(); + const searchBarInput = await this.getSearchInput(); + await searchBarInput.clearValueWithKeyboard(); + await searchBarInput.type(queryString); + await commonPage.pressEnterKey(); + await this.assertSearchInputValue(queryString); + await this.waitForTableToStartLoading(); + await this.waitForTableToLoad(); + + const rows = await this.parseTable(); + + expect(rows).to.have.length( + expectedRowCount, + `Filtered table should have ${expectedRowCount} row(s) for filter '${queryString}' (got ${rows.length} matching items)` + ); + } + }; + + return { + getServiceInstance( + name: string, + tableTestSubj: string, + tableRowSubj: string, + columns: Array<{ id: string; testSubj: string }>, + searchInputSubj: string + ) { + Object.defineProperty(TableService, 'name', { value: name }); + return new TableService(tableTestSubj, tableRowSubj, columns, searchInputSubj); + }, + }; +} diff --git a/x-pack/test/functional/services/ml/common_ui.ts b/x-pack/test/functional/services/ml/common_ui.ts index 0d8ee7d11a8b1..ef69f909437c1 100644 --- a/x-pack/test/functional/services/ml/common_ui.ts +++ b/x-pack/test/functional/services/ml/common_ui.ts @@ -164,22 +164,27 @@ export function MachineLearningCommonUIProvider({ }, async setMultiSelectFilter(testDataSubj: string, fieldTypes: string[]) { - await testSubjects.clickWhenNotDisabledWithoutRetry(`${testDataSubj}-button`); - await testSubjects.existOrFail(`${testDataSubj}-popover`); - await testSubjects.existOrFail(`${testDataSubj}-searchInput`); - const searchBarInput = await testSubjects.find(`${testDataSubj}-searchInput`); + await retry.tryForTime(60 * 1000, async () => { + // escape popover + await browser.pressKeys(browser.keys.ESCAPE); - for (const fieldType of fieldTypes) { - await retry.tryForTime(5000, async () => { - await searchBarInput.clearValueWithKeyboard(); - await searchBarInput.type(fieldType); - if (!(await testSubjects.exists(`${testDataSubj}-option-${fieldType}-checked`))) { - await testSubjects.existOrFail(`${testDataSubj}-option-${fieldType}`); - await testSubjects.click(`${testDataSubj}-option-${fieldType}`); - await testSubjects.existOrFail(`${testDataSubj}-option-${fieldType}-checked`); - } - }); - } + await testSubjects.clickWhenNotDisabledWithoutRetry(`${testDataSubj}-button`); + await testSubjects.existOrFail(`${testDataSubj}-popover`); + await testSubjects.existOrFail(`${testDataSubj}-searchInput`); + const searchBarInput = await testSubjects.find(`${testDataSubj}-searchInput`); + + for (const fieldType of fieldTypes) { + await retry.tryForTime(5000, async () => { + await searchBarInput.clearValueWithKeyboard(); + await searchBarInput.type(fieldType); + if (!(await testSubjects.exists(`${testDataSubj}-option-${fieldType}-checked`))) { + await testSubjects.existOrFail(`${testDataSubj}-option-${fieldType}`); + await testSubjects.click(`${testDataSubj}-option-${fieldType}`); + await testSubjects.existOrFail(`${testDataSubj}-option-${fieldType}-checked`); + } + }); + } + }); // escape popover await browser.pressKeys(browser.keys.ESCAPE); diff --git a/x-pack/test/functional/services/ml/index.ts b/x-pack/test/functional/services/ml/index.ts index d8c6924ec4cfd..9452baa324898 100644 --- a/x-pack/test/functional/services/ml/index.ts +++ b/x-pack/test/functional/services/ml/index.ts @@ -59,6 +59,8 @@ import { MachineLearningJobAnnotationsProvider } from './job_annotations_table'; import { MlNodesPanelProvider } from './ml_nodes_list'; import { MachineLearningCasesProvider } from './cases'; import { AnomalyChartsProvider } from './anomaly_charts'; +import { NotificationsProvider } from './notifications'; +import { MlTableServiceProvider } from './common_table_service'; export function MachineLearningProvider(context: FtrProviderContext) { const commonAPI = MachineLearningCommonAPIProvider(context); @@ -123,6 +125,7 @@ export function MachineLearningProvider(context: FtrProviderContext) { const settingsFilterList = MachineLearningSettingsFilterListProvider(context, commonUI); const singleMetricViewer = MachineLearningSingleMetricViewerProvider(context, commonUI); const stackManagementJobs = MachineLearningStackManagementJobsProvider(context); + const tableService = MlTableServiceProvider(context); const testExecution = MachineLearningTestExecutionProvider(context); const testResources = MachineLearningTestResourcesProvider(context, api); const alerting = MachineLearningAlertingProvider(context, api, commonUI); @@ -130,6 +133,7 @@ export function MachineLearningProvider(context: FtrProviderContext) { const trainedModels = TrainedModelsProvider(context, commonUI); const trainedModelsTable = TrainedModelsTableProvider(context, commonUI); const mlNodesPanel = MlNodesPanelProvider(context); + const notifications = NotificationsProvider(context, commonUI, tableService); const cases = MachineLearningCasesProvider(context, swimLane, anomalyCharts); @@ -171,7 +175,9 @@ export function MachineLearningProvider(context: FtrProviderContext) { jobWizardMultiMetric, jobWizardPopulation, lensVisualizations, + mlNodesPanel, navigation, + notifications, overviewPage, securityCommon, securityUI, @@ -181,10 +187,10 @@ export function MachineLearningProvider(context: FtrProviderContext) { singleMetricViewer, stackManagementJobs, swimLane, + tableService, testExecution, testResources, trainedModels, trainedModelsTable, - mlNodesPanel, }; } diff --git a/x-pack/test/functional/services/ml/notifications.ts b/x-pack/test/functional/services/ml/notifications.ts new file mode 100644 index 0000000000000..2365717d7226b --- /dev/null +++ b/x-pack/test/functional/services/ml/notifications.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; +import { MlCommonUI } from './common_ui'; +import { MlTableService } from './common_table_service'; + +export function NotificationsProvider( + { getService }: FtrProviderContext, + mlCommonUI: MlCommonUI, + tableService: MlTableService +) { + const testSubjects = getService('testSubjects'); + + return { + async assertNotificationIndicatorExist(expectExist = true) { + if (expectExist) { + await testSubjects.existOrFail('mlNotificationsIndicator'); + } else { + await testSubjects.missingOrFail('mlNotificationsIndicator'); + } + }, + + async assertNotificationErrorsCount(expectedCount: number) { + const actualCount = await testSubjects.getVisibleText('mlNotificationErrorsIndicator'); + expect(actualCount).to.greaterThan(expectedCount); + }, + + table: tableService.getServiceInstance( + 'NotificationsTable', + 'mlNotificationsTable', + 'mlNotificationsTableRow', + [ + { id: 'timestamp', testSubj: 'mlNotificationTime' }, + { id: 'level', testSubj: 'mlNotificationLevel' }, + { id: 'job_type', testSubj: 'mlNotificationType' }, + { id: 'job_id', testSubj: 'mlNotificationEntity' }, + { id: 'message', testSubj: 'mlNotificationMessage' }, + ], + 'mlNotificationsSearchBarInput' + ), + }; +} diff --git a/x-pack/test/functional/services/ml/test_resources.ts b/x-pack/test/functional/services/ml/test_resources.ts index 4fccde6712e62..d1a7557caf2b1 100644 --- a/x-pack/test/functional/services/ml/test_resources.ts +++ b/x-pack/test/functional/services/ml/test_resources.ts @@ -46,6 +46,14 @@ export function MachineLearningTestResourcesProvider( await kibanaServer.uiSettings.unset('dateFormat:tz'); }, + async disableKibanaAnnouncements() { + await kibanaServer.uiSettings.update({ hideAnnouncements: true }); + }, + + async resetKibanaAnnouncements() { + await kibanaServer.uiSettings.unset('hideAnnouncements'); + }, + async savedObjectExistsById(id: string, objectType: SavedObjectType): Promise { const response = await supertest.get(`/api/saved_objects/${objectType}/${id}`); return response.status === 200; diff --git a/x-pack/test/functional_with_es_ssl/apps/cases/upgrade.ts b/x-pack/test/functional_with_es_ssl/apps/cases/upgrade.ts index cbbbb90c05abc..c1e2979d313bb 100644 --- a/x-pack/test/functional_with_es_ssl/apps/cases/upgrade.ts +++ b/x-pack/test/functional_with_es_ssl/apps/cases/upgrade.ts @@ -18,6 +18,7 @@ export default ({ getPageObject, getService }: FtrProviderContext) => { const supertest = getService('supertest'); const testSubjects = getService('testSubjects'); const find = getService('find'); + const toasts = getService('toasts'); const updateConnector = async (id: string, req: Record) => { const { body: connector } = await supertest @@ -74,6 +75,10 @@ export default ({ getPageObject, getService }: FtrProviderContext) => { }); describe('Case view page', function () { + it('does not show any error toasters', async () => { + expect(await toasts.getToastCount()).to.be(0); + }); + it('shows the title correctly', async () => { const title = await testSubjects.find('header-page-title'); expect(await title.getVisibleText()).equal('Upgrade test in Kibana'); @@ -275,6 +280,10 @@ export default ({ getPageObject, getService }: FtrProviderContext) => { it('shows the add comment button', async () => { await testSubjects.exists('submit-comment'); }); + + it('shows the assignees section', async () => { + await testSubjects.exists('case-view-assignees'); + }); }); }); }; diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts index 0abb9bd7a395e..cabbadb43ac57 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts @@ -88,12 +88,14 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.setValue('slackWebhookUrlInput', 'https://test.com'); await find.clickByCssSelector( - '[data-test-subj="edit-connector-flyout-save-close-btn"]:not(disabled)' + '[data-test-subj="edit-connector-flyout-save-btn"]:not(disabled)' ); const toastTitle = await pageObjects.common.closeToast(); expect(toastTitle).to.eql(`Updated '${updatedConnectorName}'`); + await testSubjects.click('euiFlyoutCloseButton'); + await pageObjects.triggersActionsUI.searchConnectors(updatedConnectorName); const searchResultsAfterEdit = await pageObjects.triggersActionsUI.getConnectorsList(); @@ -130,7 +132,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); await find.clickByCssSelector( - '[data-test-subj="edit-connector-flyout-cancel-btn"]:not(disabled)' + '[data-test-subj="edit-connector-flyout-close-btn"]:not(disabled)' ); }); @@ -158,7 +160,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); await find.clickByCssSelector( - '[data-test-subj="edit-connector-flyout-cancel-btn"]:not(disabled)' + '[data-test-subj="edit-connector-flyout-close-btn"]:not(disabled)' ); }); @@ -174,9 +176,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await find.clickByCssSelector('[data-test-subj="connectorsTableCell-name"] button'); await testSubjects.setValue('nameInput', 'some test name to cancel'); - await testSubjects.click('edit-connector-flyout-cancel-btn'); + await testSubjects.click('edit-connector-flyout-close-btn'); + await testSubjects.click('confirmModalConfirmButton'); - await find.waitForDeletedByCssSelector('[data-test-subj="edit-connector-flyout-cancel-btn"]'); + await find.waitForDeletedByCssSelector('[data-test-subj="edit-connector-flyout-close-btn"]'); await pageObjects.triggersActionsUI.searchConnectors(connectorName); @@ -265,7 +268,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await find.clickByCssSelector('[data-test-subj="connectorsTableCell-name"] button'); expect(await testSubjects.exists('preconfiguredBadge')).to.be(true); - expect(await testSubjects.exists('edit-connector-flyout-save-close-btn')).to.be(false); + expect(await testSubjects.exists('edit-connector-flyout-save-btn')).to.be(false); }); }); diff --git a/x-pack/test/osquery_cypress/artifact_manager.ts b/x-pack/test/osquery_cypress/artifact_manager.ts index bef18d0177220..7ee2680e21f83 100644 --- a/x-pack/test/osquery_cypress/artifact_manager.ts +++ b/x-pack/test/osquery_cypress/artifact_manager.ts @@ -6,5 +6,5 @@ */ export async function getLatestVersion(): Promise { - return '8.5.0-SNAPSHOT'; + return '8.6.0-SNAPSHOT'; } diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts index e857636d8f67a..123259cadf0c7 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts @@ -54,8 +54,7 @@ export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const testHistoryIndex = '.kibana_task_manager_test_result'; - // Failing: See https://github.com/elastic/kibana/issues/141002 - describe.skip('scheduling and running tasks', () => { + describe('scheduling and running tasks', () => { beforeEach(async () => { // clean up before each test return await supertest.delete('/api/sample_tasks').set('kbn-xsrf', 'xxx').expect(200); @@ -646,36 +645,36 @@ export default function ({ getService }: FtrProviderContext) { const historyItem = random(1, 100); const scheduledTask = await scheduleTask({ taskType: 'sampleTask', - schedule: { interval: '30m' }, + schedule: { interval: '1h' }, params: { historyItem }, }); await retry.try(async () => { expect((await historyDocs()).length).to.eql(1); - const tasks = (await currentTasks()).docs; + const task = await currentTask(scheduledTask.id); - expect(getTaskById(tasks, scheduledTask.id).enabled).to.eql(true); + expect(task.enabled).to.eql(true); }); // disable the task await bulkDisable([scheduledTask.id]); await retry.try(async () => { - const tasks = (await currentTasks()).docs; - - expect(getTaskById(tasks, scheduledTask.id).enabled).to.eql(false); + const task = await currentTask(scheduledTask.id); + expect(task.enabled).to.eql(false); }); // re-enable the task await bulkEnable([scheduledTask.id], true); await retry.try(async () => { - const tasks = (await currentTasks()).docs; - - expect(getTaskById(tasks, scheduledTask.id).enabled).to.eql(true); + const task = await currentTask(scheduledTask.id); - // should get a new document even tho original schedule interval was 30m - expect((await historyDocs()).length).to.eql(2); + expect(task.enabled).to.eql(true); + expect(Date.parse(task.scheduledAt)).to.be.greaterThan( + Date.parse(scheduledTask.scheduledAt) + ); + expect(Date.parse(task.runAt)).to.be.greaterThan(Date.parse(scheduledTask.runAt)); }); }); @@ -683,40 +682,33 @@ export default function ({ getService }: FtrProviderContext) { const historyItem = random(1, 100); const scheduledTask = await scheduleTask({ taskType: 'sampleTask', - schedule: { interval: '30m' }, + schedule: { interval: '1h' }, params: { historyItem }, }); await retry.try(async () => { expect((await historyDocs()).length).to.eql(1); - const tasks = (await currentTasks()).docs; - expect(getTaskById(tasks, scheduledTask.id).enabled).to.eql(true); + const task = await currentTask(scheduledTask.id); + expect(task.enabled).to.eql(true); }); // disable the task await bulkDisable([scheduledTask.id]); await retry.try(async () => { - const tasks = (await currentTasks()).docs; - - expect(getTaskById(tasks, scheduledTask.id).enabled).to.eql(false); + const task = await currentTask(scheduledTask.id); + expect(task.enabled).to.eql(false); }); // re-enable the task await bulkEnable([scheduledTask.id], false); await retry.try(async () => { - const tasks = (await currentTasks()).docs; - - const task = getTaskById(tasks, scheduledTask.id); + const task = await currentTask(scheduledTask.id); expect(task.enabled).to.eql(true); - - // task runAt should be set in the future by greater than 20 minutes - // this assumes it takes less than 10 minutes to disable and renable the task - // since the schedule interval is 30 minutes - expect(Date.parse(task.runAt) - Date.now()).to.be.greaterThan(10 * 60 * 1000); + expect(Date.parse(task.scheduledAt)).to.eql(Date.parse(scheduledTask.scheduledAt)); }); }); diff --git a/x-pack/test/rule_registry/security_and_spaces/tests/basic/search_strategy.ts b/x-pack/test/rule_registry/security_and_spaces/tests/basic/search_strategy.ts index a04899d68d585..11982a8b51425 100644 --- a/x-pack/test/rule_registry/security_and_spaces/tests/basic/search_strategy.ts +++ b/x-pack/test/rule_registry/security_and_spaces/tests/basic/search_strategy.ts @@ -110,24 +110,6 @@ export default ({ getService }: FtrProviderContext) => { const second = result.rawResponse.hits.hits[1].fields?.['kibana.alert.evaluation.value']; expect(first > second).to.be(true); }); - - it('should reject public requests', async () => { - const result = await secureBsearch.send({ - supertestWithoutAuth, - auth: { - username: logsOnlySpacesAll.username, - password: logsOnlySpacesAll.password, - }, - options: { - featureIds: [AlertConsumers.LOGS], - }, - strategy: 'privateRuleRegistryAlertsSearchStrategy', - }); - expect(result.statusCode).to.be(500); - expect(result.message).to.be( - `The privateRuleRegistryAlertsSearchStrategy search strategy is currently only available for internal use.` - ); - }); }); describe('siem', () => { diff --git a/x-pack/test/screenshot_creation/apps/ml_docs/index.ts b/x-pack/test/screenshot_creation/apps/ml_docs/index.ts index 1c12efc89caf7..806414939cd84 100644 --- a/x-pack/test/screenshot_creation/apps/ml_docs/index.ts +++ b/x-pack/test/screenshot_creation/apps/ml_docs/index.ts @@ -22,6 +22,7 @@ export default function ({ getPageObject, getService, loadTestFile }: FtrProvide before(async () => { await ml.testResources.installAllKibanaSampleData(); await ml.testResources.setKibanaTimeZoneToUTC(); + await ml.testResources.disableKibanaAnnouncements(); await browser.setWindowSize(1920, 1080); }); @@ -29,6 +30,7 @@ export default function ({ getPageObject, getService, loadTestFile }: FtrProvide await securityPage.forceLogout(); await ml.testResources.removeAllKibanaSampleData(); await ml.testResources.resetKibanaTimeZone(); + await ml.testResources.resetKibanaAnnouncements(); }); loadTestFile(require.resolve('./anomaly_detection')); diff --git a/x-pack/test/screenshot_creation/apps/response_ops_docs/index.ts b/x-pack/test/screenshot_creation/apps/response_ops_docs/index.ts index 64ed2599d65b4..e836e3e63c9b7 100644 --- a/x-pack/test/screenshot_creation/apps/response_ops_docs/index.ts +++ b/x-pack/test/screenshot_creation/apps/response_ops_docs/index.ts @@ -23,6 +23,7 @@ export default function ({ getPageObject, getService, loadTestFile }: FtrProvide before(async () => { await ml.testResources.installAllKibanaSampleData(); await ml.testResources.setKibanaTimeZoneToUTC(); + await ml.testResources.disableKibanaAnnouncements(); await browser.setWindowSize(1920, 1080); await securityPage.login( esTestConfig.getUrlParts().username, @@ -34,6 +35,7 @@ export default function ({ getPageObject, getService, loadTestFile }: FtrProvide await securityPage.forceLogout(); await ml.testResources.removeAllKibanaSampleData(); await ml.testResources.resetKibanaTimeZone(); + await ml.testResources.resetKibanaAnnouncements(); }); loadTestFile(require.resolve('./stack_cases')); diff --git a/x-pack/test/security_solution_cypress/config.ts b/x-pack/test/security_solution_cypress/config.ts index 982d52920e2ac..e77ab1fe4d489 100644 --- a/x-pack/test/security_solution_cypress/config.ts +++ b/x-pack/test/security_solution_cypress/config.ts @@ -49,9 +49,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { // See https://github.com/elastic/kibana/pull/125396 for details '--xpack.alerting.rules.minimumScheduleInterval.value=1s', '--xpack.ruleRegistry.unsafe.legacyMultiTenancy.enabled=true', - `--xpack.securitySolution.enableExperimental=${JSON.stringify([ - 'threatIntelligenceEnabled', - ])}`, + `--xpack.securitySolution.enableExperimental=${JSON.stringify([])}`, `--home.disableWelcomeScreen=true`, ], }, diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/responder.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/responder.ts index 9caf231089860..ddcbbc6251fdf 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/responder.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/responder.ts @@ -116,7 +116,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); }); - describe('from timeline', () => { + // FLAKY: https://github.com/elastic/kibana/issues/140546 + describe.skip('from timeline', () => { let timeline: TimelineResponse; before(async () => { diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.fixtures.ts b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.fixtures.ts index 281ba95d8e0cb..3a81ad1c71dcb 100644 --- a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.fixtures.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.fixtures.ts @@ -247,8 +247,8 @@ export function generateMetadataDocs(timestamp: number) { dataset: 'endpoint.metadata', }, host: { - hostname: 'rezzani-7.example.com', - name: 'rezzani-7.example.com', + hostname: 'Example-host-name-XYZ', + name: 'Example-host-name-XYZ', id: 'fc0ff548-feba-41b6-8367-65e8790d0eaf', ip: ['10.101.149.26', '2606:a000:ffc0:39:11ef:37b9:3371:578c'], mac: ['e2-6d-f9-0-46-2e'], @@ -399,8 +399,8 @@ export function generateMetadataDocs(timestamp: number) { }, host: { architecture: 'x86', - hostname: 'rezzani-7.example.com', - name: 'rezzani-7.example.com', + hostname: 'Example-host-name-XYZ', + name: 'Example-host-name-XYZ', id: 'fc0ff548-feba-41b6-8367-65e8790d0eaf', ip: ['10.101.149.26', '2606:a000:ffc0:39:11ef:37b9:3371:578c'], mac: ['e2-6d-f9-0-46-2e'], @@ -550,8 +550,8 @@ export function generateMetadataDocs(timestamp: number) { }, host: { architecture: 'x86', - hostname: 'rezzani-7.example.com', - name: 'rezzani-7.example.com', + hostname: 'Example-host-name-XYZ', + name: 'Example-host-name-XYZ', id: 'fc0ff548-feba-41b6-8367-65e8790d0eaf', ip: ['10.101.149.26', '2606:a000:ffc0:39:11ef:37b9:3371:578c'], mac: ['e2-6d-f9-0-46-2e'], diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts index 508aa8884fcfe..0ee6b44952577 100644 --- a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts @@ -259,6 +259,26 @@ export default function ({ getService }: FtrProviderContext) { expect(body.pageSize).to.eql(10); }); + it('metadata api should return the endpoint based on the agent hostname', async () => { + const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; + const targetAgentHostname = 'Example-host-name-XYZ'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `united.endpoint.host.hostname:${targetAgentHostname}`, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultHostId: string = body.data[0].metadata.host.id; + const resultElasticAgentName: string = body.data[0].metadata.host.hostname; + expect(resultHostId).to.eql(targetEndpointId); + expect(resultElasticAgentName).to.eql(targetAgentHostname); + expect(body.data.length).to.eql(1); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + it('metadata api should return all hosts when filter is empty string', async () => { const { body } = await supertest .get(HOST_METADATA_LIST_ROUTE) 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 1658bcbf6cd35..00dd89acbc9ef 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,7 +12,6 @@ import { REPO_ROOT } from '@kbn/utils'; import chalk from 'chalk'; import { esTestConfig, kbnTestConfig } from '@kbn/test'; import { TriggersActionsPageProvider } from '../../functional_with_es_ssl/page_objects/triggers_actions_ui_page'; -import { services } from '../services'; const log = new ToolingLog({ level: 'info', @@ -28,13 +27,14 @@ export default async ({ readConfigFile }) => { const xpackFunctionalConfig = await readConfigFile( require.resolve('../../functional/config.base.js') ); - const externalConf = consumeState(resolve(__dirname, stateFilePath)); + const externalConf = consumeState(resolve(__dirname, stateFilePath)) ?? { + TESTS_LIST: 'alerts', + }; process.env.stack_functional_integration = true; logAll(log); const settings = { ...xpackFunctionalConfig.getAll(), - services, pageObjects: { triggersActionsUI: TriggersActionsPageProvider, ...xpackFunctionalConfig.get('pageObjects'), @@ -53,6 +53,9 @@ export default async ({ readConfigFile }) => { ...xpackFunctionalConfig.get('kbnTestServer'), serverArgs: [...xpackFunctionalConfig.get('kbnTestServer.serverArgs')], }, + esArchiver: { + baseDirectory: INTEGRATION_TEST_ROOT, + }, testFiles: tests(externalConf.TESTS_LIST).map(prepend).map(logTest), // testFiles: ['alerts'].map(prepend).map(logTest), // If we need to do things like disable animations, we can do it in configure_start_kibana.sh, in the provisioner...which lives in the integration-test private repo diff --git a/x-pack/test/stack_functional_integration/services/es_archiver.js b/x-pack/test/stack_functional_integration/services/es_archiver.js deleted file mode 100644 index 821cf72e2c6bc..0000000000000 --- a/x-pack/test/stack_functional_integration/services/es_archiver.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import Path from 'path'; - -import { EsArchiver } from '@kbn/es-archiver'; -import { REPO_ROOT } from '@kbn/utils'; - -import { KibanaServer } from '@kbn/ftr-common-functional-services'; - -const INTEGRATION_TEST_ROOT = - process.env.WORKSPACE || Path.resolve(REPO_ROOT, '../integration-test'); - -export function EsArchiverProvider({ getService }) { - const config = getService('config'); - const client = getService('es'); - const log = getService('log'); - const kibanaServer = getService('kibanaServer'); - const retry = getService('retry'); - - const esArchiver = new EsArchiver({ - baseDir: INTEGRATION_TEST_ROOT, - client, - log, - kbnClient: kibanaServer, - }); - - KibanaServer.extendEsArchiver({ - esArchiver, - kibanaServer, - retry, - defaults: config.get('uiSettings.defaults'), - }); - - return esArchiver; -} diff --git a/x-pack/test/threat_intelligence_cypress/config.ts b/x-pack/test/threat_intelligence_cypress/config.ts index 8d638789b61ff..3fc305ab35f74 100644 --- a/x-pack/test/threat_intelligence_cypress/config.ts +++ b/x-pack/test/threat_intelligence_cypress/config.ts @@ -48,9 +48,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { // See https://github.com/elastic/kibana/pull/125396 for details '--xpack.alerting.rules.minimumScheduleInterval.value=1s', '--xpack.ruleRegistry.unsafe.legacyMultiTenancy.enabled=true', - `--xpack.securitySolution.enableExperimental=${JSON.stringify([ - 'threatIntelligenceEnabled', - ])}`, + `--xpack.securitySolution.enableExperimental=${JSON.stringify([])}`, `--home.disableWelcomeScreen=true`, ], }, diff --git a/yarn.lock b/yarn.lock index 374d3119e018e..804502ebeb4c7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2954,6 +2954,14 @@ version "0.0.0" uid "" +"@kbn/core-http-request-handler-context-server-internal@link:bazel-bin/packages/core/http/core-http-request-handler-context-server-internal": + version "0.0.0" + uid "" + +"@kbn/core-http-request-handler-context-server@link:bazel-bin/packages/core/http/core-http-request-handler-context-server": + version "0.0.0" + uid "" + "@kbn/core-http-router-server-internal@link:bazel-bin/packages/core/http/core-http-router-server-internal": version "0.0.0" uid "" @@ -3142,6 +3150,10 @@ version "0.0.0" uid "" +"@kbn/core-root-browser-internal@link:bazel-bin/packages/core/root/core-root-browser-internal": + version "0.0.0" + uid "" + "@kbn/core-saved-objects-api-browser@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser": version "0.0.0" uid "" @@ -3554,6 +3566,10 @@ version "0.0.0" uid "" +"@kbn/securitysolution-exception-list-components@link:bazel-bin/packages/kbn-securitysolution-exception-list-components": + version "0.0.0" + uid "" + "@kbn/securitysolution-hook-utils@link:bazel-bin/packages/kbn-securitysolution-hook-utils": version "0.0.0" uid "" @@ -4284,6 +4300,11 @@ resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.10.1.tgz#57b5cc6c7b4e55d8642c93d06401fb1af4839899" integrity sha512-P+SukKanjFY0ZhsK6wSVnQmxTP2eVPPE8OPSNuxaMYtgVzwJZgfGdwlYjf4RlRU4vLEw4ts2fsE2icG4nZ5ddQ== +"@octokit/openapi-types@^13.4.0": + version "13.4.0" + resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-13.4.0.tgz#06fe8fda93bf21bdd397fe7ef8805249efda6c06" + integrity sha512-2mVzW0X1+HDO3jF80/+QFZNzJiTefELKbhMu6yaBYbp/1gSMkVDm4rT472gJljTokWUlXaaE63m7WrWENhMDLw== + "@octokit/plugin-paginate-rest@^1.1.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-1.1.2.tgz#004170acf8c2be535aba26727867d692f7b488fc" @@ -4291,12 +4312,12 @@ dependencies: "@octokit/types" "^2.0.1" -"@octokit/plugin-paginate-rest@^3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-3.0.0.tgz#df779de686aeb21b5e776e4318defc33b0418566" - integrity sha512-fvw0Q5IXnn60D32sKeLIxgXCEZ7BTSAjJd8cFAE6QU5qUp0xo7LjFUjjX1J5D7HgN355CN4EXE4+Q1/96JaNUA== +"@octokit/plugin-paginate-rest@^4.0.0": + version "4.1.0" + resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-4.1.0.tgz#670ac9ac369448c69a2371bfcd7e2b37d95534f2" + integrity sha512-2O5K5fpajYG5g62wjzHR7/cWYaCA88CextAW3vFP+yoIHD0KEdlVMHfM5/i5LyV+JMmqiYW7w5qfg46FR+McNw== dependencies: - "@octokit/types" "^6.39.0" + "@octokit/types" "^7.1.1" "@octokit/plugin-request-log@^1.0.0", "@octokit/plugin-request-log@^1.0.4": version "1.0.4" @@ -4411,17 +4432,17 @@ once "^1.4.0" universal-user-agent "^4.0.0" -"@octokit/rest@^19.0.3": - version "19.0.3" - resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.3.tgz#b9a4e8dc8d53e030d611c053153ee6045f080f02" - integrity sha512-5arkTsnnRT7/sbI4fqgSJ35KiFaN7zQm0uQiQtivNQLI8RQx8EHwJCajcTUwmaCMNDg7tdCvqAnc7uvHHPxrtQ== +"@octokit/rest@^19.0.4": + version "19.0.4" + resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.4.tgz#fd8bed1cefffa486e9ae46a9dc608ce81bcfcbdd" + integrity sha512-LwG668+6lE8zlSYOfwPj4FxWdv/qFXYBpv79TWIQEpBLKA9D/IMcWsF/U9RGpA3YqMVDiTxpgVpEW3zTFfPFTA== dependencies: "@octokit/core" "^4.0.0" - "@octokit/plugin-paginate-rest" "^3.0.0" + "@octokit/plugin-paginate-rest" "^4.0.0" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^6.0.0" -"@octokit/types@6.40.0", "@octokit/types@^6.0.0", "@octokit/types@^6.0.3", "@octokit/types@^6.16.1", "@octokit/types@^6.39.0": +"@octokit/types@6.40.0", "@octokit/types@^6.0.0", "@octokit/types@^6.0.3", "@octokit/types@^6.16.1": version "6.40.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.40.0.tgz#f2e665196d419e19bb4265603cf904a820505d0e" integrity sha512-MFZOU5r8SwgJWDMhrLUSvyJPtVsqA6VnbVI3TNbsmw+Jnvrktzvq2fYES/6RiJA/5Ykdwq4mJmtlYUfW7CGjmw== @@ -4442,6 +4463,13 @@ dependencies: "@types/node" ">= 8" +"@octokit/types@^7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@octokit/types/-/types-7.1.1.tgz#a30fd6ca3279d59d532fa75583d65d93b7588e6d" + integrity sha512-Dx6cNTORyVaKY0Yeb9MbHksk79L8GXsihbG6PtWqTpkyA2TY1qBWE26EQXVG3dHwY9Femdd/WEeRUEiD0+H3TQ== + dependencies: + "@octokit/openapi-types" "^13.4.0" + "@openpgp/web-stream-tools@^0.0.10": version "0.0.10" resolved "https://registry.yarnpkg.com/@openpgp/web-stream-tools/-/web-stream-tools-0.0.10.tgz#4496390da9715c9bfc581ad144f9fb8a36a37775" @@ -7059,6 +7087,14 @@ version "0.0.0" uid "" +"@types/kbn__core-http-request-handler-context-server-internal@link:bazel-bin/packages/core/http/core-http-request-handler-context-server-internal/npm_module_types": + version "0.0.0" + uid "" + +"@types/kbn__core-http-request-handler-context-server@link:bazel-bin/packages/core/http/core-http-request-handler-context-server/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__core-http-router-server-internal@link:bazel-bin/packages/core/http/core-http-router-server-internal/npm_module_types": version "0.0.0" uid "" @@ -7251,6 +7287,10 @@ version "0.0.0" uid "" +"@types/kbn__core-root-browser-internal@link:bazel-bin/packages/core/root/core-root-browser-internal/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__core-saved-objects-api-browser@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser/npm_module_types": version "0.0.0" uid "" @@ -7647,6 +7687,10 @@ version "0.0.0" uid "" +"@types/kbn__securitysolution-exception-list-components@link:bazel-bin/packages/kbn-securitysolution-exception-list-components/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__securitysolution-hook-utils@link:bazel-bin/packages/kbn-securitysolution-hook-utils/npm_module_types": version "0.0.0" uid "" @@ -8138,10 +8182,10 @@ "@types/node" "*" form-data "^2.3.3" -"@types/node-forge@^1.0.4": - version "1.0.4" - resolved "https://registry.yarnpkg.com/@types/node-forge/-/node-forge-1.0.4.tgz#82df44938848e111463080286876e4cbe2b297a0" - integrity sha512-UpX8LTRrarEZPQvQqF5/6KQAqZolOVckH7txWdlsWIJrhBFFtwEUTcqeDouhrJl6t0F7Wg5cyUOAqqF8a6hheg== +"@types/node-forge@^1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@types/node-forge/-/node-forge-1.3.0.tgz#c655e951e0fb5c4b53c9f4746c2128d4f93002fd" + integrity sha512-yUsIEHG3d81E2c+akGjZAMdVcjbfqMzpMjvpebnTO7pEGfqxCtBzpRV52kR1RETtwJ9fHkLdEjtaM+uMKWpwFA== dependencies: "@types/node" "*" @@ -10478,18 +10522,18 @@ babel-runtime@6.x, babel-runtime@^6.26.0: core-js "^2.4.0" regenerator-runtime "^0.11.0" -backport@^8.9.2: - version "8.9.2" - resolved "https://registry.yarnpkg.com/backport/-/backport-8.9.2.tgz#cf0ec69428f9e86c20e1898dd77e8f6c12bf5afa" - integrity sha512-0ghVAwSssE0mamADGnsOybWn7RroKLSf9r4uU1IpAlxxa2zkRecfnGuSfEa5L1tQjh7lJwI/2i01JR6154r+qg== +backport@^8.9.4: + version "8.9.4" + resolved "https://registry.yarnpkg.com/backport/-/backport-8.9.4.tgz#2bbe58fd766ebda6c760852d029630a277098a54" + integrity sha512-REMiogdMQ+TOLQoEABttcCevbxJ14xlCMkHn7es0ZTeCleHz6T2bl93w/Fe+JIttuyZ0e8oPQW2DVe1feTG1pw== dependencies: - "@octokit/rest" "^19.0.3" + "@octokit/rest" "^19.0.4" axios "^0.27.2" dedent "^0.7.0" del "^6.1.1" - dotenv "^16.0.1" + dotenv "^16.0.2" find-up "^5.0.0" - graphql "^16.5.0" + graphql "^16.6.0" graphql-tag "^2.12.6" inquirer "^8.2.3" lodash "^4.17.21" @@ -10499,9 +10543,9 @@ backport@^8.9.2: strip-json-comments "^3.1.1" terminal-link "^2.1.1" utility-types "^3.10.0" - winston "^3.8.1" + winston "^3.8.2" yargs "^17.5.1" - yargs-parser "^21.0.1" + yargs-parser "^21.1.1" bail@^1.0.0: version "1.0.2" @@ -13642,10 +13686,10 @@ dotenv-expand@^5.1.0: resolved "https://registry.yarnpkg.com/dotenv-expand/-/dotenv-expand-5.1.0.tgz#3fbaf020bfd794884072ea26b1e9791d45a629f0" integrity sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA== -dotenv@^16.0.1: - version "16.0.1" - resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.0.1.tgz#8f8f9d94876c35dac989876a5d3a82a267fdce1d" - integrity sha512-1K6hR6wtk2FviQ4kEiSjFiH5rpzEVi8WW0x96aztHVMhEspNpc4DVOUTEHtEva5VThQ8IaBX1Pe4gSzpVVUsKQ== +dotenv@^16.0.2: + version "16.0.2" + resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.0.2.tgz#0b0f8652c016a3858ef795024508cddc4bffc5bf" + integrity sha512-JvpYKUmzQhYoIFgK2MOnF3bciIZoItIIoryihy0rIA+H4Jy0FmgyKYAHCTN98P5ybGSJcIFbh6QKeJdtZd1qhA== dotenv@^8.0.0: version "8.2.0" @@ -16136,10 +16180,10 @@ graphql-tag@^2.12.6: dependencies: tslib "^2.1.0" -graphql@^16.5.0: - version "16.5.0" - resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.5.0.tgz#41b5c1182eaac7f3d47164fb247f61e4dfb69c85" - integrity sha512-qbHgh8Ix+j/qY+a/ZcJnFQ+j8ezakqPiHwPiZhV/3PgGlgf96QMBB5/f2rkiC9sgLoy/xvT6TSiaf2nTHJh5iA== +graphql@^16.6.0: + version "16.6.0" + resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.6.0.tgz#c2dcffa4649db149f6282af726c8c83f1c7c5fdb" + integrity sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw== growly@^1.3.0: version "1.3.0" @@ -27906,10 +27950,10 @@ vega-label@~1.2.0: vega-scenegraph "^4.9.2" vega-util "^1.15.2" -vega-lite@^5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/vega-lite/-/vega-lite-5.3.0.tgz#b9b9ecd80e869e823e6848c67d0a8ad94954bdee" - integrity sha512-6giodZ/bJnWyLq6Gj4OyiDt7EndoGyC9f5xDQjo82yPpUiO4MuG9iiPMqR1SPKmG9/qPBf+klWQR0v/7Mgju0Q== +vega-lite@^5.5.0: + version "5.5.0" + resolved "https://registry.yarnpkg.com/vega-lite/-/vega-lite-5.5.0.tgz#07345713d538cd63278748ec119c261722be66ff" + integrity sha512-MQBJt/iaUegvhRTS/hZVWfMOSF5ai4awlR2qtwTgHd84bErf9v7GtaZ9ArhJqXCb+FizvZ2jatmoYCzovgAhkg== dependencies: "@types/clone" "~2.1.1" array-flat-polyfill "^1.0.1" @@ -28716,7 +28760,7 @@ winston-transport@^4.5.0: readable-stream "^3.6.0" triple-beam "^1.3.0" -winston@^3.3.3, winston@^3.8.1: +winston@^3.3.3: version "3.8.1" resolved "https://registry.yarnpkg.com/winston/-/winston-3.8.1.tgz#76f15b3478cde170b780234e0c4cf805c5a7fb57" integrity sha512-r+6YAiCR4uI3N8eQNOg8k3P3PqwAm20cLKlzVD9E66Ch39+LZC+VH1UKf9JemQj2B3QoUHfKD7Poewn0Pr3Y1w== @@ -28732,6 +28776,23 @@ winston@^3.3.3, winston@^3.8.1: triple-beam "^1.3.0" winston-transport "^4.5.0" +winston@^3.8.2: + version "3.8.2" + resolved "https://registry.yarnpkg.com/winston/-/winston-3.8.2.tgz#56e16b34022eb4cff2638196d9646d7430fdad50" + integrity sha512-MsE1gRx1m5jdTTO9Ld/vND4krP2To+lgDoMEHGGa4HIlAUyXJtfc7CxQcGXVyz2IBpw5hbFkj2b/AtUdQwyRew== + dependencies: + "@colors/colors" "1.5.0" + "@dabh/diagnostics" "^2.0.2" + async "^3.2.3" + is-stream "^2.0.0" + logform "^2.4.0" + one-time "^1.0.0" + readable-stream "^3.4.0" + safe-stable-stringify "^2.3.1" + stack-trace "0.0.x" + triple-beam "^1.3.0" + winston-transport "^4.5.0" + wkt-parser@^1.2.4: version "1.3.2" resolved "https://registry.yarnpkg.com/wkt-parser/-/wkt-parser-1.3.2.tgz#deeff04a21edc5b170a60da418e9ed1d1ab0e219" @@ -29000,11 +29061,16 @@ yargs-parser@^18.1.2: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-parser@^21.0.0, yargs-parser@^21.0.1: +yargs-parser@^21.0.0: version "21.0.1" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.0.1.tgz#0267f286c877a4f0f728fceb6f8a3e4cb95c6e35" integrity sha512-9BK1jFpLzJROCI5TzwZL/TU4gqjK5xiHV/RfWLOahrjAko/e4DJkRDZQXfvqAsiZzzYhgAzbgz6lg48jcm4GLg== +yargs-parser@^21.1.1: + version "21.1.1" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" + integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== + yargs-unparser@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-2.0.0.tgz#f131f9226911ae5d9ad38c432fe809366c2325eb"